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 |
---|---|---|---|---|---|---|
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract EventTokens is ERC1155, Ownable {
// TODO: Everything
// The below "GameItems' are from OpenZeppelin's example (https://docs.openzeppelin.com/contracts/3.x/erc1155)
// We should override
uint256 public constant GOLD = 0;
uint256 public constant SILVER = 1;
uint256 public constant THORS_HAMMER = 2;
uint256 public constant SWORD = 3;
uint256 public constant SHIELD = 4;
constructor() ERC1155("https://game.example/api/item/{id}.json") {
_mint(msg.sender, GOLD, 10**18, "");
_mint(msg.sender, SILVER, 10**27, "");
_mint(msg.sender, THORS_HAMMER, 1, "");
_mint(msg.sender, SWORD, 10**9, "");
_mint(msg.sender, SHIELD, 10**9, "");
}
}
| TODO: Everything The below "GameItems' are from OpenZeppelin's example (https:docs.openzeppelin.com/contracts/3.x/erc1155) We should override | contract EventTokens is ERC1155, Ownable {
uint256 public constant GOLD = 0;
uint256 public constant SILVER = 1;
uint256 public constant THORS_HAMMER = 2;
uint256 public constant SWORD = 3;
uint256 public constant SHIELD = 4;
_mint(msg.sender, GOLD, 10**18, "");
_mint(msg.sender, SILVER, 10**27, "");
_mint(msg.sender, THORS_HAMMER, 1, "");
_mint(msg.sender, SWORD, 10**9, "");
_mint(msg.sender, SHIELD, 10**9, "");
}
| 7,234,277 | [
1,
6241,
30,
26553,
1021,
5712,
315,
12496,
3126,
11,
854,
628,
3502,
62,
881,
84,
292,
267,
1807,
3454,
261,
4528,
30,
8532,
18,
3190,
94,
881,
84,
292,
267,
18,
832,
19,
16351,
87,
19,
23,
18,
92,
19,
12610,
2499,
2539,
13,
1660,
1410,
3849,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
2587,
5157,
353,
4232,
39,
2499,
2539,
16,
14223,
6914,
288,
203,
225,
2254,
5034,
1071,
5381,
611,
11846,
273,
374,
31,
203,
225,
2254,
5034,
1071,
5381,
348,
2627,
2204,
273,
404,
31,
203,
225,
2254,
5034,
1071,
5381,
7662,
14006,
67,
44,
2192,
20969,
273,
576,
31,
203,
225,
2254,
5034,
1071,
5381,
348,
7952,
273,
890,
31,
203,
225,
2254,
5034,
1071,
5381,
6122,
45,
5192,
273,
1059,
31,
203,
203,
565,
389,
81,
474,
12,
3576,
18,
15330,
16,
611,
11846,
16,
1728,
636,
2643,
16,
1408,
1769,
203,
565,
389,
81,
474,
12,
3576,
18,
15330,
16,
348,
2627,
2204,
16,
1728,
636,
5324,
16,
1408,
1769,
203,
565,
389,
81,
474,
12,
3576,
18,
15330,
16,
7662,
14006,
67,
44,
2192,
20969,
16,
404,
16,
1408,
1769,
203,
565,
389,
81,
474,
12,
3576,
18,
15330,
16,
348,
7952,
16,
1728,
636,
29,
16,
1408,
1769,
203,
565,
389,
81,
474,
12,
3576,
18,
15330,
16,
6122,
45,
5192,
16,
1728,
636,
29,
16,
1408,
1769,
203,
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
] |
./partial_match/56/0x2A9e0645c6c34747C94DEDce383a73F789dB6193/sources/CommunityFund.sol | * @dev This contract will collect vesting Shares, stake to the Boardroom and rebalance MDO, BUSD, WBNB according to DAO./ governance flags price Pancakeswap DAO parameters - https:docs.midasdollar.fi/DAO | contract CommunityFund {
using SafeERC20 for IERC20;
using SafeMath for uint256;
address public operator;
bool public initialized = false;
address public dollar = address(0x35e869B7456462b81cdB5e6e42434bD27f3F788c);
address public share = address(0x242E46490397ACCa94ED930F2C4EdF16250237fa);
address public bond = address(0xCaD2109CC2816D47a796cB7a0B57988EC7611541);
address public busd = address(0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56);
address public usdt = address(0x55d398326f99059fF775485246999027B3197955);
address public bdo = address(0x190b589cf9Fb8DDEabBFeae36a813FFb2A702454);
address public bcash = address(0xc2161d47011C4065648ab9cDFd0071094228fa09);
address public wbnb = address(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c);
address public boardroom = address(0xFF0b41ad7a85430FEbBC5220fd4c7a68013F2C0d);
address public dollarOracle = address(0x26593B4E6a803aac7f39955bd33C6826f266D7Fc);
address public treasury = address(0xD3372603Db4087FF5D797F91839c0Ca6b9aF294a);
IUniswapV2Router public pancakeRouter = IUniswapV2Router(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F);
mapping(address => mapping(address => address[])) public uniswapPaths;
uint256[] public expansionPercent;
uint256[] public contractionPercent;
address public strategist;
address public shareRewardPool = address(0xecC17b190581C60811862E5dF8c9183dA98BD08a);
event Initialized(address indexed executor, uint256 at);
event SwapToken(address inputToken, address outputToken, uint256 amount);
event BoughtBonds(uint256 amount);
event RedeemedBonds(uint256 amount);
event ExecuteTransaction(address indexed target, uint256 value, string signature, bytes data);
modifier onlyOperator() {
require(operator == msg.sender, "!operator");
_;
}
modifier onlyStrategist() {
require(strategist == msg.sender || operator == msg.sender, "!strategist");
_;
}
modifier notInitialized() {
require(!initialized, "initialized");
_;
}
modifier checkPublicAllow() {
require(publicAllowed || msg.sender == operator, "!operator nor !publicAllowed");
_;
}
function initialize(
address _dollar,
address _bond,
address _share,
address _busd,
address _wbnb,
address _boardroom,
address _dollarOracle,
address _treasury,
IUniswapV2Router _pancakeRouter
) public notInitialized {
dollar = _dollar;
bond = _bond;
share = _share;
busd = _busd;
wbnb = _wbnb;
boardroom = _boardroom;
dollarOracle = _dollarOracle;
treasury = _treasury;
pancakeRouter = _pancakeRouter;
publicAllowed = true;
initialized = true;
operator = msg.sender;
strategist = msg.sender;
emit Initialized(msg.sender, block.number);
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function setStrategist(address _strategist) external onlyOperator {
strategist = _strategist;
}
function setTreasury(address _treasury) external onlyOperator {
treasury = _treasury;
}
function setShareRewardPool(address _shareRewardPool) external onlyOperator {
shareRewardPool = _shareRewardPool;
}
function setShareRewardPoolId(address _tokenB, uint256 _pid) external onlyStrategist {
shareRewardPoolId[_tokenB] = _pid;
}
function setLpPairAddress(address _tokenB, address _lpAdd) external onlyStrategist {
lpPairAddress[_tokenB] = _lpAdd;
}
function setDollarOracle(address _dollarOracle) external onlyOperator {
dollarOracle = _dollarOracle;
}
function setPublicAllowed(bool _publicAllowed) external onlyStrategist {
publicAllowed = _publicAllowed;
}
function setExpansionPercent(
uint256 _dollarPercent,
uint256 _busdPercent,
uint256 _wbnbPercent
) external onlyStrategist {
require(_dollarPercent.add(_busdPercent).add(_wbnbPercent) == 10000, "!100%");
expansionPercent[0] = _dollarPercent;
expansionPercent[1] = _busdPercent;
expansionPercent[2] = _wbnbPercent;
}
function setContractionPercent(
uint256 _dollarPercent,
uint256 _busdPercent,
uint256 _wbnbPercent
) external onlyStrategist {
require(_dollarPercent.add(_busdPercent).add(_wbnbPercent) == 10000, "!100%");
contractionPercent[0] = _dollarPercent;
contractionPercent[1] = _busdPercent;
contractionPercent[2] = _wbnbPercent;
}
function setMaxAmountToTrade(
uint256 _dollarAmount,
uint256 _busdAmount,
uint256 _wbnbAmount
) external onlyStrategist {
maxAmountToTrade[dollar] = _dollarAmount;
maxAmountToTrade[busd] = _busdAmount;
maxAmountToTrade[wbnb] = _wbnbAmount;
}
function setDollarPriceToSell(uint256 _dollarPriceToSell) external onlyStrategist {
dollarPriceToSell = _dollarPriceToSell;
}
function setDollarPriceToBuy(uint256 _dollarPriceToBuy) external onlyStrategist {
dollarPriceToBuy = _dollarPriceToBuy;
}
function setUnirouterPath(
address _input,
address _output,
address[] memory _path
) external onlyStrategist {
uniswapPaths[_input][_output] = _path;
}
function setTokenAddresses(
address _busd,
address _usdt,
address _bdo,
address _bcash,
address _wbnb
) external onlyOperator {
busd = _busd;
usdt = _usdt;
bdo = _bdo;
bcash = _bcash;
wbnb = _wbnb;
}
function withdrawShare(uint256 _amount) external onlyStrategist {
IBoardroom(boardroom).withdraw(_amount);
}
function exitBoardroom() external onlyStrategist {
IBoardroom(boardroom).exit();
}
function grandFund(
address _token,
uint256 _amount,
address _to
) external onlyOperator {
IERC20(_token).transfer(_to, _amount);
}
function earned() public view returns (uint256) {
return IBoardroom(boardroom).earned(address(this));
}
function tokenBalances()
public
view
returns (
uint256 _dollarBal,
uint256 _busdBal,
uint256 _wbnbBal,
uint256 _totalBal
)
{
_dollarBal = IERC20(dollar).balanceOf(address(this));
_busdBal = IERC20(busd).balanceOf(address(this));
_wbnbBal = IERC20(wbnb).balanceOf(address(this));
_totalBal = _dollarBal.add(_busdBal).add(_wbnbBal);
}
function tokenPercents()
public
view
returns (
uint256 _dollarPercent,
uint256 _busdPercent,
uint256 _wbnbPercent
)
{
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
_dollarPercent = _dollarBal.mul(10000).div(_totalBal);
_busdPercent = _busdBal.mul(10000).div(_totalBal);
_wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
}
}
function tokenPercents()
public
view
returns (
uint256 _dollarPercent,
uint256 _busdPercent,
uint256 _wbnbPercent
)
{
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
_dollarPercent = _dollarBal.mul(10000).div(_totalBal);
_busdPercent = _busdBal.mul(10000).div(_totalBal);
_wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
}
}
function getDollarPrice() public view returns (uint256 dollarPrice) {
try IOracle(dollarOracle).consult(dollar, 1e18) returns (uint144 price) {
return uint256(price);
revert("failed to consult price");
}
}
function getDollarPrice() public view returns (uint256 dollarPrice) {
try IOracle(dollarOracle).consult(dollar, 1e18) returns (uint144 price) {
return uint256(price);
revert("failed to consult price");
}
}
} catch {
function getDollarUpdatedPrice() public view returns (uint256 _dollarPrice) {
try IOracle(dollarOracle).twap(dollar, 1e18) returns (uint144 price) {
return uint256(price);
revert("failed to consult price");
}
}
function getDollarUpdatedPrice() public view returns (uint256 _dollarPrice) {
try IOracle(dollarOracle).twap(dollar, 1e18) returns (uint144 price) {
return uint256(price);
revert("failed to consult price");
}
}
} catch {
function collectShareRewards() public checkPublicAllow {
if (IShare(share).unclaimedTreasuryFund() > 0) {
IShare(share).claimRewards();
}
}
function collectShareRewards() public checkPublicAllow {
if (IShare(share).unclaimedTreasuryFund() > 0) {
IShare(share).claimRewards();
}
}
function claimAndRestake() public checkPublicAllow {
if (IBoardroom(boardroom).canClaimReward(address(this))) {
if (earned() > 0) {
IBoardroom(boardroom).claimReward();
}
uint256 _shareBal = IERC20(share).balanceOf(address(this));
if (_shareBal > 0) {
IERC20(share).safeApprove(boardroom, 0);
IERC20(share).safeApprove(boardroom, _shareBal);
IBoardroom(boardroom).stake(_shareBal);
}
}
}
function claimAndRestake() public checkPublicAllow {
if (IBoardroom(boardroom).canClaimReward(address(this))) {
if (earned() > 0) {
IBoardroom(boardroom).claimReward();
}
uint256 _shareBal = IERC20(share).balanceOf(address(this));
if (_shareBal > 0) {
IERC20(share).safeApprove(boardroom, 0);
IERC20(share).safeApprove(boardroom, _shareBal);
IBoardroom(boardroom).stake(_shareBal);
}
}
}
function claimAndRestake() public checkPublicAllow {
if (IBoardroom(boardroom).canClaimReward(address(this))) {
if (earned() > 0) {
IBoardroom(boardroom).claimReward();
}
uint256 _shareBal = IERC20(share).balanceOf(address(this));
if (_shareBal > 0) {
IERC20(share).safeApprove(boardroom, 0);
IERC20(share).safeApprove(boardroom, _shareBal);
IBoardroom(boardroom).stake(_shareBal);
}
}
}
function claimAndRestake() public checkPublicAllow {
if (IBoardroom(boardroom).canClaimReward(address(this))) {
if (earned() > 0) {
IBoardroom(boardroom).claimReward();
}
uint256 _shareBal = IERC20(share).balanceOf(address(this));
if (_shareBal > 0) {
IERC20(share).safeApprove(boardroom, 0);
IERC20(share).safeApprove(boardroom, _shareBal);
IBoardroom(boardroom).stake(_shareBal);
}
}
}
function rebalance() public checkPublicAllow {
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
uint256 _dollarPercent = _dollarBal.mul(10000).div(_totalBal);
uint256 _busdPercent = _busdBal.mul(10000).div(_totalBal);
uint256 _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
uint256 _dollarPrice = getDollarUpdatedPrice();
if (_dollarPrice >= dollarPriceToSell) {
if (_dollarPercent > expansionPercent[0]) {
uint256 _sellingMdo = _dollarBal.mul(_dollarPercent.sub(expansionPercent[0])).div(10000);
if (_busdPercent >= expansionPercent[1]) {
if (_wbnbPercent < expansionPercent[2]) {
_swapToken(dollar, wbnb, _sellingMdo);
if (_busdPercent.sub(expansionPercent[1]) <= _wbnbPercent.sub(expansionPercent[2])) {
_swapToken(dollar, busd, _sellingMdo);
_swapToken(dollar, wbnb, _sellingMdo);
}
}
if (_wbnbPercent >= expansionPercent[2]) {
_swapToken(dollar, busd, _sellingMdo);
uint256 _sellingMdoToBusd = _sellingMdo.div(2);
_swapToken(dollar, busd, _sellingMdoToBusd);
_swapToken(dollar, wbnb, _sellingMdo.sub(_sellingMdoToBusd));
}
}
}
if (_busdPercent >= contractionPercent[1]) {
if (_wbnbPercent <= contractionPercent[2]) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
if (_busdPercent.sub(contractionPercent[1]) > _wbnbPercent.sub(contractionPercent[2])) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
if (_wbnbPercent > contractionPercent[2]) {
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
}
}
}
function rebalance() public checkPublicAllow {
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
uint256 _dollarPercent = _dollarBal.mul(10000).div(_totalBal);
uint256 _busdPercent = _busdBal.mul(10000).div(_totalBal);
uint256 _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
uint256 _dollarPrice = getDollarUpdatedPrice();
if (_dollarPrice >= dollarPriceToSell) {
if (_dollarPercent > expansionPercent[0]) {
uint256 _sellingMdo = _dollarBal.mul(_dollarPercent.sub(expansionPercent[0])).div(10000);
if (_busdPercent >= expansionPercent[1]) {
if (_wbnbPercent < expansionPercent[2]) {
_swapToken(dollar, wbnb, _sellingMdo);
if (_busdPercent.sub(expansionPercent[1]) <= _wbnbPercent.sub(expansionPercent[2])) {
_swapToken(dollar, busd, _sellingMdo);
_swapToken(dollar, wbnb, _sellingMdo);
}
}
if (_wbnbPercent >= expansionPercent[2]) {
_swapToken(dollar, busd, _sellingMdo);
uint256 _sellingMdoToBusd = _sellingMdo.div(2);
_swapToken(dollar, busd, _sellingMdoToBusd);
_swapToken(dollar, wbnb, _sellingMdo.sub(_sellingMdoToBusd));
}
}
}
if (_busdPercent >= contractionPercent[1]) {
if (_wbnbPercent <= contractionPercent[2]) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
if (_busdPercent.sub(contractionPercent[1]) > _wbnbPercent.sub(contractionPercent[2])) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
if (_wbnbPercent > contractionPercent[2]) {
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
}
}
}
function rebalance() public checkPublicAllow {
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
uint256 _dollarPercent = _dollarBal.mul(10000).div(_totalBal);
uint256 _busdPercent = _busdBal.mul(10000).div(_totalBal);
uint256 _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
uint256 _dollarPrice = getDollarUpdatedPrice();
if (_dollarPrice >= dollarPriceToSell) {
if (_dollarPercent > expansionPercent[0]) {
uint256 _sellingMdo = _dollarBal.mul(_dollarPercent.sub(expansionPercent[0])).div(10000);
if (_busdPercent >= expansionPercent[1]) {
if (_wbnbPercent < expansionPercent[2]) {
_swapToken(dollar, wbnb, _sellingMdo);
if (_busdPercent.sub(expansionPercent[1]) <= _wbnbPercent.sub(expansionPercent[2])) {
_swapToken(dollar, busd, _sellingMdo);
_swapToken(dollar, wbnb, _sellingMdo);
}
}
if (_wbnbPercent >= expansionPercent[2]) {
_swapToken(dollar, busd, _sellingMdo);
uint256 _sellingMdoToBusd = _sellingMdo.div(2);
_swapToken(dollar, busd, _sellingMdoToBusd);
_swapToken(dollar, wbnb, _sellingMdo.sub(_sellingMdoToBusd));
}
}
}
if (_busdPercent >= contractionPercent[1]) {
if (_wbnbPercent <= contractionPercent[2]) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
if (_busdPercent.sub(contractionPercent[1]) > _wbnbPercent.sub(contractionPercent[2])) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
if (_wbnbPercent > contractionPercent[2]) {
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
}
}
}
function rebalance() public checkPublicAllow {
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
uint256 _dollarPercent = _dollarBal.mul(10000).div(_totalBal);
uint256 _busdPercent = _busdBal.mul(10000).div(_totalBal);
uint256 _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
uint256 _dollarPrice = getDollarUpdatedPrice();
if (_dollarPrice >= dollarPriceToSell) {
if (_dollarPercent > expansionPercent[0]) {
uint256 _sellingMdo = _dollarBal.mul(_dollarPercent.sub(expansionPercent[0])).div(10000);
if (_busdPercent >= expansionPercent[1]) {
if (_wbnbPercent < expansionPercent[2]) {
_swapToken(dollar, wbnb, _sellingMdo);
if (_busdPercent.sub(expansionPercent[1]) <= _wbnbPercent.sub(expansionPercent[2])) {
_swapToken(dollar, busd, _sellingMdo);
_swapToken(dollar, wbnb, _sellingMdo);
}
}
if (_wbnbPercent >= expansionPercent[2]) {
_swapToken(dollar, busd, _sellingMdo);
uint256 _sellingMdoToBusd = _sellingMdo.div(2);
_swapToken(dollar, busd, _sellingMdoToBusd);
_swapToken(dollar, wbnb, _sellingMdo.sub(_sellingMdoToBusd));
}
}
}
if (_busdPercent >= contractionPercent[1]) {
if (_wbnbPercent <= contractionPercent[2]) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
if (_busdPercent.sub(contractionPercent[1]) > _wbnbPercent.sub(contractionPercent[2])) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
if (_wbnbPercent > contractionPercent[2]) {
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
}
}
}
function rebalance() public checkPublicAllow {
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
uint256 _dollarPercent = _dollarBal.mul(10000).div(_totalBal);
uint256 _busdPercent = _busdBal.mul(10000).div(_totalBal);
uint256 _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
uint256 _dollarPrice = getDollarUpdatedPrice();
if (_dollarPrice >= dollarPriceToSell) {
if (_dollarPercent > expansionPercent[0]) {
uint256 _sellingMdo = _dollarBal.mul(_dollarPercent.sub(expansionPercent[0])).div(10000);
if (_busdPercent >= expansionPercent[1]) {
if (_wbnbPercent < expansionPercent[2]) {
_swapToken(dollar, wbnb, _sellingMdo);
if (_busdPercent.sub(expansionPercent[1]) <= _wbnbPercent.sub(expansionPercent[2])) {
_swapToken(dollar, busd, _sellingMdo);
_swapToken(dollar, wbnb, _sellingMdo);
}
}
if (_wbnbPercent >= expansionPercent[2]) {
_swapToken(dollar, busd, _sellingMdo);
uint256 _sellingMdoToBusd = _sellingMdo.div(2);
_swapToken(dollar, busd, _sellingMdoToBusd);
_swapToken(dollar, wbnb, _sellingMdo.sub(_sellingMdoToBusd));
}
}
}
if (_busdPercent >= contractionPercent[1]) {
if (_wbnbPercent <= contractionPercent[2]) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
if (_busdPercent.sub(contractionPercent[1]) > _wbnbPercent.sub(contractionPercent[2])) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
if (_wbnbPercent > contractionPercent[2]) {
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
}
}
}
function rebalance() public checkPublicAllow {
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
uint256 _dollarPercent = _dollarBal.mul(10000).div(_totalBal);
uint256 _busdPercent = _busdBal.mul(10000).div(_totalBal);
uint256 _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
uint256 _dollarPrice = getDollarUpdatedPrice();
if (_dollarPrice >= dollarPriceToSell) {
if (_dollarPercent > expansionPercent[0]) {
uint256 _sellingMdo = _dollarBal.mul(_dollarPercent.sub(expansionPercent[0])).div(10000);
if (_busdPercent >= expansionPercent[1]) {
if (_wbnbPercent < expansionPercent[2]) {
_swapToken(dollar, wbnb, _sellingMdo);
if (_busdPercent.sub(expansionPercent[1]) <= _wbnbPercent.sub(expansionPercent[2])) {
_swapToken(dollar, busd, _sellingMdo);
_swapToken(dollar, wbnb, _sellingMdo);
}
}
if (_wbnbPercent >= expansionPercent[2]) {
_swapToken(dollar, busd, _sellingMdo);
uint256 _sellingMdoToBusd = _sellingMdo.div(2);
_swapToken(dollar, busd, _sellingMdoToBusd);
_swapToken(dollar, wbnb, _sellingMdo.sub(_sellingMdoToBusd));
}
}
}
if (_busdPercent >= contractionPercent[1]) {
if (_wbnbPercent <= contractionPercent[2]) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
if (_busdPercent.sub(contractionPercent[1]) > _wbnbPercent.sub(contractionPercent[2])) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
if (_wbnbPercent > contractionPercent[2]) {
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
}
}
}
} else {
function rebalance() public checkPublicAllow {
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
uint256 _dollarPercent = _dollarBal.mul(10000).div(_totalBal);
uint256 _busdPercent = _busdBal.mul(10000).div(_totalBal);
uint256 _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
uint256 _dollarPrice = getDollarUpdatedPrice();
if (_dollarPrice >= dollarPriceToSell) {
if (_dollarPercent > expansionPercent[0]) {
uint256 _sellingMdo = _dollarBal.mul(_dollarPercent.sub(expansionPercent[0])).div(10000);
if (_busdPercent >= expansionPercent[1]) {
if (_wbnbPercent < expansionPercent[2]) {
_swapToken(dollar, wbnb, _sellingMdo);
if (_busdPercent.sub(expansionPercent[1]) <= _wbnbPercent.sub(expansionPercent[2])) {
_swapToken(dollar, busd, _sellingMdo);
_swapToken(dollar, wbnb, _sellingMdo);
}
}
if (_wbnbPercent >= expansionPercent[2]) {
_swapToken(dollar, busd, _sellingMdo);
uint256 _sellingMdoToBusd = _sellingMdo.div(2);
_swapToken(dollar, busd, _sellingMdoToBusd);
_swapToken(dollar, wbnb, _sellingMdo.sub(_sellingMdoToBusd));
}
}
}
if (_busdPercent >= contractionPercent[1]) {
if (_wbnbPercent <= contractionPercent[2]) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
if (_busdPercent.sub(contractionPercent[1]) > _wbnbPercent.sub(contractionPercent[2])) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
if (_wbnbPercent > contractionPercent[2]) {
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
}
}
}
} else {
} else {
function rebalance() public checkPublicAllow {
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
uint256 _dollarPercent = _dollarBal.mul(10000).div(_totalBal);
uint256 _busdPercent = _busdBal.mul(10000).div(_totalBal);
uint256 _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
uint256 _dollarPrice = getDollarUpdatedPrice();
if (_dollarPrice >= dollarPriceToSell) {
if (_dollarPercent > expansionPercent[0]) {
uint256 _sellingMdo = _dollarBal.mul(_dollarPercent.sub(expansionPercent[0])).div(10000);
if (_busdPercent >= expansionPercent[1]) {
if (_wbnbPercent < expansionPercent[2]) {
_swapToken(dollar, wbnb, _sellingMdo);
if (_busdPercent.sub(expansionPercent[1]) <= _wbnbPercent.sub(expansionPercent[2])) {
_swapToken(dollar, busd, _sellingMdo);
_swapToken(dollar, wbnb, _sellingMdo);
}
}
if (_wbnbPercent >= expansionPercent[2]) {
_swapToken(dollar, busd, _sellingMdo);
uint256 _sellingMdoToBusd = _sellingMdo.div(2);
_swapToken(dollar, busd, _sellingMdoToBusd);
_swapToken(dollar, wbnb, _sellingMdo.sub(_sellingMdoToBusd));
}
}
}
if (_busdPercent >= contractionPercent[1]) {
if (_wbnbPercent <= contractionPercent[2]) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
if (_busdPercent.sub(contractionPercent[1]) > _wbnbPercent.sub(contractionPercent[2])) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
if (_wbnbPercent > contractionPercent[2]) {
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
}
}
}
} else {
} else if (_dollarPrice <= dollarPriceToBuy && (msg.sender == operator || msg.sender == strategist)) {
function rebalance() public checkPublicAllow {
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
uint256 _dollarPercent = _dollarBal.mul(10000).div(_totalBal);
uint256 _busdPercent = _busdBal.mul(10000).div(_totalBal);
uint256 _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
uint256 _dollarPrice = getDollarUpdatedPrice();
if (_dollarPrice >= dollarPriceToSell) {
if (_dollarPercent > expansionPercent[0]) {
uint256 _sellingMdo = _dollarBal.mul(_dollarPercent.sub(expansionPercent[0])).div(10000);
if (_busdPercent >= expansionPercent[1]) {
if (_wbnbPercent < expansionPercent[2]) {
_swapToken(dollar, wbnb, _sellingMdo);
if (_busdPercent.sub(expansionPercent[1]) <= _wbnbPercent.sub(expansionPercent[2])) {
_swapToken(dollar, busd, _sellingMdo);
_swapToken(dollar, wbnb, _sellingMdo);
}
}
if (_wbnbPercent >= expansionPercent[2]) {
_swapToken(dollar, busd, _sellingMdo);
uint256 _sellingMdoToBusd = _sellingMdo.div(2);
_swapToken(dollar, busd, _sellingMdoToBusd);
_swapToken(dollar, wbnb, _sellingMdo.sub(_sellingMdoToBusd));
}
}
}
if (_busdPercent >= contractionPercent[1]) {
if (_wbnbPercent <= contractionPercent[2]) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
if (_busdPercent.sub(contractionPercent[1]) > _wbnbPercent.sub(contractionPercent[2])) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
if (_wbnbPercent > contractionPercent[2]) {
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
}
}
}
function rebalance() public checkPublicAllow {
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
uint256 _dollarPercent = _dollarBal.mul(10000).div(_totalBal);
uint256 _busdPercent = _busdBal.mul(10000).div(_totalBal);
uint256 _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
uint256 _dollarPrice = getDollarUpdatedPrice();
if (_dollarPrice >= dollarPriceToSell) {
if (_dollarPercent > expansionPercent[0]) {
uint256 _sellingMdo = _dollarBal.mul(_dollarPercent.sub(expansionPercent[0])).div(10000);
if (_busdPercent >= expansionPercent[1]) {
if (_wbnbPercent < expansionPercent[2]) {
_swapToken(dollar, wbnb, _sellingMdo);
if (_busdPercent.sub(expansionPercent[1]) <= _wbnbPercent.sub(expansionPercent[2])) {
_swapToken(dollar, busd, _sellingMdo);
_swapToken(dollar, wbnb, _sellingMdo);
}
}
if (_wbnbPercent >= expansionPercent[2]) {
_swapToken(dollar, busd, _sellingMdo);
uint256 _sellingMdoToBusd = _sellingMdo.div(2);
_swapToken(dollar, busd, _sellingMdoToBusd);
_swapToken(dollar, wbnb, _sellingMdo.sub(_sellingMdoToBusd));
}
}
}
if (_busdPercent >= contractionPercent[1]) {
if (_wbnbPercent <= contractionPercent[2]) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
if (_busdPercent.sub(contractionPercent[1]) > _wbnbPercent.sub(contractionPercent[2])) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
if (_wbnbPercent > contractionPercent[2]) {
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
}
}
}
} else {
function rebalance() public checkPublicAllow {
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
uint256 _dollarPercent = _dollarBal.mul(10000).div(_totalBal);
uint256 _busdPercent = _busdBal.mul(10000).div(_totalBal);
uint256 _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
uint256 _dollarPrice = getDollarUpdatedPrice();
if (_dollarPrice >= dollarPriceToSell) {
if (_dollarPercent > expansionPercent[0]) {
uint256 _sellingMdo = _dollarBal.mul(_dollarPercent.sub(expansionPercent[0])).div(10000);
if (_busdPercent >= expansionPercent[1]) {
if (_wbnbPercent < expansionPercent[2]) {
_swapToken(dollar, wbnb, _sellingMdo);
if (_busdPercent.sub(expansionPercent[1]) <= _wbnbPercent.sub(expansionPercent[2])) {
_swapToken(dollar, busd, _sellingMdo);
_swapToken(dollar, wbnb, _sellingMdo);
}
}
if (_wbnbPercent >= expansionPercent[2]) {
_swapToken(dollar, busd, _sellingMdo);
uint256 _sellingMdoToBusd = _sellingMdo.div(2);
_swapToken(dollar, busd, _sellingMdoToBusd);
_swapToken(dollar, wbnb, _sellingMdo.sub(_sellingMdoToBusd));
}
}
}
if (_busdPercent >= contractionPercent[1]) {
if (_wbnbPercent <= contractionPercent[2]) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
if (_busdPercent.sub(contractionPercent[1]) > _wbnbPercent.sub(contractionPercent[2])) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
if (_wbnbPercent > contractionPercent[2]) {
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
}
}
}
} else {
} else {
function rebalance() public checkPublicAllow {
(uint256 _dollarBal, uint256 _busdBal, uint256 _wbnbBal, uint256 _totalBal) = tokenBalances();
if (_totalBal > 0) {
uint256 _dollarPercent = _dollarBal.mul(10000).div(_totalBal);
uint256 _busdPercent = _busdBal.mul(10000).div(_totalBal);
uint256 _wbnbPercent = _wbnbBal.mul(10000).div(_totalBal);
uint256 _dollarPrice = getDollarUpdatedPrice();
if (_dollarPrice >= dollarPriceToSell) {
if (_dollarPercent > expansionPercent[0]) {
uint256 _sellingMdo = _dollarBal.mul(_dollarPercent.sub(expansionPercent[0])).div(10000);
if (_busdPercent >= expansionPercent[1]) {
if (_wbnbPercent < expansionPercent[2]) {
_swapToken(dollar, wbnb, _sellingMdo);
if (_busdPercent.sub(expansionPercent[1]) <= _wbnbPercent.sub(expansionPercent[2])) {
_swapToken(dollar, busd, _sellingMdo);
_swapToken(dollar, wbnb, _sellingMdo);
}
}
if (_wbnbPercent >= expansionPercent[2]) {
_swapToken(dollar, busd, _sellingMdo);
uint256 _sellingMdoToBusd = _sellingMdo.div(2);
_swapToken(dollar, busd, _sellingMdoToBusd);
_swapToken(dollar, wbnb, _sellingMdo.sub(_sellingMdoToBusd));
}
}
}
if (_busdPercent >= contractionPercent[1]) {
if (_wbnbPercent <= contractionPercent[2]) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
if (_busdPercent.sub(contractionPercent[1]) > _wbnbPercent.sub(contractionPercent[2])) {
uint256 _sellingBUSD = _busdBal.mul(_busdPercent.sub(contractionPercent[1])).div(10000);
_swapToken(busd, dollar, _sellingBUSD);
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
if (_wbnbPercent > contractionPercent[2]) {
uint256 _sellingWBNB = _wbnbBal.mul(_wbnbPercent.sub(contractionPercent[2])).div(10000);
_swapToken(wbnb, dollar, _sellingWBNB);
}
}
}
}
}
function workForDaoFund() external checkPublicAllow {
collectShareRewards();
claimAllRewardFromSharePool();
claimAndRestake();
rebalance();
}
function buyBonds(uint256 _dollarAmount) external onlyStrategist {
uint256 _dollarPrice = ITreasury(treasury).getDollarPrice();
ITreasury(treasury).buyBonds(_dollarAmount, _dollarPrice);
emit BoughtBonds(_dollarAmount);
}
function redeemBonds(uint256 _bondAmount) external onlyStrategist {
uint256 _dollarPrice = ITreasury(treasury).getDollarPrice();
ITreasury(treasury).redeemBonds(_bondAmount, _dollarPrice);
emit RedeemedBonds(_bondAmount);
}
function forceSell(address _buyingToken, uint256 _dollarAmount) external onlyStrategist {
require(getDollarUpdatedPrice() >= dollarPriceToBuy, "price is too low to sell");
_swapToken(dollar, _buyingToken, _dollarAmount);
}
function forceBuy(address _sellingToken, uint256 _sellingAmount) external onlyStrategist {
require(getDollarUpdatedPrice() <= dollarPriceToSell, "price is too high to buy");
_swapToken(_sellingToken, dollar, _sellingAmount);
}
function trimNonCoreToken(address _sellingToken) public onlyStrategist {
require(_sellingToken != dollar && _sellingToken != bond && _sellingToken != share && _sellingToken != busd && _sellingToken != wbnb, "core");
uint256 _bal = IERC20(_sellingToken).balanceOf(address(this));
if (_bal > 0) {
_swapToken(_sellingToken, dollar, _bal);
}
}
function trimNonCoreToken(address _sellingToken) public onlyStrategist {
require(_sellingToken != dollar && _sellingToken != bond && _sellingToken != share && _sellingToken != busd && _sellingToken != wbnb, "core");
uint256 _bal = IERC20(_sellingToken).balanceOf(address(this));
if (_bal > 0) {
_swapToken(_sellingToken, dollar, _bal);
}
}
function _swapToken(
address _inputToken,
address _outputToken,
uint256 _amount
) internal {
if (_amount == 0) return;
uint256 _maxAmount = maxAmountToTrade[_inputToken];
if (_maxAmount > 0 && _maxAmount < _amount) {
_amount = _maxAmount;
}
address[] memory _path = uniswapPaths[_inputToken][_outputToken];
if (_path.length == 0) {
_path = new address[](2);
_path[0] = _inputToken;
_path[1] = _outputToken;
}
IERC20(_inputToken).safeApprove(address(pancakeRouter), 0);
IERC20(_inputToken).safeApprove(address(pancakeRouter), _amount);
pancakeRouter.swapExactTokensForTokens(_amount, 1, _path, address(this), now.add(1800));
}
function _swapToken(
address _inputToken,
address _outputToken,
uint256 _amount
) internal {
if (_amount == 0) return;
uint256 _maxAmount = maxAmountToTrade[_inputToken];
if (_maxAmount > 0 && _maxAmount < _amount) {
_amount = _maxAmount;
}
address[] memory _path = uniswapPaths[_inputToken][_outputToken];
if (_path.length == 0) {
_path = new address[](2);
_path[0] = _inputToken;
_path[1] = _outputToken;
}
IERC20(_inputToken).safeApprove(address(pancakeRouter), 0);
IERC20(_inputToken).safeApprove(address(pancakeRouter), _amount);
pancakeRouter.swapExactTokensForTokens(_amount, 1, _path, address(this), now.add(1800));
}
function _swapToken(
address _inputToken,
address _outputToken,
uint256 _amount
) internal {
if (_amount == 0) return;
uint256 _maxAmount = maxAmountToTrade[_inputToken];
if (_maxAmount > 0 && _maxAmount < _amount) {
_amount = _maxAmount;
}
address[] memory _path = uniswapPaths[_inputToken][_outputToken];
if (_path.length == 0) {
_path = new address[](2);
_path[0] = _inputToken;
_path[1] = _outputToken;
}
IERC20(_inputToken).safeApprove(address(pancakeRouter), 0);
IERC20(_inputToken).safeApprove(address(pancakeRouter), _amount);
pancakeRouter.swapExactTokensForTokens(_amount, 1, _path, address(this), now.add(1800));
}
function _addLiquidity(address _tokenB, uint256 _amountADesired) internal {
_addLiquidity2(dollar, _tokenB, _amountADesired, IERC20(_tokenB).balanceOf(address(this)));
}
function _removeLiquidity(
address _lpAdd,
address _tokenB,
uint256 _liquidity
) internal {
_removeLiquidity2(_lpAdd, dollar, _tokenB, _liquidity);
}
function _addLiquidity2(
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 amountBDesired
) internal {
IERC20(_tokenA).safeApprove(address(pancakeRouter), 0);
IERC20(_tokenA).safeApprove(address(pancakeRouter), type(uint256).max);
IERC20(_tokenB).safeApprove(address(pancakeRouter), 0);
IERC20(_tokenB).safeApprove(address(pancakeRouter), type(uint256).max);
pancakeRouter.addLiquidity(_tokenA, _tokenB, _amountADesired, amountBDesired, 0, 0, address(this), now.add(1800));
}
function _removeLiquidity2(
address _lpAdd,
address _tokenA,
address _tokenB,
uint256 _liquidity
) internal {
IERC20(_lpAdd).safeApprove(address(pancakeRouter), 0);
IERC20(_lpAdd).safeApprove(address(pancakeRouter), _liquidity);
pancakeRouter.removeLiquidity(_tokenA, _tokenB, _liquidity, 1, 1, address(this), now.add(1800));
}
function depositToSharePool(address _tokenB, uint256 _dollarAmount) external onlyStrategist {
address _lpAdd = lpPairAddress[_tokenB];
uint256 _before = IERC20(_lpAdd).balanceOf(address(this));
_addLiquidity(_tokenB, _dollarAmount);
uint256 _after = IERC20(_lpAdd).balanceOf(address(this));
uint256 _lpBal = _after.sub(_before);
require(_lpBal > 0, "!_lpBal");
address _shareRewardPool = shareRewardPool;
uint256 _pid = shareRewardPoolId[_tokenB];
IERC20(_lpAdd).safeApprove(_shareRewardPool, 0);
IERC20(_lpAdd).safeApprove(_shareRewardPool, _lpBal);
IShareRewardPool(_shareRewardPool).deposit(_pid, _lpBal);
}
function withdrawFromSharePool(address _tokenB, uint256 _lpAmount) public onlyStrategist {
address _lpAdd = lpPairAddress[_tokenB];
address _shareRewardPool = shareRewardPool;
uint256 _pid = shareRewardPoolId[_tokenB];
IShareRewardPool(_shareRewardPool).withdraw(_pid, _lpAmount);
_removeLiquidity(_lpAdd, _tokenB, _lpAmount);
}
function exitSharePool(address _tokenB) public onlyStrategist {
(uint256 _stakedAmount, ) = IShareRewardPool(shareRewardPool).userInfo(shareRewardPoolId[_tokenB], address(this));
withdrawFromSharePool(_tokenB, _stakedAmount);
}
function exitAllSharePool() external {
if (stakeAmountFromSharePool(busd) > 0) exitSharePool(busd);
if (stakeAmountFromSharePool(wbnb) > 0) exitSharePool(wbnb);
}
function claimRewardFromSharePool(address _tokenB) public {
uint256 _pid = shareRewardPoolId[_tokenB];
IShareRewardPool(shareRewardPool).withdraw(_pid, 0);
}
function claimAllRewardFromSharePool() public {
if (pendingFromSharePool(busd) > 0) claimRewardFromSharePool(busd);
if (pendingFromSharePool(wbnb) > 0) claimRewardFromSharePool(wbnb);
}
function pendingFromSharePool(address _tokenB) public view returns (uint256) {
return IShareRewardPool(shareRewardPool).pendingShare(shareRewardPoolId[_tokenB], address(this));
}
function pendingAllFromSharePool() public view returns (uint256) {
return pendingFromSharePool(busd).add(pendingFromSharePool(wbnb));
}
function stakeAmountFromSharePool(address _tokenB) public view returns (uint256 _stakedAmount) {
(_stakedAmount, ) = IShareRewardPool(shareRewardPool).userInfo(shareRewardPoolId[_tokenB], address(this));
}
function stakeAmountAllFromSharePool() public view returns (uint256 _bnbPoolStakedAmount, uint256 _wbnbPoolStakedAmount) {
_bnbPoolStakedAmount = stakeAmountFromSharePool(busd);
_wbnbPoolStakedAmount = stakeAmountFromSharePool(wbnb);
}
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data
) public onlyOperator returns (bytes memory) {
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
require(success, string("CommunityFund::executeTransaction: Transaction execution reverted."));
emit ExecuteTransaction(target, value, signature, data);
return returnData;
}
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data
) public onlyOperator returns (bytes memory) {
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
require(success, string("CommunityFund::executeTransaction: Transaction execution reverted."));
emit ExecuteTransaction(target, value, signature, data);
return returnData;
}
} else {
(bool success, bytes memory returnData) = target.call{value: value}(callData);
receive() external payable {}
} | 11,214,628 | [
1,
2503,
6835,
903,
3274,
331,
10100,
2638,
4807,
16,
384,
911,
358,
326,
17980,
1060,
13924,
471,
283,
12296,
490,
3191,
16,
605,
3378,
40,
16,
678,
15388,
38,
4888,
358,
463,
20463,
18,
19,
314,
1643,
82,
1359,
2943,
6205,
12913,
71,
3223,
91,
438,
463,
20463,
1472,
300,
2333,
30,
8532,
18,
13138,
345,
72,
25442,
18,
22056,
19,
18485,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
16854,
13352,
42,
1074,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
565,
1758,
1071,
3726,
31,
203,
203,
565,
1426,
1071,
6454,
273,
629,
31,
203,
203,
203,
565,
1758,
1071,
302,
25442,
273,
1758,
12,
20,
92,
4763,
73,
5292,
29,
38,
5608,
25,
1105,
8898,
70,
11861,
4315,
38,
25,
73,
26,
73,
24,
3247,
5026,
70,
40,
5324,
74,
23,
42,
27,
5482,
71,
1769,
203,
565,
1758,
1071,
7433,
273,
1758,
12,
20,
92,
3247,
22,
41,
24,
1105,
29,
4630,
10580,
2226,
23508,
11290,
2056,
29,
5082,
42,
22,
39,
24,
2671,
42,
2313,
2947,
3103,
6418,
507,
1769,
203,
565,
1758,
1071,
8427,
273,
1758,
12,
20,
14626,
69,
40,
22,
22267,
6743,
6030,
2313,
40,
9462,
69,
7235,
26,
71,
38,
27,
69,
20,
38,
25,
7235,
5482,
7228,
6669,
2499,
6564,
21,
1769,
203,
203,
565,
1758,
1071,
5766,
72,
273,
1758,
12,
20,
6554,
29,
73,
27,
1441,
37,
23,
20563,
71,
37,
6162,
5193,
27,
3672,
38,
1727,
71,
25,
2733,
70,
40,
8148,
1880,
72,
6840,
27,
40,
4313,
1769,
203,
565,
1758,
1071,
584,
7510,
273,
1758,
12,
20,
92,
2539,
72,
5520,
28,
27284,
74,
2733,
20,
6162,
74,
42,
4700,
6564,
7140,
3247,
26,
11984,
3103,
27,
38,
23,
3657,
7235,
2539,
1769,
203,
565,
1758,
1071,
324,
2896,
273,
1758,
12,
20,
92,
30454,
70,
25,
6675,
8522,
29,
2
] |
pragma solidity ^0.6.0;
import "./SafeMath.sol";
import "./_Interfaces.sol";
interface IAnyStake_Library {
function tokenInfoLibrary(address _token) external view returns(
string memory name, string memory symbol, uint8 decimals, uint256 spotPrice, bool activated, uint8 boost);
function tokenPriceUpdate(address _token) external returns (uint256);
}
// File: @defiat-crypto/defiat/blob/master/contracts/XXXXXX.sol
/**
* @dev Delegated Farming Contract.
* Implements a conditoin on the DFT-DFT farming pool for users to generate more rewards
*/
contract DeFiat_AnyStake{
using SafeMath for uint256;
//Structs
struct PoolMetrics {
mapping(address => uint256) tokenStake; // stakes per token
mapping(address => uint256) wETHtokenStake; // wETH equivalent
uint256 wETHStake; // total stake in wETH Gwei (aggregated)
uint256 stakingFee; // entry fee
uint256 stakingPoints;
address rewardToken;
uint256 rewards; // current rewards in the pool
uint256 totalRewards;
uint256 startTime; // when the pool opens
uint256 closingTime; // when the pool closes.
uint256 duration; // duration of the staking
uint256 lastEvent; // last time metrics were updated.
uint256 ratePerToken; // CALCULATED pool reward Rate per Token (calculated based on total stake and time)
address DftDungeon; // used to calculate the DeFiatScore
}
PoolMetrics public poolMetrics;
struct UserMetrics {
mapping(address => uint256) tokenStake; // stakes per token (nb of tokens)
mapping(address => uint256) wETHtokenStake; // wETH equivalent
mapping(address => uint256) tokenPoints;
mapping(address => uint256) tokenBoost; // boost per token, depends on the nb of DFT staked (0 = no stakingPoints generated)
uint256 wETHStake; // total stake in wETH Gwei (aggregated)
uint256 stakingPoints; // total staking points at lastEvent
uint256 poolPoints; // pool point at lastEvent
uint256 lastEvent;
uint256 rewardAccrued; // accrued rewards over time based on staking points
uint256 rewardsPaid; // for information only
uint256 lastTxBlock; // latest transaction from the user (antiSpam)
}
mapping(address => UserMetrics) public userMetrics;
address public poolOperator; address public owner; address public AnyStake_Library;
//== constructor
constructor(address _rewardToken, uint256 _feeBase1000, uint256 _durationHours) public {
owner = msg.sender;
poolOperator = msg.sender;
poolMetrics.rewardToken = address(_rewardToken);
poolMetrics.stakingFee = _feeBase1000; //10 = 1%
poolMetrics.duration = _durationHours.mul(3600); //
poolMetrics.startTime = block.timestamp;
poolMetrics.closingTime = poolMetrics.startTime + poolMetrics.duration;
poolMetrics.stakingPoints = 1; //avoids div by 0 at start
}
//== Events & Modifiers
event PoolInitalized(uint256 amountAdded, string _desc);
event RewardTaken(address indexed user, uint256 reward, string _desc);
event userStaking(address indexed user, uint256 amount, string _desc);
event userWithdrawal(address indexed user, uint256 amount, string _desc);
modifier poolLive() {
require(block.timestamp >= poolMetrics.startTime,"Pool not started Yet"); //good for delayed starts.
require(block.timestamp <= poolMetrics.closingTime,"Pool closed"); //good for delayed starts.
_;
}
modifier poolStarted() {
require(block.timestamp >= poolMetrics.startTime,"Pool not started Yet"); //good for delayed starts.
_;
}
modifier poolEnded() {
require(block.timestamp > poolMetrics.closingTime,"Pool not ended Yet"); //good for delayed starts.
_;
}
modifier antiSpam(uint256 _blocks) {
require(block.number > userMetrics[msg.sender].lastTxBlock.add(_blocks), "Wait X BLOCKS between Transactions");
userMetrics[msg.sender].lastTxBlock = block.number; //update
_;
}
modifier onlyPoolOperator() {
require(msg.sender== poolOperator || msg.sender == owner, "msg.sender is not allowed to operate Pool");
_;
}
modifier onlyOwner() {
require(msg.sender== owner, "Only Owner");
_;
}
modifier antiWhale(address _token, address _address) {
require(myStakeShare(_token, _address) < 20000, "User stake% share too high. Leave some for the smaller guys ;-)"); //max 20%
_;
}
// avoids stakes being deposited once a user reached 20%.
// Simplistic implementation as if we calculate "futureStake" value very 1st stakers will not be able to deposit.
modifier tokenListed(address _token) {
(,,,,bool _activated,) = getTokenFromLibrary(_token);
require(_activated == true, "token not Listed");
_;
}
//==Basics
function currentTime() public view returns (uint256) {
return SafeMath.min(block.timestamp, poolMetrics.closingTime); //allows expiration
} // SafeMath.min(now, endTime)
function setPoolOperator(address _address) public onlyPoolOperator {
poolOperator = _address;
}
/**
* @dev Function gets the amount of DFT in the DFT dungeon farm
* to calculate a score that boosts the StakingRewards calculation
* DFT requirements to get a boost are hard coded into the contract
* 0DFT to 100 DFT staked respectfully generate a 0% to 100% bonus on Staking.
* returned is a number between 50 and 100
*/
/*
function viewDftStaked(address _address) public view returns(uint256) {
return IDungeon(poolMetrics.DftDungeon).myStake(_address);
}
function viewTokenBoost(address _token, address _address) public view returns(uint256) {
uint256 _userStake = viewDftStaked(_address);
return 0;
}
*/
//==Points locking
function viewPoolPoints() public view returns(uint256) {
uint256 _previousPoints = poolMetrics.stakingPoints; // previous points shapshot
uint256 _previousStake = poolMetrics.wETHStake; // previous stake snapshot
uint256 _timeHeld = currentTime().sub(
SafeMath.max(poolMetrics.lastEvent, poolMetrics.startTime)
); // time held with _previous Event
return _previousPoints.add(_previousStake.mul(_timeHeld)); //generated points since event
}
function lockPoolPoints() internal returns (uint256) { //ON STAKE/UNSTAKE EVENT
poolMetrics.stakingPoints = viewPoolPoints();
poolMetrics.lastEvent = currentTime(); // update lastStakingEvent
return poolMetrics.stakingPoints;
}
function viewPointsOf(address _address) public view returns(uint256) {
uint256 _previousPoints = userMetrics[_address].stakingPoints;
uint256 _previousStake = userMetrics[_address].wETHStake;
uint256 _timeHeld = currentTime().sub(
SafeMath.max(userMetrics[_address].lastEvent, poolMetrics.startTime)
); // time held since lastEvent (take RWD, STK, unSTK)
uint256 _result = _previousPoints.add(_previousStake.mul(_timeHeld));
if(_result > poolMetrics.stakingPoints){_result = poolMetrics.stakingPoints;}
return _result;
}
function lockPointsOf(address _address) internal returns (uint256) {
userMetrics[_address].poolPoints = viewPoolPoints(); // snapshot of pool points at lockEvent
userMetrics[_address].stakingPoints = viewPointsOf(_address);
userMetrics[_address].lastEvent = currentTime();
return userMetrics[_address].stakingPoints;
}
function pointsSnapshot(address _address) public returns (bool) {
lockPointsOf(_address);
lockPoolPoints();
return true;
}
//==Rewards
function viewTrancheReward(uint256 _period) internal view returns(uint256) {
uint256 _poolRewards = poolMetrics.totalRewards;
uint256 _timeRate = _period.mul(1e18).div(poolMetrics.duration);
return _poolRewards.mul(_timeRate).div(1e18); //tranche of rewards on period
}
function userRateOnPeriod(address _address) public view returns (uint256){
//calculates the delta of pool points and user points since last Event
uint256 _deltaUser = viewPointsOf(_address).sub(userMetrics[_address].stakingPoints); // points generated since lastEvent
uint256 _deltaPool = viewPoolPoints().sub(userMetrics[_address].poolPoints); // pool points generated since lastEvent
uint256 _rate = 0;
if(_deltaUser == 0 || _deltaPool == 0 ){_rate = 0;} //rounding
else {_rate = _deltaUser.mul(1e18).div(_deltaPool);}
return _rate;
}
function viewAdditionalRewardOf(address _address) public view returns(uint256) { // rewards generated since last Event
require(poolMetrics.rewards > 0, "No Rewards in the Pool");
// user weighted average share of Pool since lastEvent
uint256 _userRateOnPeriod = userRateOnPeriod(_address); //can drop if pool size increases within period -> slows rewards generation
// Pool Yield Rate
uint256 _period = currentTime().sub(
SafeMath.max(userMetrics[_address].lastEvent, poolMetrics.startTime)
); // time elapsed since last reward or pool started (if never taken rewards)
// Calculate reward
uint256 _reward = viewTrancheReward(_period).mul(_userRateOnPeriod).div(1e18); //user rate on pool rewards' tranche
return _reward;
}
function lockRewardOf(address _address) public returns(uint256) {
uint256 _additional = viewAdditionalRewardOf(_address); //stakeShare(sinceLastEvent) * poolRewards(sinceLastEvent)
userMetrics[_address].rewardAccrued = userMetrics[_address].rewardAccrued.add(_additional); //snapshot rewards.
pointsSnapshot(_address); //updates lastEvent and points
return userMetrics[_address].rewardAccrued;
}
function takeRewards() public poolStarted antiSpam(1) { //1 blocks between rewards
require(poolMetrics.rewards > 0, "No Rewards in the Pool");
uint256 _reward = lockRewardOf(msg.sender); //returns already accrued + additional (also resets time counters)
userMetrics[msg.sender].rewardsPaid = _reward; // update user paid rewards
userMetrics[msg.sender].rewardAccrued = 0; //flush previously accrued rewards.
poolMetrics.rewards = poolMetrics.rewards.sub(_reward); // update pool rewards
IERC20(poolMetrics.rewardToken).transfer(msg.sender, _reward); // transfer
pointsSnapshot(msg.sender); //updates lastEvent
//lockRewardOf(msg.sender);
emit RewardTaken(msg.sender, _reward, "Rewards Sent");
}
//==staking & unstaking
//add condition on TOKEN IN AnyStake_Library
function stake(address _token, uint256 _amount) public poolLive antiSpam(1) antiWhale(_token, msg.sender) tokenListed(_token){
require(_amount > 0, "Cannot stake 0");
//initialize
userMetrics[msg.sender].rewardAccrued = lockRewardOf(msg.sender); //Locks previous eligible rewards based on lastRewardEvent and lastStakingEvent
pointsSnapshot(msg.sender); //snapshot of wETHstakebalances
//receive staked
uint256 _balanceNow = IERC20(_token).balanceOf(address(this));
IERC20(_token).transferFrom(msg.sender, address(this), _amount); //will require allowance
uint256 amount = IERC20(_token).balanceOf(address(this)).sub(_balanceNow); //actually received
//fee stays in contract until period ends
amount = amount.sub(amount.mul(poolMetrics.stakingFee).div(1000));
//Manage stakes
//per token (mb of tokens)
poolMetrics.tokenStake[_token] = poolMetrics.tokenStake[_token].add(amount);
userMetrics[msg.sender].tokenStake[_token] = userMetrics[msg.sender].tokenStake[_token].add(amount);
//update wETHStake
uint256 _tokenPerEth = getTokensPerETH(_token);
uint256 _wETHstake = amount.mul(1e18).div(_tokenPerEth);
_wETHstake = _wETHstake.mul(getTokenBoost(_token)).div(100); //add token BOOST
poolMetrics.wETHStake = poolMetrics.wETHStake.add(_wETHstake);
userMetrics[msg.sender].wETHStake = userMetrics[msg.sender].wETHStake.add(_wETHstake); //wETH stake updated
//granular update (wETH stake per token, for users to measure stake impact and calculate avg price)
poolMetrics.wETHtokenStake[_token] = poolMetrics.wETHtokenStake[_token].add(amount);
userMetrics[msg.sender].wETHtokenStake[_token] = userMetrics[msg.sender].wETHtokenStake[_token].add(_wETHstake);
//finalize
pointsSnapshot(msg.sender); //updates lastEvent
emit userStaking(msg.sender, amount, "Staking... ... ");
}
function unStake(address _token, uint256 _amount) public poolStarted antiSpam(1) {
require(_amount > 0, "Cannot withdraw 0");
require(_amount <= userMetrics[msg.sender].tokenStake[_token], "Cannot withdraw more than stake");
//initialize
userMetrics[msg.sender].rewardAccrued = lockRewardOf(msg.sender); //snapshot of previous eligible rewards based on lastStakingEvent
pointsSnapshot(msg.sender);
uint256 amount = _amount;
//Manage stakes
/* @dev wETH average price is calculated from previous stakes
*
*/
//update wETHStake
uint256 _avgPriceUser = userMetrics[msg.sender].tokenStake[_token].mul(1e18).div(userMetrics[msg.sender].wETHtokenStake[_token]);
uint256 _wETHstake = amount.mul(1e18).div(_avgPriceUser);
poolMetrics.wETHStake = poolMetrics.wETHStake.sub(_wETHstake);
userMetrics[msg.sender].wETHStake = userMetrics[msg.sender].wETHStake.sub(_wETHstake); //wETH stake updated
//per token (mb of tokens)
poolMetrics.tokenStake[_token] = poolMetrics.tokenStake[_token].sub(amount);
userMetrics[msg.sender].tokenStake[_token] = userMetrics[msg.sender].tokenStake[_token].sub(amount);
//granular update (wETH stake per token, for users to measure stake impact)
poolMetrics.wETHtokenStake[_token] = poolMetrics.wETHtokenStake[_token].sub(amount);
userMetrics[msg.sender].wETHtokenStake[_token] = userMetrics[msg.sender].wETHtokenStake[_token].sub(_wETHstake);
// transfer _amount. Put at the end of the function to avoid reentrancy.
IERC20(_token).transfer(msg.sender, _amount);
//finalize
//check if snapshot needed with new points manangement
emit userWithdrawal(msg.sender, _amount, "Widhtdrawal");
}
function myStake(address _token, address _address) public view returns(uint256) {
return userMetrics[_address].tokenStake[_token];
}
function myStakeShare(address _token, address _address) public view returns(uint256) {
if(poolMetrics.wETHStake == 0){return 0;}
else {
return (userMetrics[_address].wETHtokenStake[_token]).mul(100000).div(poolMetrics.wETHtokenStake[_token]);
}
}
function myPointsShare(address _address) public view returns(uint256) { //weighted average of your stake over time vs the pool
return viewPointsOf(_address).mul(100000).div(viewPoolPoints());
} //base 100,000. Drops when taking rewards.=> Refills after (favors strong hands)
function myRewards(address _address) public view returns(uint256) {
if(block.timestamp <= poolMetrics.startTime || poolMetrics.rewards == 0){return 0;}
else { return userMetrics[_address].rewardAccrued.add(viewAdditionalRewardOf(_address));} //previousLock + time based extra
}
//== USER TOKEN MANAGEMENT FUNCTIONS
//== Library
function getTokenFromLibrary(address _token) public view returns(
string memory name, string memory symbol, uint8 decimals, uint256 spotPrice, bool activated, uint8 boost) {
return IAnyStake_Library(AnyStake_Library).tokenInfoLibrary(_token);
}
function getTokensPerETH(address _token) public returns(uint256){
return IAnyStake_Library(AnyStake_Library).tokenPriceUpdate(_token);
}
function getTokenBoost(address _token) public view returns(uint256){
(,,,,,uint256 _boost) = getTokenFromLibrary(_token);
return _boost;
}
//== userArray
mapping(address => address[]) tokenList; //array of tokens per user
/* @dev: users manage they tokens staked array (list)
* can only replace a token if stake is == 0 for the replaced token
* max nb of tokens is 16
* token 0 is always DFT
*
* Users need to add the token before they can Stake
*/
function chgTokenIntoList(address _token, uint256 _rank) public {
require(_rank > 0, "cannot change 1st token, DFT only");
require(_rank <16, "maximum 16 tokens inclusing the token 0");
require(myStake(viewMyToken(msg.sender, _rank), msg.sender) == 0, "cannot remove a token with existing stake");
tokenList[msg.sender][_rank] = _token;
tokenList[msg.sender][0] = address(0xB6eE603933E024d8d53dDE3faa0bf98fE2a3d6f1);
}
function viewMyToken(address _address, uint256 _rank) public view returns(address) {
return tokenList[_address][_rank];
}
function viewMyTokenCount(address _address) public view returns(uint256) {
return(tokenList[_address].length);
}
//== OPERATOR FUNCTIONS ==
function loadRewards(uint256 _amount) public onlyPoolOperator { //load tokens in the rewards pool.
uint256 _balanceNow = IERC20(address(poolMetrics.rewardToken)).balanceOf(address(this));
IERC20(address(poolMetrics.rewardToken)).transferFrom( msg.sender, address(this), _amount);
uint256 amount = IERC20(address(poolMetrics.rewardToken)).balanceOf(address(this)).sub(_balanceNow); //actually received
poolMetrics.rewards = SafeMath.add(poolMetrics.rewards,amount);
poolMetrics.totalRewards = poolMetrics.totalRewards.add(_amount);
}
function setFee(uint256 _fee) public onlyPoolOperator {
poolMetrics.stakingFee = _fee;
}
//== OWNER FUNCTIONS ==
function setAnyStake_Library(address _library) public onlyOwner {
AnyStake_Library = _library;
}
function setDungeon(address _dungeon) public onlyOwner {
poolMetrics.DftDungeon = _dungeon;
}
function flushPool(address _ERC20address, address _recipient) external onlyOwner poolEnded {
uint256 _amount = IERC20(_ERC20address).balanceOf(address(this));
IERC20(_ERC20address).transfer(_recipient, _amount); //use of the _ERC20 traditional transfer
}
function killPool() public onlyOwner poolEnded returns(bool) {
selfdestruct(msg.sender);
} //frees space on the ETH chain
}
| == OWNER FUNCTIONS == | function setAnyStake_Library(address _library) public onlyOwner {
AnyStake_Library = _library;
}
| 7,283,852 | [
1,
631,
531,
22527,
13690,
55,
422,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
444,
2961,
510,
911,
67,
9313,
12,
2867,
389,
12083,
13,
1071,
1338,
5541,
288,
203,
3639,
5502,
510,
911,
67,
9313,
273,
389,
12083,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.0;
contract Nest_NToken_OfferMain {
using SafeMath for uint256;
using address_make_payable for address;
using SafeERC20 for ERC20;
// Offering data structure
struct Nest_NToken_OfferPriceData {
// The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress())
address owner; // Offering owner
bool deviate; // Whether it deviates
address tokenAddress; // The erc20 contract address of the target offer token
uint256 ethAmount; // The ETH amount in the offer list
uint256 tokenAmount; // The token amount in the offer list
uint256 dealEthAmount; // The remaining number of tradable ETH
uint256 dealTokenAmount; // The remaining number of tradable tokens
uint256 blockNum; // The block number where the offer is located
uint256 serviceCharge; // The fee for mining
// Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0
}
Nest_NToken_OfferPriceData [] _prices; // Array used to save offers
Nest_3_VoteFactory _voteFactory; // Voting contract
Nest_3_OfferPrice _offerPrice; // Price contract
Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract
ERC20 _nestToken; // nestToken
Nest_3_Abonus _abonus; // Bonus pool
uint256 _miningETH = 10; // Offering mining fee ratio
uint256 _tranEth = 1; // Taker fee ratio
uint256 _tranAddition = 2; // Additional transaction multiple
uint256 _leastEth = 10 ether; // Minimum offer of ETH
uint256 _offerSpan = 10 ether; // ETH Offering span
uint256 _deviate = 10; // Price deviation - 10%
uint256 _deviationFromScale = 10; // Deviation from asset scale
uint256 _ownerMining = 5; // Creator ratio
uint256 _afterMiningAmount = 0.4 ether; // Stable period mining amount
uint32 _blockLimit = 25; // Block interval upper limit
uint256 _blockAttenuation = 2400000; // Block decay interval
mapping(uint256 => mapping(address => uint256)) _blockOfferAmount; // Block offer times - block number=>token address=>offer fee
mapping(uint256 => mapping(address => uint256)) _blockMining; // Offering block mining amount - block number=>token address=>mining amount
uint256[10] _attenuationAmount; // Mining decay list
// Log token contract address
event OFFERTOKENCONTRACTADDRESS732(address contractAddress); //inject NONSTANDARD NAMING
// Log offering contract, token address, amount of ETH, amount of ERC20, delayed block, mining fee
event OFFERCONTRACTADDRESS317(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued,uint256 mining); //inject NONSTANDARD NAMING
// Log transaction sender, transaction token, transaction amount, purchase token address, purchase token amount, transaction offering contract address, transaction user address
event OFFERTRAN368(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner); //inject NONSTANDARD NAMING
// Log current block, current block mined amount, token address
event OREDRAWINGLOG324(uint256 nowBlock, uint256 blockAmount, address tokenAddress); //inject NONSTANDARD NAMING
// Log offering block, token address, token offered times
event MININGLOG206(uint256 blockNum, address tokenAddress, uint256 offerTimes); //inject NONSTANDARD NAMING
constructor (address voteFactory) public {
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.CHECKADDRESS430("nest.v3.offerPrice")));
_nestToken = ERC20(voteFactoryMap.CHECKADDRESS430("nest"));
_abonus = Nest_3_Abonus(voteFactoryMap.CHECKADDRESS430("nest.v3.abonus"));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.CHECKADDRESS430("nest.nToken.tokenMapping")));
uint256 blockAmount = 4 ether;
for (uint256 i = 0; i < 10; i ++) {
_attenuationAmount[i] = blockAmount;
blockAmount = blockAmount.MUL982(8).DIV757(10);
}
}
function CHANGEMAPPING259(address voteFactory) public ONLYOWNER202 { //inject NONSTANDARD NAMING
Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory));
_voteFactory = voteFactoryMap;
_offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.CHECKADDRESS430("nest.v3.offerPrice")));
_nestToken = ERC20(voteFactoryMap.CHECKADDRESS430("nest"));
_abonus = Nest_3_Abonus(voteFactoryMap.CHECKADDRESS430("nest.v3.abonus"));
_tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.CHECKADDRESS430("nest.nToken.tokenMapping")));
}
function OFFER735(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable { //inject NONSTANDARD NAMING
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
address nTokenAddress = _tokenMapping.CHECKTOKENMAPPING799(erc20Address);
require(nTokenAddress != address(0x0));
// Judge whether the price deviates
uint256 ethMining;
bool isDeviate = COMPARATIVEPRICE616(ethAmount,erc20Amount,erc20Address);
if (isDeviate) {
require(ethAmount >= _leastEth.MUL982(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale");
ethMining = _leastEth.MUL982(_miningETH).DIV757(1000);
} else {
ethMining = ethAmount.MUL982(_miningETH).DIV757(1000);
}
require(msg.value >= ethAmount.ADD379(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee");
uint256 subValue = msg.value.SUB918(ethAmount.ADD379(ethMining));
if (subValue > 0) {
REPAYETH964(address(msg.sender), subValue);
}
// Create an offer
CREATEOFFER725(ethAmount, erc20Amount, erc20Address,isDeviate, ethMining);
// Transfer in offer asset - erc20 to this contract
ERC20(erc20Address).SAFETRANSFERFROM181(address(msg.sender), address(this), erc20Amount);
_abonus.SWITCHTOETHFORNTOKENOFFER869.value(ethMining)(nTokenAddress);
// Mining
if (_blockOfferAmount[block.number][erc20Address] == 0) {
uint256 miningAmount = OREDRAWING657(nTokenAddress);
Nest_NToken nToken = Nest_NToken(nTokenAddress);
nToken.TRANSFER16(nToken.CHECKBIDDER306(), miningAmount.MUL982(_ownerMining).DIV757(100));
_blockMining[block.number][erc20Address] = miningAmount.SUB918(miningAmount.MUL982(_ownerMining).DIV757(100));
}
_blockOfferAmount[block.number][erc20Address] = _blockOfferAmount[block.number][erc20Address].ADD379(ethMining);
}
function CREATEOFFER725(uint256 ethAmount, uint256 erc20Amount, address erc20Address, bool isDeviate, uint256 mining) private { //inject NONSTANDARD NAMING
// Check offer conditions
require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale");
require(ethAmount % _offerSpan == 0, "Non compliant asset span");
require(erc20Amount % (ethAmount.DIV757(_offerSpan)) == 0, "Asset quantity is not divided");
require(erc20Amount > 0);
// Create offering contract
emit OFFERCONTRACTADDRESS317(TOADDRESS719(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining);
_prices.push(Nest_NToken_OfferPriceData(
msg.sender,
isDeviate,
erc20Address,
ethAmount,
erc20Amount,
ethAmount,
erc20Amount,
block.number,
mining
));
// Record price
_offerPrice.ADDPRICE894(ethAmount, erc20Amount, block.number.ADD379(_blockLimit), erc20Address, address(msg.sender));
}
// Convert offer address into index in offer array
function TOINDEX783(address contractAddress) public pure returns(uint256) { //inject NONSTANDARD NAMING
return uint256(contractAddress);
}
// Convert index in offer array into offer address
function TOADDRESS719(uint256 index) public pure returns(address) { //inject NONSTANDARD NAMING
return address(index);
}
function TURNOUT418(address contractAddress) public { //inject NONSTANDARD NAMING
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 index = TOINDEX783(contractAddress);
Nest_NToken_OfferPriceData storage offerPriceData = _prices[index];
require(CHECKCONTRACTSTATE995(offerPriceData.blockNum) == 1, "Offer status error");
// Withdraw ETH
if (offerPriceData.ethAmount > 0) {
uint256 payEth = offerPriceData.ethAmount;
offerPriceData.ethAmount = 0;
REPAYETH964(offerPriceData.owner, payEth);
}
// Withdraw erc20
if (offerPriceData.tokenAmount > 0) {
uint256 payErc = offerPriceData.tokenAmount;
offerPriceData.tokenAmount = 0;
ERC20(address(offerPriceData.tokenAddress)).TRANSFER16(offerPriceData.owner, payErc);
}
// Mining settlement
if (offerPriceData.serviceCharge > 0) {
MINING254(offerPriceData.blockNum, offerPriceData.tokenAddress, offerPriceData.serviceCharge, offerPriceData.owner);
offerPriceData.serviceCharge = 0;
}
}
function SENDETHBUYERC123(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { //inject NONSTANDARD NAMING
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 serviceCharge = tranEthAmount.MUL982(_tranEth).DIV757(1000);
require(msg.value == ethAmount.ADD379(tranEthAmount).ADD379(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Get the offer data structure
uint256 index = TOINDEX783(contractAddress);
Nest_NToken_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = COMPARATIVEPRICE616(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.MUL982(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.MUL982(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.MUL982(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
// Check whether the conditions for taker order are satisfied
require(CHECKCONTRACTSTATE995(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.ADD379(tranEthAmount);
offerPriceData.tokenAmount = offerPriceData.tokenAmount.SUB918(tranTokenAmount);
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.SUB918(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.SUB918(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
CREATEOFFER725(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0);
// Transfer in erc20 + offer asset to this contract
if (tokenAmount > tranTokenAmount) {
ERC20(tranTokenAddress).SAFETRANSFERFROM181(address(msg.sender), address(this), tokenAmount.SUB918(tranTokenAmount));
} else {
ERC20(tranTokenAddress).SAFETRANSFER797(address(msg.sender), tranTokenAmount.SUB918(tokenAmount));
}
// Modify price
_offerPrice.CHANGEPRICE820(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.ADD379(_blockLimit));
emit OFFERTRAN368(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
address nTokenAddress = _tokenMapping.CHECKTOKENMAPPING799(tranTokenAddress);
_abonus.SWITCHTOETH95.value(serviceCharge)(nTokenAddress);
}
}
function SENDERCBUYETH398(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { //inject NONSTANDARD NAMING
require(address(msg.sender) == address(tx.origin), "It can't be a contract");
uint256 serviceCharge = tranEthAmount.MUL982(_tranEth).DIV757(1000);
require(msg.value == ethAmount.SUB918(tranEthAmount).ADD379(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee");
require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span");
// Get the offer data structure
uint256 index = TOINDEX783(contractAddress);
Nest_NToken_OfferPriceData memory offerPriceData = _prices[index];
// Check the price, compare the current offer to the last effective price
bool thisDeviate = COMPARATIVEPRICE616(ethAmount,tokenAmount,tranTokenAddress);
bool isDeviate;
if (offerPriceData.deviate == true) {
isDeviate = true;
} else {
isDeviate = thisDeviate;
}
// Limit the taker order only be twice the amount of the offer to prevent large-amount attacks
if (offerPriceData.deviate) {
// The taker order deviates x2
require(ethAmount >= tranEthAmount.MUL982(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
} else {
if (isDeviate) {
// If the taken offer is normal and the taker order deviates x10
require(ethAmount >= tranEthAmount.MUL982(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale");
} else {
// If the taken offer is normal and the taker order is normal x2
require(ethAmount >= tranEthAmount.MUL982(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale");
}
}
// Check whether the conditions for taker order are satisfied
require(CHECKCONTRACTSTATE995(offerPriceData.blockNum) == 0, "Offer status error");
require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth");
require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token");
require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address");
require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount");
// Update the offer information
offerPriceData.ethAmount = offerPriceData.ethAmount.SUB918(tranEthAmount);
offerPriceData.tokenAmount = offerPriceData.tokenAmount.ADD379(tranTokenAmount);
offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.SUB918(tranEthAmount);
offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.SUB918(tranTokenAmount);
_prices[index] = offerPriceData;
// Create a new offer
CREATEOFFER725(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0);
// Transfer in erc20 + offer asset to this contract
ERC20(tranTokenAddress).SAFETRANSFERFROM181(address(msg.sender), address(this), tranTokenAmount.ADD379(tokenAmount));
// Modify price
_offerPrice.CHANGEPRICE820(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.ADD379(_blockLimit));
emit OFFERTRAN368(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner);
// Transfer fee
if (serviceCharge > 0) {
address nTokenAddress = _tokenMapping.CHECKTOKENMAPPING799(tranTokenAddress);
_abonus.SWITCHTOETH95.value(serviceCharge)(nTokenAddress);
}
}
function OREDRAWING657(address ntoken) private returns(uint256) { //inject NONSTANDARD NAMING
Nest_NToken miningToken = Nest_NToken(ntoken);
(uint256 createBlock, uint256 recentlyUsedBlock) = miningToken.CHECKBLOCKINFO350();
uint256 attenuationPointNow = block.number.SUB918(createBlock).DIV757(_blockAttenuation);
uint256 miningAmount = 0;
uint256 attenuation;
if (attenuationPointNow > 9) {
attenuation = _afterMiningAmount;
} else {
attenuation = _attenuationAmount[attenuationPointNow];
}
miningAmount = attenuation.MUL982(block.number.SUB918(recentlyUsedBlock));
miningToken.INCREASETOTAL78(miningAmount);
emit OREDRAWINGLOG324(block.number, miningAmount, ntoken);
return miningAmount;
}
function MINING254(uint256 blockNum, address token, uint256 serviceCharge, address owner) private returns(uint256) { //inject NONSTANDARD NAMING
// Block mining amount*offer fee/block offer fee
uint256 miningAmount = _blockMining[blockNum][token].MUL982(serviceCharge).DIV757(_blockOfferAmount[blockNum][token]);
// Transfer NToken
Nest_NToken nToken = Nest_NToken(address(_tokenMapping.CHECKTOKENMAPPING799(token)));
require(nToken.TRANSFER16(address(owner), miningAmount), "Transfer failure");
emit MININGLOG206(blockNum, token,_blockOfferAmount[blockNum][token]);
return miningAmount;
}
// Compare order prices
function COMPARATIVEPRICE616(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) { //inject NONSTANDARD NAMING
(uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.UPDATEANDCHECKPRICEPRIVATE349(token);
if (frontEthValue == 0 || frontTokenValue == 0) {
return false;
}
uint256 maxTokenAmount = myEthValue.MUL982(frontTokenValue).MUL982(uint256(100).ADD379(_deviate)).DIV757(frontEthValue.MUL982(100));
if (myTokenValue <= maxTokenAmount) {
uint256 minTokenAmount = myEthValue.MUL982(frontTokenValue).MUL982(uint256(100).SUB918(_deviate)).DIV757(frontEthValue.MUL982(100));
if (myTokenValue >= minTokenAmount) {
return false;
}
}
return true;
}
// Check contract status
function CHECKCONTRACTSTATE995(uint256 createBlock) public view returns (uint256) { //inject NONSTANDARD NAMING
if (block.number.SUB918(createBlock) > _blockLimit) {
return 1;
}
return 0;
}
// Transfer ETH
function REPAYETH964(address accountAddress, uint256 asset) private { //inject NONSTANDARD NAMING
address payable addr = accountAddress.MAKE_PAYABLE861();
addr.transfer(asset);
}
// View the upper limit of the block interval
function CHECKBLOCKLIMIT652() public view returns(uint256) { //inject NONSTANDARD NAMING
return _blockLimit;
}
// View taker fee ratio
function CHECKTRANETH271() public view returns (uint256) { //inject NONSTANDARD NAMING
return _tranEth;
}
// View additional transaction multiple
function CHECKTRANADDITION123() public view returns(uint256) { //inject NONSTANDARD NAMING
return _tranAddition;
}
// View minimum offering ETH
function CHECKLEASTETH415() public view returns(uint256) { //inject NONSTANDARD NAMING
return _leastEth;
}
// View offering ETH span
function CHECKOFFERSPAN954() public view returns(uint256) { //inject NONSTANDARD NAMING
return _offerSpan;
}
// View block offering amount
function CHECKBLOCKOFFERAMOUNT357(uint256 blockNum, address token) public view returns (uint256) { //inject NONSTANDARD NAMING
return _blockOfferAmount[blockNum][token];
}
// View offering block mining amount
function CHECKBLOCKMINING594(uint256 blockNum, address token) public view returns (uint256) { //inject NONSTANDARD NAMING
return _blockMining[blockNum][token];
}
// View offering mining amount
function CHECKOFFERMINING245(uint256 blockNum, address token, uint256 serviceCharge) public view returns (uint256) { //inject NONSTANDARD NAMING
if (serviceCharge == 0) {
return 0;
} else {
return _blockMining[blockNum][token].MUL982(serviceCharge).DIV757(_blockOfferAmount[blockNum][token]);
}
}
// View the owner allocation ratio
function CHECKOWNERMINING462() public view returns(uint256) { //inject NONSTANDARD NAMING
return _ownerMining;
}
// View the mining decay
function CHECKATTENUATIONAMOUNT848(uint256 num) public view returns(uint256) { //inject NONSTANDARD NAMING
return _attenuationAmount[num];
}
// Modify taker order fee ratio
function CHANGETRANETH866(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
_tranEth = num;
}
// Modify block interval upper limit
function CHANGEBLOCKLIMIT22(uint32 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
_blockLimit = num;
}
// Modify additional transaction multiple
function CHANGETRANADDITION884(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
require(num > 0, "Parameter needs to be greater than 0");
_tranAddition = num;
}
// Modify minimum offering ETH
function CHANGELEASTETH405(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
require(num > 0, "Parameter needs to be greater than 0");
_leastEth = num;
}
// Modify offering ETH span
function CHANGEOFFERSPAN492(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
require(num > 0, "Parameter needs to be greater than 0");
_offerSpan = num;
}
// Modify price deviation
function CHANGEKDEVIATE724(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
_deviate = num;
}
// Modify the deviation from scale
function CHANGEDEVIATIONFROMSCALE300(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
_deviationFromScale = num;
}
// Modify the owner allocation ratio
function CHANGEOWNERMINING351(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING
_ownerMining = num;
}
// Modify the mining decay
function CHANGEATTENUATIONAMOUNT1(uint256 firstAmount, uint256 top, uint256 bottom) public ONLYOWNER202 { //inject NONSTANDARD NAMING
uint256 blockAmount = firstAmount;
for (uint256 i = 0; i < 10; i ++) {
_attenuationAmount[i] = blockAmount;
blockAmount = blockAmount.MUL982(top).DIV757(bottom);
}
}
// Vote administrators only
modifier ONLYOWNER202(){ //inject NONSTANDARD NAMING
require(_voteFactory.CHECKOWNERS558(msg.sender), "No authority");
_;
}
function GETPRICECOUNT52() view public returns (uint256) { //inject NONSTANDARD NAMING
return _prices.length;
}
function GETPRICE258(uint256 priceIndex) view public returns (string memory) { //inject NONSTANDARD NAMING
// The buffer array used to generate the result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
index = WRITEOFFERPRICEDATA490(priceIndex, _prices[priceIndex], buf, index);
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
function FIND608(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) { //inject NONSTANDARD NAMING
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Calculate search interval i and end
uint256 i = _prices.length;
uint256 end = 0;
if (start != address(0)) {
i = TOINDEX783(start);
}
if (i > maxFindCount) {
end = i - maxFindCount;
}
// Loop search, write qualified records into buffer
while (count > 0 && i-- > end) {
Nest_NToken_OfferPriceData memory price = _prices[i];
if (price.owner == owner) {
--count;
index = WRITEOFFERPRICEDATA490(i, price, buf, index);
}
}
// Generate result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
function LIST901(uint256 offset, uint256 count, uint256 order) view public returns (string memory) { //inject NONSTANDARD NAMING
// Buffer array used to generate result string
bytes memory buf = new bytes(500000);
uint256 index = 0;
// Find search interval i and end
uint256 i = 0;
uint256 end = 0;
if (order == 0) {
// Reverse order, in default
// Calculate search interval i and end
if (offset < _prices.length) {
i = _prices.length - offset;
}
if (count < i) {
end = i - count;
}
// Write records in the target interval into the buffer
while (i-- > end) {
index = WRITEOFFERPRICEDATA490(i, _prices[i], buf, index);
}
} else {
// Ascending order
// Calculate the search interval i and end
if (offset < _prices.length) {
i = offset;
} else {
i = _prices.length;
}
end = i + count;
if(end > _prices.length) {
end = _prices.length;
}
// Write the records in the target interval into the buffer
while (i < end) {
index = WRITEOFFERPRICEDATA490(i, _prices[i], buf, index);
++i;
}
}
// Generate the result string and return
bytes memory str = new bytes(index);
while(index-- > 0) {
str[index] = buf[index];
}
return string(str);
}
// Write the offer data into the buffer and return the buffer index
function WRITEOFFERPRICEDATA490(uint256 priceIndex, Nest_NToken_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) { //inject NONSTANDARD NAMING
index = WRITEADDRESS338(TOADDRESS719(priceIndex), buf, index);
buf[index++] = byte(uint8(44));
index = WRITEADDRESS338(price.owner, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEADDRESS338(price.tokenAddress, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEUINT859(price.ethAmount, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEUINT859(price.tokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEUINT859(price.dealEthAmount, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEUINT859(price.dealTokenAmount, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEUINT859(price.blockNum, buf, index);
buf[index++] = byte(uint8(44));
index = WRITEUINT859(price.serviceCharge, buf, index);
buf[index++] = byte(uint8(44));
return index;
}
// Convert integer to string in decimal form, write the string into the buffer, and return the buffer index
function WRITEUINT859(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) { //inject NONSTANDARD NAMING
uint256 i = index;
do {
buf[index++] = byte(uint8(iv % 10 +48));
iv /= 10;
} while (iv > 0);
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
// Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index
function WRITEADDRESS338(address addr, bytes memory buf, uint256 index) pure private returns (uint256) { //inject NONSTANDARD NAMING
uint256 iv = uint256(addr);
uint256 i = index + 40;
do {
uint256 w = iv % 16;
if(w < 10) {
buf[index++] = byte(uint8(w +48));
} else {
buf[index++] = byte(uint8(w +87));
}
iv /= 16;
} while (index < i);
i -= 40;
for (uint256 j = index; j > i; ++i) {
byte t = buf[i];
buf[i] = buf[--j];
buf[j] = t;
}
return index;
}
}
// Price contract
interface Nest_3_OfferPrice {
// Add price data
function ADDPRICE894(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) external; //inject NONSTANDARD NAMING
// Modify price
function CHANGEPRICE820(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) external; //inject NONSTANDARD NAMING
function UPDATEANDCHECKPRICEPRIVATE349(address tokenAddress) external view returns(uint256 ethAmount, uint256 erc20Amount); //inject NONSTANDARD NAMING
}
// Voting contract
interface Nest_3_VoteFactory {
// Check address
function CHECKADDRESS430(string calldata name) external view returns (address contractAddress); //inject NONSTANDARD NAMING
// Check whether an administrator
function CHECKOWNERS558(address man) external view returns (bool); //inject NONSTANDARD NAMING
}
// NToken contract
interface Nest_NToken {
// Additional issuance
function INCREASETOTAL78(uint256 value) external; //inject NONSTANDARD NAMING
// Check mining information
function CHECKBLOCKINFO350() external view returns(uint256 createBlock, uint256 recentlyUsedBlock); //inject NONSTANDARD NAMING
// Check creator
function CHECKBIDDER306() external view returns(address); //inject NONSTANDARD NAMING
function TOTALSUPPLY249() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF133(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER16(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE798(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE147(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM462(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL26(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// NToken mapping contract
interface Nest_NToken_TokenMapping {
// Check token mapping
function CHECKTOKENMAPPING799(address token) external view returns (address); //inject NONSTANDARD NAMING
}
// Bonus pool contract
interface Nest_3_Abonus {
function SWITCHTOETH95(address token) external payable; //inject NONSTANDARD NAMING
function SWITCHTOETHFORNTOKENOFFER869(address token) external payable; //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD379(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB918(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB918(a, b, "SafeMath: subtraction overflow");
}
function SUB918(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL982(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV757(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV757(a, b, "SafeMath: division by zero");
}
function DIV757(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD863(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD863(a, b, "SafeMath: modulo by zero");
}
function MOD863(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library address_make_payable {
function MAKE_PAYABLE861(address x) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(x));
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER797(ERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.TRANSFER16.selector, to, value));
}
function SAFETRANSFERFROM181(ERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.TRANSFERFROM462.selector, from, to, value));
}
function SAFEAPPROVE632(ERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE798(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.APPROVE147.selector, spender, value));
}
function SAFEINCREASEALLOWANCE243(ERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE798(address(this), spender).ADD379(value);
CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.APPROVE147.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE715(ERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE798(address(this), spender).SUB918(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.APPROVE147.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN10(ERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT477(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface ERC20 {
function TOTALSUPPLY249() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF133(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER16(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE798(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE147(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM462(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL26(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library Address {
function ISCONTRACT477(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function SENDVALUE528(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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");
}
} | inject NONSTANDARD NAMING
| function TRANSFERFROM462(address sender, address recipient, uint256 amount) external returns (bool); | 14,093,955 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4235,
17598,
11249,
8749,
22,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: un-licensed
pragma solidity ^0.8.0;
import "../Interface/IERCX.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "../Interface/IERCXReceiver.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165Storage.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract ERCX is IERCX, ERC721, ERC165Storage, AccessControl {
using Strings for uint256;
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
address _owner;
Counters.Counter private _tokenIds;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes4 private constant _ERCX_RECEIVED = 0x11111111;
//bytes4(keccak256("onERCXReceived(address,address,uint256,bytes)"));
// Mapping from item ID to layer to owner
mapping(uint256 => mapping(uint256 => address)) private _itemOwner;
// Mapping from item ID to layer to approved address
mapping(uint256 => mapping(uint256 => address)) private _transferApprovals;
// Mapping from owner to layer to number of owned item
mapping(address => mapping(uint256 => Counters.Counter))
private _ownedItemsCount;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Mapping from item ID to approved address of setting lien
mapping(uint256 => address) private _lienApprovals;
// Mapping from item ID to contract address of lien
mapping(uint256 => address) private _lienAddress;
// Mapping from item ID to approved address of setting tenant right agreement
mapping(uint256 => address) private _tenantRightApprovals;
// Mapping from item ID to contract address of TenantRight
mapping(uint256 => address) private _tenantRightAddress;
bytes4 private constant _InterfaceId_ERCX =
bytes4(keccak256("balanceOfOwner(address)")) ^
bytes4(keccak256("balanceOfUser(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("userOf(uint256)")) ^
bytes4(keccak256("safeTransferOwner(address, address, uint256)")) ^
bytes4(
keccak256("safeTransferOwner(address, address, uint256, bytes)")
) ^
bytes4(keccak256("safeTransferUser(address, address, uint256)")) ^
bytes4(
keccak256("safeTransferUser(address, address, uint256, bytes)")
) ^
bytes4(keccak256("approveForOwner(address, uint256)")) ^
bytes4(keccak256("getApprovedForOwner(uint256)")) ^
bytes4(keccak256("approveForUser(address, uint256)")) ^
bytes4(keccak256("getApprovedForUser(uint256)")) ^
bytes4(keccak256("setApprovalForAll(address, bool)")) ^
bytes4(keccak256("isApprovedForAll(address, address)")) ^
bytes4(keccak256("approveLien(address, uint256)")) ^
bytes4(keccak256("getApprovedLien(uint256)")) ^
bytes4(keccak256("setLien(uint256)")) ^
bytes4(keccak256("getCurrentLien(uint256)")) ^
bytes4(keccak256("revokeLien(uint256)")) ^
bytes4(keccak256("approveTenantRight(address, uint256)")) ^
bytes4(keccak256("getApprovedTenantRight(uint256)")) ^
bytes4(keccak256("setTenantRight(uint256)")) ^
bytes4(keccak256("getCurrentTenantRight(uint256)")) ^
bytes4(keccak256("revokeTenantRight(uint256)"));
constructor() ERC721("vRent Non-C", "RNC") {
_owner = msg.sender;
// register the supported interfaces to conform to ERCX via ERC165
_registerInterface(_InterfaceId_ERCX);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, ERC165Storage, AccessControl)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return uint256 representing the amount of items owned by the passed address in the specified layer
*/
function balanceOfOwner(address owner)
public
view
override
returns (uint256)
{
require(owner != address(0));
uint256 balance = _ownedItemsCount[owner][2].current();
return balance;
}
/**
* @dev Gets the balance of the specified address
* @param user address to query the balance of
* @return uint256 representing the amount of items owned by the passed address
*/
function balanceOfUser(address user)
public
view
override
returns (uint256)
{
require(user != address(0));
uint256 balance = _ownedItemsCount[user][1].current();
return balance;
}
/**
* @dev Gets the user of the specified item ID
* @param itemId uint256 ID of the item to query the user of
* @return owner address currently marked as the owner of the given item ID
*/
function userOf(uint256 itemId) public view override returns (address) {
address user = _itemOwner[itemId][1];
require(user != address(0));
return user;
}
/**
* @dev Gets the owner of the specified item ID
* @param itemId uint256 ID of the item to query the owner of
* @return owner address currently marked as the owner of the given item ID
*/
function ownerOf(uint256 itemId)
public
view
override(IERCX, ERC721)
returns (address)
{
address owner = _itemOwner[itemId][2];
require(owner != address(0));
return owner;
}
/**
* @dev Approves another address to transfer the user of the given item ID
* The zero address indicates there is no approved address.
* There can only be one approved address per item at a given time.
* Can only be called by the item owner or an approved operator.
* @param to address to be approved for the given item ID
*/
function approveForUser(address to, uint256 itemId) public override {
address user = userOf(itemId);
address owner = ownerOf(itemId);
require(to != owner && to != user);
require(
msg.sender == user ||
msg.sender == owner ||
isApprovedForAll(user, msg.sender) ||
isApprovedForAll(owner, msg.sender)
);
if (msg.sender == owner || isApprovedForAll(owner, msg.sender)) {
require(getCurrentTenantRight(itemId) == address(0));
}
_transferApprovals[itemId][1] = to;
emit ApprovalForUser(user, to, itemId);
}
/**
* @dev Gets the approved address for the user of the item ID, or zero if no address set
* Reverts if the item ID does not exist.
* @param itemId uint256 ID of the item to query the approval of
* @return address currently approved for the given item ID
*/
function getApprovedForUser(uint256 itemId)
public
view
override
returns (address)
{
require(_exists(itemId, 1));
return _transferApprovals[itemId][1];
}
/**
* @dev Approves another address to transfer the owner of the given item ID
* The zero address indicates there is no approved address.
* There can only be one approved address per item at a given time.
* Can only be called by the item owner or an approved operator.
* @param to address to be approved for the given item ID
* @param itemId uint256 ID of the item to be approved
*/
function approveForOwner(address to, uint256 itemId) public override {
address owner = ownerOf(itemId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_transferApprovals[itemId][2] = to;
emit ApprovalForOwner(owner, to, itemId);
}
/**
* @dev Gets the approved address for the of the item ID, or zero if no address set
* Reverts if the item ID does not exist.
* @param itemId uint256 ID of the item to query the approval o
* @return address currently approved for the given item ID
*/
function getApprovedForOwner(uint256 itemId)
public
view
override
returns (address)
{
require(_exists(itemId, 2));
return _transferApprovals[itemId][2];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all items of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved)
public
override(IERCX, ERC721)
{
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator)
public
view
override(IERCX, ERC721)
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev Approves another address to set lien contract for the given item ID
* The zero address indicates there is no approved address.
* There can only be one approved address per item at a given time.
* Can only be called by the item owner or an approved operator.
* @param to address to be approved for the given item ID
* @param itemId uint256 ID of the item to be approved
*/
function approveLien(address to, uint256 itemId) public override {
address owner = ownerOf(itemId);
// require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_lienApprovals[itemId] = to;
emit LienApproval(to, itemId);
}
/**
* @dev Gets the approved address for setting lien for a item ID, or zero if no address set
* Reverts if the item ID does not exist.
* @param itemId uint256 ID of the item to query the approval of
* @return address currently approved for the given item ID
*/
function getApprovedLien(uint256 itemId)
public
view
override
returns (address)
{
require(_exists(itemId, 2));
return _lienApprovals[itemId];
}
/**
* @dev Sets lien agreements to already approved address
* The lien address is allowed to transfer all items of the sender on their behalf
* @param itemId uint256 ID of the item
*/
function setLien(uint256 itemId) public override {
require(msg.sender == getApprovedLien(itemId));
_lienAddress[itemId] = msg.sender;
_clearLienApproval(itemId);
emit LienSet(msg.sender, itemId, true);
}
/**
* @dev Gets the current lien agreement address, or zero if no address set
* Reverts if the item ID does not exist.
* @param itemId uint256 ID of the item to query the lien address
* @return address of the lien agreement address for the given item ID
*/
function getCurrentLien(uint256 itemId)
public
view
override
returns (address)
{
require(_exists(itemId, 2));
return _lienAddress[itemId];
}
/**
* @dev Revoke the lien agreements. Only the lien address can revoke.
* @param itemId uint256 ID of the item
*/
function revokeLien(uint256 itemId) public override {
require(msg.sender == getCurrentLien(itemId));
_lienAddress[itemId] = address(0);
emit LienSet(address(0), itemId, false);
}
/**
* @dev Approves another address to set tenant right agreement for the given item ID
* The zero address indicates there is no approved address.
* There can only be one approved address per item at a given time.
* Can only be called by the item owner or an approved operator.
* @param to address to be approved for the given item ID
* @param itemId uint256 ID of the item to be approved
*/
function approveTenantRight(address to, uint256 itemId) public override {
address owner = ownerOf(itemId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tenantRightApprovals[itemId] = to;
emit TenantRightApproval(to, itemId);
}
/**
* @dev Gets the approved address for setting tenant right for a item ID, or zero if no address set
* Reverts if the item ID does not exist.
* @param itemId uint256 ID of the item to query the approval of
* @return address currently approved for the given item ID
*/
function getApprovedTenantRight(uint256 itemId)
public
view
override
returns (address)
{
require(_exists(itemId, 2));
return _tenantRightApprovals[itemId];
}
/**
* @dev Sets the tenant right agreement to already approved address
* The lien address is allowed to transfer all items of the sender on their behalf
* @param itemId uint256 ID of the item
*/
function setTenantRight(uint256 itemId) public override {
require(msg.sender == getApprovedTenantRight(itemId));
_tenantRightAddress[itemId] = msg.sender;
_clearTenantRightApproval(itemId);
_clearTransferApproval(itemId, 1); //Reset transfer approval
emit TenantRightSet(msg.sender, itemId, true);
}
/**
* @dev Gets the current tenant right agreement address, or zero if no address set
* Reverts if the item ID does not exist.
* @param itemId uint256 ID of the item to query the tenant right address
* @return address of the tenant right agreement address for the given item ID
*/
function getCurrentTenantRight(uint256 itemId)
public
view
override
returns (address)
{
require(_exists(itemId, 2));
return _tenantRightAddress[itemId];
}
/**
* @dev Revoke the tenant right agreement. Only the lien address can revoke.
* @param itemId uint256 ID of the item
*/
function revokeTenantRight(uint256 itemId) public override {
require(msg.sender == getCurrentTenantRight(itemId));
_tenantRightAddress[itemId] = address(0);
emit TenantRightSet(address(0), itemId, false);
}
/**
* @dev Safely transfers the user of a given item ID to another address
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the item
* @param to address to receive the ownership of the given item ID
* @param itemId uint256 ID of the item to be transferred
*/
function safeTransferUser(
address from,
address to,
uint256 itemId
) public override {
// solium-disable-next-line arg-overflow
safeTransferUser(from, to, itemId, "");
}
/**
* @dev Safely transfers the user of a given item ID to another address
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the item
* @param to address to receive the ownership of the given item ID
* @param itemId uint256 ID of the item to be transferred
* @param data bytes data to send along with a safe transfer check
*/
function safeTransferUser(
address from,
address to,
uint256 itemId,
bytes memory data
) public override {
require(_isEligibleForTransfer(msg.sender, itemId, 1));
_safeTransfer(from, to, itemId, 1, data);
}
/**
* @dev Safely transfers the ownership of a given item ID to another address
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the item
* @param to address to receive the ownership of the given item ID
* @param itemId uint256 ID of the item to be transferred
*/
function safeTransferOwner(
address from,
address to,
uint256 itemId
) public override {
// solium-disable-next-line arg-overflow
safeTransferOwner(from, to, itemId, "");
}
/**
* @dev Safely transfers the ownership of a given item ID to another address
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the item
* @param to address to receive the ownership of the given item ID
* @param itemId uint256 ID of the item to be transferred
* @param data bytes data to send along with a safe transfer check
*/
function safeTransferOwner(
address from,
address to,
uint256 itemId,
bytes memory data
) public override {
require(_isEligibleForTransfer(msg.sender, itemId, 2));
_safeTransfer(from, to, itemId, 2, data);
}
/**
* @dev Safely transfers the ownership of a given item ID to another address
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the item
* @param to address to receive the ownership of the given item ID
* @param itemId uint256 ID of the item to be transferred
* @param layer uint256 number to specify the layer
* @param data bytes data to send along with a safe transfer check
*/
function _safeTransfer(
address from,
address to,
uint256 itemId,
uint256 layer,
bytes memory data
) internal {
_transfer(from, to, itemId, layer);
require(
_checkOnERCXReceived(from, to, itemId, layer, data),
"ERCX: transfer to non ERCXReceiver implementer"
);
}
/**
* @dev Returns whether the given spender can transfer a given item ID.
* @param spender address of the spender to query
* @param itemId uint256 ID of the item to be transferred
* @param layer uint256 number to specify the layer
* @return bool whether the msg.sender is approved for the given item ID,
* is an operator of the owner, or is the owner of the item
*/
function _isEligibleForTransfer(
address spender,
uint256 itemId,
uint256 layer
) internal view returns (bool) {
require(_exists(itemId, layer));
bool flag;
if (layer == 1) {
address user = userOf(itemId);
address owner = ownerOf(itemId);
require(
spender == user ||
spender == owner ||
isApprovedForAll(user, spender) ||
isApprovedForAll(owner, spender) ||
spender == getApprovedForUser(itemId) ||
spender == getCurrentLien(itemId)
);
if (spender == owner || isApprovedForAll(owner, spender)) {
require(getCurrentTenantRight(itemId) == address(0));
}
flag = true;
}
if (layer == 2) {
address owner = ownerOf(itemId);
require(
spender == owner ||
isApprovedForAll(owner, spender) ||
spender == getApprovedForOwner(itemId) ||
spender == getCurrentLien(itemId)
);
flag = true;
}
return flag;
}
/**
* @dev Returns whether the specified item exists
* @param itemId uint256 ID of the item to query the existence of
* @param layer uint256 number to specify the layer
* @return whether the item exists
*/
function _exists(uint256 itemId, uint256 layer)
internal
view
returns (bool)
{
address owner = _itemOwner[itemId][layer];
return owner != address(0);
}
/**
* @dev Internal function to safely mint a new item.
* Reverts if the given item ID already exists.
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted item
* @param itemId uint256 ID of the item to be minted
*/
function _safeMint(address to, uint256 itemId) internal override {
_safeMint(to, itemId, "");
}
/**
* @dev Internal function to safely mint a new item.
* Reverts if the given item ID already exists.
* If the target address is a contract, it must implement `onERCXReceived`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERCXReceived(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted item
* @param itemId uint256 ID of the item to be minted
* @param data bytes data to send along with a safe transfer check
*/
function _safeMint(
address to,
uint256 itemId,
bytes memory data
) internal override {
_mint(to, itemId);
require(_checkOnERCXReceived(address(0), to, itemId, 1, data));
require(_checkOnERCXReceived(address(0), to, itemId, 2, data));
}
function _mint(address to, uint256 itemId) internal override {
require(to != address(0), "ERCX: mint to the zero address");
require(!_exists(itemId, 1), "ERCX: item already minted");
_itemOwner[itemId][1] = to;
_itemOwner[itemId][2] = to;
_ownedItemsCount[to][1].increment();
_ownedItemsCount[to][2].increment();
emit TransferUser(address(0), to, itemId, msg.sender);
emit TransferOwner(address(0), to, itemId, msg.sender);
}
/**
* @dev Internal function to mint a new item.
* Reverts if the given item ID already exists.
* A new item iss minted with all three layers.
*/
function mint() external {
require(hasRole(MINTER_ROLE, msg.sender), "ERCX: Admin only");
_tokenIds.increment();
uint256 itemId = _tokenIds.current();
_mint(msg.sender, itemId);
emit TransferUser(address(0), msg.sender, itemId, msg.sender);
emit TransferOwner(address(0), msg.sender, itemId, msg.sender);
}
/**
* @dev Internal function to burn a specific item.
* Reverts if the item does not exist.
* @param itemId uint256 ID of the item being burned
*/
function _burn(uint256 itemId) internal virtual override {
address user = userOf(itemId);
address owner = ownerOf(itemId);
require(user == msg.sender && owner == msg.sender);
_clearTransferApproval(itemId, 1);
_clearTransferApproval(itemId, 2);
_ownedItemsCount[user][1].decrement();
_ownedItemsCount[owner][2].decrement();
_itemOwner[itemId][1] = address(0);
_itemOwner[itemId][2] = address(0);
emit TransferUser(user, address(0), itemId, msg.sender);
emit TransferOwner(owner, address(0), itemId, msg.sender);
}
/**
* @dev Internal function to transfer ownership of a given item ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the item
* @param to address to receive the ownership of the given item ID
* @param itemId uint256 ID of the item to be transferred
* @param layer uint256 number to specify the layer
*/
function _transfer(
address from,
address to,
uint256 itemId,
uint256 layer
) internal virtual {
if (layer == 1) {
require(userOf(itemId) == from);
} else {
require(ownerOf(itemId) == from);
}
require(to != address(0));
_clearTransferApproval(itemId, layer);
if (layer == 2) {
_clearLienApproval(itemId);
_clearTenantRightApproval(itemId);
}
_ownedItemsCount[from][layer].decrement();
_ownedItemsCount[to][layer].increment();
_itemOwner[itemId][layer] = to;
if (layer == 1) {
emit TransferUser(from, to, itemId, msg.sender);
} else {
emit TransferOwner(from, to, itemId, msg.sender);
}
}
/**
* @dev Internal function to invoke {IERCXReceiver-onERCXReceived} on a target address.
* The call is not executed if the target address is not a contract.
*
* This is an internal detail of the `ERCX` contract and its use is deprecated.
* @param from address representing the previous owner of the given item ID
* @param to target address that will receive the items
* @param itemId uint256 ID of the item to be transferred
* @param layer uint256 number to specify the layer
* @param data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERCXReceived(
address from,
address to,
uint256 itemId,
uint256 layer,
bytes memory data
) internal returns (bool) {
if (!to.isContract()) {
return true;
}
bytes4 retval = IERCXReceiver(to).onERCXReceived(
msg.sender,
from,
itemId,
layer,
data
);
return (retval == _ERCX_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given item ID.
* @param itemId uint256 ID of the item to be transferred
* @param layer uint256 number to specify the layer
*/
function _clearTransferApproval(uint256 itemId, uint256 layer) private {
if (_transferApprovals[itemId][layer] != address(0)) {
_transferApprovals[itemId][layer] = address(0);
}
}
function _clearTenantRightApproval(uint256 itemId) private {
if (_tenantRightApprovals[itemId] != address(0)) {
_tenantRightApprovals[itemId] = address(0);
}
}
function _clearLienApproval(uint256 itemId) private {
if (_lienApprovals[itemId] != address(0)) {
_lienApprovals[itemId] = address(0);
}
}
}
//SPDX-License-Identifier: un-licensed
pragma solidity ^0.8.0;
interface IERCX {
event TransferUser(
address indexed from,
address indexed to,
uint256 indexed itemId,
address operator
);
event ApprovalForUser(
address indexed user,
address indexed approved,
uint256 itemId
);
event TransferOwner(
address indexed from,
address indexed to,
uint256 indexed itemId,
address operator
);
event ApprovalForOwner(
address indexed owner,
address indexed approved,
uint256 itemId
);
event LienApproval(address indexed to, uint256 indexed itemId);
event TenantRightApproval(address indexed to, uint256 indexed itemId);
event LienSet(address indexed to, uint256 indexed itemId, bool status);
event TenantRightSet(
address indexed to,
uint256 indexed itemId,
bool status
);
function balanceOfOwner(address owner) external view returns (uint256);
function balanceOfUser(address user) external view returns (uint256);
function userOf(uint256 itemId) external view returns (address);
function ownerOf(uint256 itemId) external view returns (address);
function safeTransferOwner(address from, address to, uint256 itemId) external;
function safeTransferOwner(
address from,
address to,
uint256 itemId,
bytes memory data
) external;
function safeTransferUser(address from, address to, uint256 itemId) external;
function safeTransferUser(
address from,
address to,
uint256 itemId,
bytes memory data
) external;
function approveForOwner(address to, uint256 itemId) external;
function getApprovedForOwner(uint256 itemId) external view returns (address);
function approveForUser(address to, uint256 itemId) external;
function getApprovedForUser(uint256 itemId) external view returns (address);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address requester, address operator)
external
view
returns (bool);
function approveLien(address to, uint256 itemId) external;
function getApprovedLien(uint256 itemId) external view returns (address);
function setLien(uint256 itemId) external;
function getCurrentLien(uint256 itemId) external view returns (address);
function revokeLien(uint256 itemId) external;
function approveTenantRight(address to, uint256 itemId) external;
function getApprovedTenantRight(uint256 itemId)
external
view
returns (address);
function setTenantRight(uint256 itemId) external;
function getCurrentTenantRight(uint256 itemId)
external
view
returns (address);
function revokeTenantRight(uint256 itemId) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library 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
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
//SPDX-License-Identifier: un-licensed
pragma solidity ^0.8.0;
/**
* @title ERCX token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERCX asset contracts.
*/
interface IERCXReceiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERCX smart contract calls this function on the recipient
* after a {IERCX-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERCXReceived.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERCX contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param itemId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERCXReceived(address,address,uint256,uint256,bytes)"))`
*/
function onERCXReceived(
address operator,
address from,
uint256 itemId,
uint256 layer,
bytes memory data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Storage.sol)
pragma solidity ^0.8.0;
import "./ERC165.sol";
/**
* @dev Storage based implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Storage is ERC165 {
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return super.supportsInterface(interfaceId) || _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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
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 {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @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 {AccessControl-_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) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @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) external;
/**
* @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) external;
/**
* @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) external;
} | * @dev Tells whether an operator is approved by a given owner @param owner owner address which you want to query the approval of @param operator operator address which you want to query the approval of @return bool whether the given operator is approved by the given owner/ | function isApprovedForAll(address owner, address operator)
public
view
override(IERCX, ERC721)
returns (bool)
{
return _operatorApprovals[owner][operator];
}
| 621,149 | [
1,
21009,
87,
2856,
392,
3726,
353,
20412,
635,
279,
864,
3410,
225,
3410,
3410,
1758,
1492,
1846,
2545,
358,
843,
326,
23556,
434,
225,
3726,
3726,
1758,
1492,
1846,
2545,
358,
843,
326,
23556,
434,
327,
1426,
2856,
326,
864,
3726,
353,
20412,
635,
326,
864,
3410,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
31639,
1290,
1595,
12,
2867,
3410,
16,
1758,
3726,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
3849,
12,
45,
654,
39,
60,
16,
4232,
39,
27,
5340,
13,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
389,
9497,
12053,
4524,
63,
8443,
6362,
9497,
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
] |
/**
Copyright (c) 2018, ZSC Dev Team
2018-10-19: v0.00.01
*/
pragma solidity ^0.4.25;
// pragma experimental ABIEncoderV2;
import "../common/hashmap.sol";
import "../common/delegate.sol";
contract InsuranceTemplate is Delegate {
address private tempMgr_;
modifier _onlyAdminOrHigher() {
require(checkDelegate(msg.sender, 2));
_;
}
constructor() public {
tempMgr_ = new Hashmap();
}
/** [desc] Destroy the contract.
* [param] none.
* [return] none.
*/
function destroy() external _onlyOwner {
Hashmap(tempMgr_).kill();
tempMgr_ = address(0);
super.kill();
}
/** [desc] update template.
* [param] _key: key of template.
* [param] _data: data of template.
* [return] none.
*/
function update(string _key, string _data) external _onlyAdminOrHigher {
// check param
require(0 != bytes(_key).length);
require(0 != bytes(_data).length);
Hashmap(tempMgr_).set(_key, 0, _data, address(0), uint(0));
}
/** [desc] remove template.
* [param] _key: key of template.
* [return] none.
*/
function remove(string _key) external _onlyAdminOrHigher {
// check param
require(0 != bytes(_key).length);
Hashmap(tempMgr_).remove(_key);
}
/** [desc] Get size of templates.
* [param] none.
* [return] size of templates.
*/
function size() external view returns (uint) {
return Hashmap(tempMgr_).size(true);
}
/** [desc] Get template by key.
* [param] _key: key of template.
* [return] error code and template data.
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function getByKey(string _key) external view returns (int, string) {
// check param
if (0 == bytes(_key).length) {
return (-1, "");
}
int error = 0;
uint8 positon = 0;
string memory value = "";
address data1 = address(0);
uint data2 = uint(0);
(error, positon, value, data1, data2) = Hashmap(tempMgr_).get(_key, true);
return (error, value);
}
/** [desc] Get template by id.
* [param] _id: _id of template.
* [return] error code and template key/data.
* 0: success
* -1: params error
* -2: no data
* -3: no authority
* -9: inner error
*/
function getById(uint _id) external view returns (int, string, string) {
// check param
if (Hashmap(tempMgr_).size(true) <= _id) {
return (-1, "", "");
}
int error = 0;
string memory key = "";
uint8 positon = 0;
string memory value = "";
address data1 = address(0);
uint data2 = uint(0);
(error, key, positon, value, data1, data2) = Hashmap(tempMgr_).get(_id, true);
return (error, key, value);
}
}
| * [desc] Get template by id. [param] _id: _id of template. [return] error code and template key/data. 0: success -1: params error -2: no data -3: no authority -9: inner error/ check param | function getById(uint _id) external view returns (int, string, string) {
if (Hashmap(tempMgr_).size(true) <= _id) {
return (-1, "", "");
}
int error = 0;
string memory key = "";
uint8 positon = 0;
string memory value = "";
address data1 = address(0);
uint data2 = uint(0);
(error, key, positon, value, data1, data2) = Hashmap(tempMgr_).get(_id, true);
return (error, key, value);
}
| 12,805,805 | [
1,
63,
5569,
65,
968,
1542,
635,
612,
18,
306,
891,
65,
389,
350,
30,
389,
350,
434,
1542,
18,
306,
2463,
65,
555,
981,
471,
1542,
498,
19,
892,
18,
6647,
374,
30,
2216,
1850,
300,
21,
30,
859,
555,
1850,
300,
22,
30,
1158,
501,
1850,
300,
23,
30,
1158,
11675,
1850,
300,
29,
30,
3443,
555,
19,
866,
579,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
22191,
12,
11890,
389,
350,
13,
3903,
1476,
1135,
261,
474,
16,
533,
16,
533,
13,
288,
203,
3639,
309,
261,
2310,
1458,
12,
5814,
9455,
67,
2934,
1467,
12,
3767,
13,
1648,
389,
350,
13,
288,
203,
5411,
327,
24927,
21,
16,
23453,
1408,
1769,
203,
3639,
289,
203,
203,
3639,
509,
555,
273,
374,
31,
203,
3639,
533,
3778,
498,
273,
1408,
31,
203,
3639,
2254,
28,
949,
26949,
273,
374,
31,
203,
3639,
533,
3778,
460,
273,
1408,
31,
203,
3639,
1758,
501,
21,
273,
1758,
12,
20,
1769,
203,
3639,
2254,
501,
22,
273,
2254,
12,
20,
1769,
203,
203,
3639,
261,
1636,
16,
498,
16,
949,
26949,
16,
460,
16,
501,
21,
16,
501,
22,
13,
273,
2474,
1458,
12,
5814,
9455,
67,
2934,
588,
24899,
350,
16,
638,
1769,
540,
203,
3639,
327,
261,
1636,
16,
498,
16,
460,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/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 {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/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.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.7.5;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "./exchange/Exchange.sol";
import "./registry/ProxyRegistry.sol";
import "./modules/VindergoodTransferProxy.sol";
import "./modules/ERC20.sol";
contract VindergoodExchange is Exchange {
string public constant name = "Vindergood Exchange";
/**
* @dev Initialize a VindergoodExchange instance
* @param registryAddress Address of the registry instance which this Exchange instance will use
* @param tokenAddress Address of the token used for protocol fees
*/
function initialize(
ProxyRegistry registryAddress,
VindergoodTransferProxy tokenTransferProxyAddress,
ERC20 tokenAddress
) public initializer {
registry = registryAddress;
tokenTransferProxy = tokenTransferProxyAddress;
exchangeToken = tokenAddress;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../libraries/ArrayUtils.sol";
import "../libraries/SaleKindInterface.sol";
import "../registry/ProxyRegistry.sol";
import "../modules/VindergoodTransferProxy.sol";
import "../registry/AuthenticatedProxy.sol";
import "./ExchangeMain.sol";
contract Exchange is ExchangeMain {
/**
* @dev Call calculateFinalPrice - library function exposed for testing.
*/
function calculateFinalPrice(
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
uint256 basePrice,
uint256 extra,
uint256 listingTime,
uint256 expirationTime,
uint256 amount
) public view returns (uint256) {
return
SaleKindInterface.calculateFinalPrice(
side,
saleKind,
basePrice,
extra,
listingTime,
expirationTime,
amount
);
}
/**
* @dev Call hashOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function hashOrder_(
address[7] memory addrs,
uint256[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata
) public pure returns (bytes32) {
return
hashOrder(
Order(
addrs[0],
addrs[1],
addrs[2],
uints[0],
uints[1],
addrs[3],
feeMethod,
side,
saleKind,
addrs[4],
howToCall,
callData,
replacementPattern,
addrs[5],
staticExtradata,
addrs[6],
uints[2],
uints[3],
uints[4],
uints[5],
uints[6]
)
);
}
/**
* @dev Call hashToSign - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function hashToSign_(
address[7] memory addrs,
uint256[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata
) public pure returns (bytes32) {
return
hashToSign(
Order(
addrs[0],
addrs[1],
addrs[2],
uints[0],
uints[1],
addrs[3],
feeMethod,
side,
saleKind,
addrs[4],
howToCall,
callData,
replacementPattern,
addrs[5],
staticExtradata,
addrs[6],
uints[2],
uints[3],
uints[4],
uints[5],
uints[6]
)
);
}
/**
* @dev Call validateOrderParameters - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function validateOrderParameters_(
address[7] memory addrs,
uint256[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata
) public view returns (bool) {
Order memory order = Order(
addrs[0],
addrs[1],
addrs[2],
uints[0],
uints[1],
addrs[3],
feeMethod,
side,
saleKind,
addrs[4],
howToCall,
callData,
replacementPattern,
addrs[5],
staticExtradata,
addrs[6],
uints[2],
uints[3],
uints[4],
uints[5],
uints[6]
);
return validateOrderParameters(order);
}
/**
* @dev Call validateOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function validateOrder_(
address[7] memory addrs,
uint256[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata,
uint8 v,
bytes32 r,
bytes32 s
) public view returns (bool) {
Order memory order = Order(
addrs[0],
addrs[1],
addrs[2],
uints[0],
uints[1],
addrs[3],
feeMethod,
side,
saleKind,
addrs[4],
howToCall,
callData,
replacementPattern,
addrs[5],
staticExtradata,
addrs[6],
uints[2],
uints[3],
uints[4],
uints[5],
uints[6]
);
return validateOrder(hashToSign(order), order, Sig(v, r, s));
}
/**
* @dev Call approveOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function approveOrder_(
address[7] memory addrs,
uint256[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata,
bool orderbookInclusionDesired
) public {
Order memory order = Order(
addrs[0],
addrs[1],
addrs[2],
uints[0],
uints[1],
addrs[3],
feeMethod,
side,
saleKind,
addrs[4],
howToCall,
callData,
replacementPattern,
addrs[5],
staticExtradata,
addrs[6],
uints[2],
uints[3],
uints[4],
uints[5],
uints[6]
);
return approveOrder(order, orderbookInclusionDesired);
}
/**
* @dev Call cancelOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function cancelOrder_(
address[7] memory addrs,
uint256[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata,
uint8 v,
bytes32 r,
bytes32 s
) public {
return
cancelOrder(
Order(
addrs[0],
addrs[1],
addrs[2],
uints[0],
uints[1],
addrs[3],
feeMethod,
side,
saleKind,
addrs[4],
howToCall,
callData,
replacementPattern,
addrs[5],
staticExtradata,
addrs[6],
uints[2],
uints[3],
uints[4],
uints[5],
uints[6]
),
Sig(v, r, s)
);
}
/**
* @dev Call calculateCurrentPrice - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function calculateCurrentPrice_(
address[7] memory addrs,
uint256[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata,
uint256 amount
) public view returns (uint256) {
return
calculateCurrentPrice(
Order(
addrs[0],
addrs[1],
addrs[2],
uints[0],
uints[1],
addrs[3],
feeMethod,
side,
saleKind,
addrs[4],
howToCall,
callData,
replacementPattern,
addrs[5],
staticExtradata,
addrs[6],
uints[2],
uints[3],
uints[4],
uints[5],
uints[6]
),
amount
);
}
/**
* @dev Call ordersCanMatch - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function ordersCanMatch_(
address[14] memory addrs,
uint256[14] memory uints,
uint8[8] memory feeMethodsSidesKindsHowToCalls,
bytes memory calldataBuy,
bytes memory calldataSell,
bytes memory replacementPatternBuy,
bytes memory replacementPatternSell,
bytes memory staticExtradataBuy,
bytes memory staticExtradataSell
) public view returns (bool) {
Order memory buy = Order(
addrs[0],
addrs[1],
addrs[2],
uints[0],
uints[1],
addrs[3],
FeeMethod(feeMethodsSidesKindsHowToCalls[0]),
SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]),
SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]),
addrs[4],
AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]),
calldataBuy,
replacementPatternBuy,
addrs[5],
staticExtradataBuy,
addrs[6],
uints[2],
uints[3],
uints[4],
uints[5],
uints[6]
);
Order memory sell = Order(
addrs[7],
addrs[8],
addrs[9],
uints[7],
uints[8],
addrs[10],
FeeMethod(feeMethodsSidesKindsHowToCalls[4]),
SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]),
SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]),
addrs[11],
AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]),
calldataSell,
replacementPatternSell,
addrs[12],
staticExtradataSell,
addrs[13],
uints[9],
uints[10],
uints[11],
uints[12],
uints[13]
);
return ordersCanMatch(buy, sell);
}
/**
* @dev Return whether or not two orders' calldata specifications can match
* @param buyCalldata Buy-side order calldata
* @param buyReplacementPattern Buy-side order calldata replacement mask
* @param sellCalldata Sell-side order calldata
* @param sellReplacementPattern Sell-side order calldata replacement mask
* @return Whether the orders' calldata can be matched
*/
function orderCalldataCanMatch(
bytes memory buyCalldata,
bytes memory buyReplacementPattern,
bytes memory sellCalldata,
bytes memory sellReplacementPattern
) public pure returns (bool) {
if (buyReplacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(
buyCalldata,
sellCalldata,
buyReplacementPattern
);
}
if (sellReplacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(
sellCalldata,
buyCalldata,
sellReplacementPattern
);
}
return ArrayUtils.arrayEq(buyCalldata, sellCalldata);
}
/**
* @dev Call calculateMatchPrice - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function calculateMatchPrice_(
address[14] memory addrs,
uint256[14] memory uints,
uint8[8] memory feeMethodsSidesKindsHowToCalls,
bytes memory calldataBuy,
bytes memory calldataSell,
bytes memory replacementPatternBuy,
bytes memory replacementPatternSell,
bytes memory staticExtradataBuy,
bytes memory staticExtradataSell,
uint256 amount
) public view returns (uint256) {
Order memory buy = Order(
addrs[0],
addrs[1],
addrs[2],
uints[0],
uints[1],
addrs[3],
FeeMethod(feeMethodsSidesKindsHowToCalls[0]),
SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]),
SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]),
addrs[4],
AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]),
calldataBuy,
replacementPatternBuy,
addrs[5],
staticExtradataBuy,
addrs[6],
uints[2],
uints[3],
uints[4],
uints[5],
uints[6]
);
Order memory sell = Order(
addrs[7],
addrs[8],
addrs[9],
uints[7],
uints[8],
addrs[10],
FeeMethod(feeMethodsSidesKindsHowToCalls[4]),
SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]),
SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]),
addrs[11],
AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]),
calldataSell,
replacementPatternSell,
addrs[12],
staticExtradataSell,
addrs[13],
uints[9],
uints[10],
uints[11],
uints[12],
uints[13]
);
return calculateMatchPrice(buy, sell, amount);
}
/**
* @dev Call atomicMatch - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function atomicMatch_(
address[14] memory addrs,
uint256[14] memory uints,
uint8[8] memory feeMethodsSidesKindsHowToCalls,
bytes memory calldataBuy,
bytes memory calldataSell,
bytes memory replacementPatternBuy,
bytes memory replacementPatternSell,
bytes memory staticExtradataBuy,
bytes memory staticExtradataSell,
uint8[2] memory vs,
bytes32[5] memory rssMetadata
) public payable {
return
atomicMatch(
Order(
addrs[0],
addrs[1],
addrs[2],
uints[0],
uints[1],
addrs[3],
FeeMethod(feeMethodsSidesKindsHowToCalls[0]),
SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]),
SaleKindInterface.SaleKind(
feeMethodsSidesKindsHowToCalls[2]
),
addrs[4],
AuthenticatedProxy.HowToCall(
feeMethodsSidesKindsHowToCalls[3]
),
calldataBuy,
replacementPatternBuy,
addrs[5],
staticExtradataBuy,
addrs[6],
uints[2],
uints[3],
uints[4],
uints[5],
uints[6]
),
Sig(vs[0], rssMetadata[0], rssMetadata[1]),
Order(
addrs[7],
addrs[8],
addrs[9],
uints[7],
uints[8],
addrs[10],
FeeMethod(feeMethodsSidesKindsHowToCalls[4]),
SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]),
SaleKindInterface.SaleKind(
feeMethodsSidesKindsHowToCalls[6]
),
addrs[11],
AuthenticatedProxy.HowToCall(
feeMethodsSidesKindsHowToCalls[7]
),
calldataSell,
replacementPatternSell,
addrs[12],
staticExtradataSell,
addrs[13],
uints[9],
uints[10],
uints[11],
uints[12],
uints[13]
),
Sig(vs[1], rssMetadata[2], rssMetadata[3]),
rssMetadata[4]
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "../libraries/LibPart.sol";
import "../royalties/RoyaltiesV2.sol";
import "../libraries/ArrayUtils.sol";
import "../libraries/SaleKindInterface.sol";
import "../registry/ProxyRegistry.sol";
import "../modules/ERC20.sol";
import "../modules/VindergoodTransferProxy.sol";
import "../registry/AuthenticatedProxy.sol";
import "../interfaces/IVindergoodStore.sol";
contract ExchangeMain is ReentrancyGuardUpgradeable {
/* The token used to pay exchange fees. */
ERC20 public exchangeToken;
bytes4 constant ERC1155_SIGNATURE = 0x127217d6;
/* User registry. */
ProxyRegistry public registry;
/* Token transfer proxy. */
VindergoodTransferProxy public tokenTransferProxy;
struct SellRemaining {
bool tracking;
uint256 left;
}
mapping(bytes32 => SellRemaining) public sellOrderAmountRemaining;
/* Cancelled / finalized orders, by hash. */
mapping(bytes32 => bool) public cancelledOrFinalized;
/* Orders verified by on-chain approval (alternative to ECDSA signatures so that smart contracts can place orders directly). */
mapping(bytes32 => bool) public approvedOrders;
// /* For split fee orders, minimum required protocol maker fee, in basis points. Paid to owner (who can change it). */
// uint public minimumMakerProtocolFee = 0;
// /* For split fee orders, minimum required protocol taker fee, in basis points. Paid to owner (who can change it). */
// uint public minimumTakerProtocolFee = 0;
// /* Recipient of protocol fees. */
// address public protocolFeeRecipient;
/* Fee method: protocol fee or split fee. */
enum FeeMethod {
ProtocolFee,
SplitFee
}
/* Inverse basis point. */
uint256 public constant INVERSE_BASIS_POINT = 10000;
/* An ECDSA signature. */
struct Sig {
/* v parameter */
uint8 v;
/* r parameter */
bytes32 r;
/* s parameter */
bytes32 s;
}
/* An order on the exchange. */
struct Order {
/* Exchange address, intended as a versioning mechanism. */
address exchange;
/* Order maker address. */
address maker;
/* Order taker address, if specified. */
address taker;
/* Maker relayer fee of the order, unused for taker order. */
uint256 makerRelayerFee;
/* Taker relayer fee of the order, or maximum taker fee for a taker order. */
uint256 takerRelayerFee;
// /* Maker protocol fee of the order, unused for taker order. */
// uint makerProtocolFee;
// /* Taker protocol fee of the order, or maximum taker fee for a taker order. */
// uint takerProtocolFee;
/* Order fee recipient or zero address for taker order. */
address feeRecipient;
/* Fee method (protocol token or split fee). */
FeeMethod feeMethod;
/* Side (buy/sell). */
SaleKindInterface.Side side;
/* Kind of sale. */
SaleKindInterface.SaleKind saleKind;
/* Target. */
address target;
/* HowToCall. */
AuthenticatedProxy.HowToCall howToCall;
/* Calldata. */
bytes callData;
bytes replacementPattern;
/* Calldata replacement pattern, or an empty byte array for no replacement. */
// bytes replacementPattern;
// /* Static call target, zero-address for no static call. */
address staticTarget;
/* Static call extra data. */
bytes staticExtradata;
/* Token used to pay for the order, or the zero-address as a sentinel value for Ether. */
address paymentToken;
/* Base price of the order (in paymentTokens). */
uint256 basePrice;
/* Auction extra parameter - minimum bid increment for English auctions, starting/ending price difference. */
uint256 extra;
/* Listing timestamp. */
uint256 listingTime;
/* Expiration timestamp - 0 for no expiry. */
uint256 expirationTime;
/* Order salt, used to prevent duplicate hashes. */
uint256 salt;
}
event OrderApprovedPartOne(
bytes32 indexed hash,
address exchange,
address indexed maker,
address taker,
uint256 makerRelayerFee,
uint256 takerRelayerFee,
address indexed feeRecipient,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
address target
);
event OrderApprovedPartTwo(
bytes32 indexed hash,
AuthenticatedProxy.HowToCall howToCall,
bytes callData,
address staticTarget,
bytes staticExtradata,
address paymentToken,
uint256 basePrice,
uint256 extra,
uint256 listingTime,
uint256 expirationTime,
uint256 salt,
bool orderbookInclusionDesired
);
// event OrderApprovedPartOne (bytes32 indexed hash, address exchange, address indexed maker, address taker, uint makerRelayerFee, uint takerRelayerFee, uint makerProtocolFee, uint takerProtocolFee, address indexed feeRecipient, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, address target);
// event OrderApprovedPartTwo (bytes32 indexed hash, AuthenticatedProxy.HowToCall howToCall, bytes callData, bytes replacementPattern, address staticTarget, bytes staticExtradata, address paymentToken, uint basePrice, uint extra, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired);
event OrderCancelled(bytes32 indexed hash);
event OrdersMatched(
bytes32 buyHash,
bytes32 sellHash,
address indexed maker,
address indexed taker,
uint256 price,
bytes32 indexed metadata
);
// /**
// * @dev Change the minimum maker fee paid to the protocol (owner only)
// * @param newMinimumMakerProtocolFee New fee to set in basis points
// */
// function changeMinimumMakerProtocolFee(uint newMinimumMakerProtocolFee)
// public
// onlyOwner
// {
// minimumMakerProtocolFee = newMinimumMakerProtocolFee;
// }
// /**
// * @dev Change the minimum taker fee paid to the protocol (owner only)
// * @param newMinimumTakerProtocolFee New fee to set in basis points
// */
// function changeMinimumTakerProtocolFee(uint newMinimumTakerProtocolFee)
// public
// onlyOwner
// {
// minimumTakerProtocolFee = newMinimumTakerProtocolFee;
// }
// /**
// * @dev Change the protocol fee recipient (owner only)
// * @param newProtocolFeeRecipient New protocol fee recipient address
// */
// function changeProtocolFeeRecipient(address newProtocolFeeRecipient)
// public
// onlyOwner
// {
// protocolFeeRecipient = newProtocolFeeRecipient;
// }
// function changeDefaultCollection(address _newCollection) public onlyOwner {
// require(
// _newCollection != defaultCollection,
// "VindergoodExchange::New collection address is the same"
// );
// defaultCollection = _newCollection;
// }
/**
* @dev Transfer tokens
* @param token Token to transfer
* @param from Address to charge fees
* @param to Address to receive fees
* @param amount Amount of protocol tokens to charge
*/
function transferTokens(
address token,
address from,
address to,
uint256 amount
) internal {
if (amount > 0) {
tokenTransferProxy.transferFrom(token, from, to, amount);
}
}
/**
* @dev Charge a fee in protocol tokens
* @param from Address to charge fees
* @param to Address to receive fees
* @param amount Amount of protocol tokens to charge
*/
function chargeProtocolFee(
address from,
address to,
uint256 amount
) internal {
transferTokens(address(exchangeToken), from, to, amount);
}
/**
* @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call)
* @param target Contract to call
* @param callData Calldata (appended to extradata)
* @param extradata Base data for STATICCALL (probably function selector and argument encoding)
*/
// function staticCall(address target, bytes memory callData, bytes memory extradata)
// public
// view
// returns (bool result)
// {
// bytes memory combined = new bytes(callData.length + extradata.length);
// uint index;
// assembly {
// index := add(combined, 0x20)
// }
// index = ArrayUtils.unsafeWriteBytes(index, extradata);
// ArrayUtils.unsafeWriteBytes(index, callData);
// assembly {
// result := staticcall(gas(), target, add(combined, 0x20), mload(combined), mload(0x40), 0)
// }
// return result;
// }
/**
* Calculate size of an order struct when tightly packed
*
* @param order Order to calculate size of
* @return Size in bytes
*/
function sizeOf(Order memory order) internal pure returns (uint256) {
return ((0x14 * 7) +
(0x20 * 9) +
4 +
order.callData.length +
order.replacementPattern.length +
order.staticExtradata.length);
// return ((0x14 * 7) + (0x20 * 9) + 4 + order.callData.length + order.replacementPattern.length + order.staticExtradata.length);
}
/**
* @dev Hash an order, returning the canonical order hash, without the message prefix
* @param order Order to hash
*/
function hashOrder(Order memory order)
internal
pure
returns (bytes32 hash)
{
/* Unfortunately abi.encodePacked doesn't work here, stack size constraints. */
uint256 size = sizeOf(order);
bytes memory array = new bytes(size);
uint256 index;
assembly {
index := add(array, 0x20)
}
index = ArrayUtils.unsafeWriteAddress(index, order.exchange);
index = ArrayUtils.unsafeWriteAddress(index, order.maker);
index = ArrayUtils.unsafeWriteAddress(index, order.taker);
index = ArrayUtils.unsafeWriteUint(index, order.makerRelayerFee);
index = ArrayUtils.unsafeWriteUint(index, order.takerRelayerFee);
// index = ArrayUtils.unsafeWriteUint(index, order.makerProtocolFee);
// index = ArrayUtils.unsafeWriteUint(index, order.takerProtocolFee);
index = ArrayUtils.unsafeWriteAddress(index, order.feeRecipient);
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.feeMethod));
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.side));
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.saleKind));
index = ArrayUtils.unsafeWriteAddress(index, order.target);
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.howToCall));
index = ArrayUtils.unsafeWriteBytes(index, order.callData);
index = ArrayUtils.unsafeWriteBytes(index, order.replacementPattern);
index = ArrayUtils.unsafeWriteAddress(index, order.staticTarget);
index = ArrayUtils.unsafeWriteBytes(index, order.staticExtradata);
index = ArrayUtils.unsafeWriteAddress(index, order.paymentToken);
index = ArrayUtils.unsafeWriteUint(index, order.basePrice);
index = ArrayUtils.unsafeWriteUint(index, order.extra);
index = ArrayUtils.unsafeWriteUint(index, order.listingTime);
index = ArrayUtils.unsafeWriteUint(index, order.expirationTime);
index = ArrayUtils.unsafeWriteUint(index, order.salt);
assembly {
hash := keccak256(add(array, 0x20), size)
}
return hash;
}
/**
* @dev Hash an order, returning the hash that a client must sign, including the standard message prefix
* @param order Order to hash
* @return Hash of message prefix and order hash per Ethereum format
*/
function hashToSign(Order memory order) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
hashOrder(order)
)
);
}
/**
* @dev Assert an order is valid and return its hash
* @param order Order to validate
* @param sig ECDSA signature
*/
function requireValidOrder(Order memory order, Sig memory sig)
internal
view
returns (bytes32)
{
bytes32 hash = hashToSign(order);
require(validateOrder(hash, order, sig), "INVALID_ORDER_HASH");
return hash;
}
/**
* @dev Validate order parameters (does *not* check signature validity)
* @param order Order to validate
*/
function validateOrderParameters(Order memory order)
internal
view
returns (bool)
{
/* Order must be targeted at this protocol version (this Exchange contract). */
if (order.exchange != address(this)) {
return false;
}
/* Order must possess valid sale kind parameter combination. */
if (
!SaleKindInterface.validateParameters(
order.saleKind,
order.expirationTime
)
) {
return false;
}
// /* If using the split fee method, order must have sufficient protocol fees. */
// if (order.feeMethod == FeeMethod.SplitFee && (order.makerProtocolFee < minimumMakerProtocolFee || order.takerProtocolFee < minimumTakerProtocolFee)) {
// return false;
// }
return true;
}
/**
* @dev Validate a provided previously approved / signed order, hash, and signature.
* @param hash Order hash (already calculated, passed to avoid recalculation)
* @param order Order to validate
* @param sig ECDSA signature
*/
function validateOrder(
bytes32 hash,
Order memory order,
Sig memory sig
) internal view returns (bool) {
/* Not done in an if-conditional to prevent unnecessary ecrecover evaluation, which seems to happen even though it should short-circuit. */
/* Order must have valid parameters. */
if (!validateOrderParameters(order)) {
return false;
}
/* Order must have not been canceled or already filled. */
if (cancelledOrFinalized[hash]) {
return false;
}
/* Order authentication. Order must be either:
/* (a) previously approved */
if (approvedOrders[hash]) {
return true;
}
/* or (b) ECDSA-signed by maker. */
if (ecrecover(hash, sig.v, sig.r, sig.s) == order.maker) {
return true;
}
return false;
}
/**
* @dev Approve an order and optionally mark it for orderbook inclusion. Must be called by the maker of the order
* @param order Order to approve
* @param orderbookInclusionDesired Whether orderbook providers should include the order in their orderbooks
*/
function approveOrder(Order memory order, bool orderbookInclusionDesired)
internal
{
/* CHECKS */
/* Assert sender is authorized to approve order. */
require(msg.sender == order.maker);
/* Calculate order hash. */
bytes32 hash = hashToSign(order);
/* Assert order has not already been approved. */
require(!approvedOrders[hash]);
/* EFFECTS */
/* Mark order as approved. */
approvedOrders[hash] = true;
/* Log approval event. Must be split in two due to Solidity stack size limitations. */
{
emit OrderApprovedPartOne(
hash,
order.exchange,
order.maker,
order.taker,
order.makerRelayerFee,
order.takerRelayerFee,
order.feeRecipient,
order.feeMethod,
order.side,
order.saleKind,
order.target
);
}
{
emit OrderApprovedPartTwo(
hash,
order.howToCall,
order.callData,
order.staticTarget,
order.staticExtradata,
order.paymentToken,
order.basePrice,
order.extra,
order.listingTime,
order.expirationTime,
order.salt,
orderbookInclusionDesired
);
}
}
/**
* @dev Cancel an order, preventing it from being matched. Must be called by the maker of the order
* @param order Order to cancel
* @param sig ECDSA signature
*/
function cancelOrder(Order memory order, Sig memory sig) internal {
/* CHECKS */
/* Calculate order hash. */
bytes32 hash = requireValidOrder(order, sig);
/* Assert sender is authorized to cancel order. */
require(msg.sender == order.maker);
/* Mark order as cancelled, preventing it from being matched. */
cancelledOrFinalized[hash] = true;
/* Log cancel event. */
emit OrderCancelled(hash);
}
/**
* @dev Calculate the current price of an order (convenience function)
* @param order Order to calculate the price of
* @return The current price of the order
*/
function calculateCurrentPrice(Order memory order, uint256 amount)
internal
view
returns (uint256)
{
return
SaleKindInterface.calculateFinalPrice(
order.side,
order.saleKind,
order.basePrice,
order.extra,
order.listingTime,
order.expirationTime,
amount
);
}
/**
* @dev Calculate the price two orders would match at, if in fact they would match (otherwise fail)
* @param buy Buy-side order
* @param sell Sell-side order
* @return Match price
*/
function calculateMatchPrice(
Order memory buy,
Order memory sell,
uint256 amount
) internal view returns (uint256) {
/* Calculate sell price. */
uint256 sellPrice = SaleKindInterface.calculateFinalPrice(
sell.side,
sell.saleKind,
sell.basePrice,
sell.extra,
sell.listingTime,
sell.expirationTime,
amount
);
/* Calculate buy price. */
uint256 buyPrice = SaleKindInterface.calculateFinalPrice(
buy.side,
buy.saleKind,
buy.basePrice,
buy.extra,
buy.listingTime,
buy.expirationTime,
amount
);
/* Require price cross. */
require(buyPrice >= sellPrice);
/* Maker/taker priority. */
return sell.feeRecipient != address(0) ? sellPrice : buyPrice;
}
/**
* @dev Execute all ERC20 token / Ether transfers associated with an order match (fees and buyer => seller transfer)
* @param buy Buy-side order
* @param sell Sell-side order
*/
function executeFundsTransfer(
Order memory buy,
Order memory sell,
LibPart.Part memory royalty,
uint256 amount
) internal returns (uint256) {
/* Only payable in the special case of unwrapped Ether. */
if (sell.paymentToken != address(0)) {
require(msg.value == 0);
}
/* Calculate match price. */
uint256 price = calculateMatchPrice(buy, sell, amount);
/* If paying using a token (not Ether), transfer tokens. This is done prior to fee payments to that a seller will have tokens before being charged fees. */
if (price > 0 && sell.paymentToken != address(0)) {
transferTokens(sell.paymentToken, buy.maker, sell.maker, price);
}
/* Amount that will be received by seller (for Ether). */
uint256 receiveAmount = price;
/* Amount that must be sent by buyer (for Ether). */
uint256 requiredAmount = price;
/* Determine maker/taker and charge fees accordingly. */
if (sell.feeRecipient != address(0)) {
/* Sell-side order is maker. */
/* Assert taker fee is less than or equal to maximum fee specified by buyer. */
require(sell.takerRelayerFee <= buy.takerRelayerFee);
if (sell.feeMethod == FeeMethod.SplitFee) {
// /* Assert taker fee is less than or equal to maximum fee specified by buyer. */
// require(sell.takerProtocolFee <= buy.takerProtocolFee);
/* Maker fees are deducted from the token amount that the maker receives. Taker fees are extra tokens that must be paid by the taker. */
if (sell.makerRelayerFee > 0) {
uint256 makerRelayerFee = SafeMath.div(
SafeMath.mul(sell.makerRelayerFee, price),
INVERSE_BASIS_POINT
);
if (sell.paymentToken == address(0)) {
receiveAmount = SafeMath.sub(
receiveAmount,
makerRelayerFee
);
payable(sell.feeRecipient).transfer(makerRelayerFee);
} else {
transferTokens(
sell.paymentToken,
sell.maker,
sell.feeRecipient,
makerRelayerFee
);
}
}
if (sell.takerRelayerFee > 0) {
uint256 takerRelayerFee = SafeMath.div(
SafeMath.mul(sell.takerRelayerFee, price),
INVERSE_BASIS_POINT
);
if (sell.paymentToken == address(0)) {
requiredAmount = SafeMath.add(
requiredAmount,
takerRelayerFee
);
payable(sell.feeRecipient).transfer(takerRelayerFee);
} else {
transferTokens(
sell.paymentToken,
buy.maker,
sell.feeRecipient,
takerRelayerFee
);
}
}
// if (sell.makerProtocolFee > 0) {
// uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT);
// if (sell.paymentToken == address(0)) {
// receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee);
// protocolFeeRecipient.transfer(makerProtocolFee);
// } else {
// transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee);
// }
// }
// if (sell.takerProtocolFee > 0) {
// uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT);
// if (sell.paymentToken == address(0)) {
// requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee);
// protocolFeeRecipient.transfer(takerProtocolFee);
// } else {
// transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee);
// }
// }
} else {
/* Charge maker fee to seller. */
chargeProtocolFee(
sell.maker,
sell.feeRecipient,
sell.makerRelayerFee
);
/* Charge taker fee to buyer. */
chargeProtocolFee(
buy.maker,
sell.feeRecipient,
sell.takerRelayerFee
);
}
} else {
/* Buy-side order is maker. */
/* Assert taker fee is less than or equal to maximum fee specified by seller. */
require(buy.takerRelayerFee <= sell.takerRelayerFee);
if (sell.feeMethod == FeeMethod.SplitFee) {
/* The Exchange does not escrow Ether, so direct Ether can only be used to with sell-side maker / buy-side taker orders. */
require(sell.paymentToken != address(0));
// /* Assert taker fee is less than or equal to maximum fee specified by seller. */
// require(buy.takerProtocolFee <= sell.takerProtocolFee);
if (buy.makerRelayerFee > 0) {
uint256 makerRelayerFee = SafeMath.div(
SafeMath.mul(buy.makerRelayerFee, price),
INVERSE_BASIS_POINT
);
transferTokens(
sell.paymentToken,
buy.maker,
buy.feeRecipient,
makerRelayerFee
);
}
if (buy.takerRelayerFee > 0) {
uint256 takerRelayerFee = SafeMath.div(
SafeMath.mul(buy.takerRelayerFee, price),
INVERSE_BASIS_POINT
);
transferTokens(
sell.paymentToken,
sell.maker,
buy.feeRecipient,
takerRelayerFee
);
}
// if (buy.makerProtocolFee > 0) {
// makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT);
// transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee);
// }
// if (buy.takerProtocolFee > 0) {
// takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT);
// transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee);
// }
} else {
/* Charge maker fee to buyer. */
chargeProtocolFee(
buy.maker,
buy.feeRecipient,
buy.makerRelayerFee
);
/* Charge taker fee to seller. */
chargeProtocolFee(
sell.maker,
buy.feeRecipient,
buy.takerRelayerFee
);
}
}
if (royalty.account != address(0) && royalty.value > 0) {
uint256 royaltyAmount = SafeMath.div(
SafeMath.mul(royalty.value, price),
INVERSE_BASIS_POINT
);
receiveAmount = SafeMath.sub(receiveAmount, royaltyAmount);
if (sell.paymentToken == address(0)) {
royalty.account.transfer(royaltyAmount);
}
if (
sell.paymentToken != address(0) && sell.maker != royalty.account
) {
transferTokens(
sell.paymentToken,
sell.maker,
royalty.account,
royaltyAmount
);
}
}
if (sell.paymentToken == address(0)) {
/* Special-case Ether, order must be matched by buyer. */
require(msg.value >= requiredAmount);
payable(sell.maker).transfer(receiveAmount);
/* Allow overshoot for variable-price auctions, refund difference. */
uint256 diff = SafeMath.sub(msg.value, requiredAmount);
if (diff > 0) {
payable(buy.maker).transfer(diff);
}
}
/* This contract should never hold Ether, however, we cannot assert this, since it is impossible to prevent anyone from sending Ether e.g. with selfdestruct. */
return price;
}
/**
* @dev Return whether or not two orders can be matched with each other by basic parameters (does not check order signatures / calldata or perform static calls)
* @param buy Buy-side order
* @param sell Sell-side order
* @return Whether or not the two orders can be matched
*/
function ordersCanMatch(Order memory buy, Order memory sell)
internal
view
returns (bool)
{
return (/* Must be opposite-side. */
(buy.side == SaleKindInterface.Side.Buy &&
sell.side == SaleKindInterface.Side.Sell) &&
/* Must use same fee method. */
(buy.feeMethod == sell.feeMethod) &&
/* Must use same payment token. */
(buy.paymentToken == sell.paymentToken) &&
/* Must match maker/taker addresses. */
(sell.taker == address(0) || sell.taker == buy.maker) &&
(buy.taker == address(0) || buy.taker == sell.maker) &&
/* One must be maker and the other must be taker (no bool XOR in Solidity). */
((sell.feeRecipient == address(0) &&
buy.feeRecipient != address(0)) ||
(sell.feeRecipient != address(0) &&
buy.feeRecipient == address(0))) &&
/* Must match target. */
(buy.target == sell.target) &&
/* Must match howToCall. */
(buy.howToCall == sell.howToCall) &&
/* Buy-side order must be settleable. */
SaleKindInterface.canSettleOrder(
buy.listingTime,
buy.expirationTime
) &&
/* Sell-side order must be settleable. */
SaleKindInterface.canSettleOrder(
sell.listingTime,
sell.expirationTime
));
}
function _validatePartialSellingAmount(Order memory buy, Order memory sell)
internal
returns (bool, uint256)
{
uint256 buyAmount;
uint256 sellAmount;
uint256 tokenId;
bytes32 hash = hashToSign(sell);
SellRemaining storage sellAmountRemaining = sellOrderAmountRemaining[
hash
];
assembly {
let sellCallData := mload(add(sell, mul(0x20, 11)))
let buyCallData := mload(add(buy, mul(0x20, 11)))
tokenId := mload(add(sellCallData, add(mul(0x20, 2), 0x04)))
buyAmount := mload(add(buyCallData, add(mul(0x20, 4), 0x04)))
sellAmount := mload(add(sellCallData, add(mul(0x20, 4), 0x04)))
}
if (!sellAmountRemaining.tracking) {
sellAmountRemaining.tracking = true;
sellAmountRemaining.left = sellAmount;
}
require(
SafeMath.sub(sellAmountRemaining.left, buyAmount) >= 0,
"PaceArtExchange::ERC1155 remaining is not enough!"
);
sellAmountRemaining.left = SafeMath.sub(
sellAmountRemaining.left,
buyAmount
);
if (sellAmountRemaining.left == 0) {
delete sellOrderAmountRemaining[hash];
return (true, buyAmount);
}
return (false, buyAmount);
}
function makeStaticCall(Order memory order, bool callMint)
internal
returns (bytes memory)
{
if (callMint) {
(bool result, bytes memory returnData) = order.target.call(
order.callData
);
require(result, "Exchange::Failed when call other contract");
return returnData;
} else {
/* Retrieve delegateProxy contract. */
OwnableDelegateProxy delegateProxy = registry.proxies(order.maker);
/* Proxy must exist. */
require(
address(delegateProxy) != address(0),
"User not registed proxy yet!"
);
/* Assert implementation. */
require(
delegateProxy.implementation() ==
registry.delegateProxyImplementation()
);
/* Execute specified call through proxy. */
(bool result, bytes memory returnData) = AuthenticatedProxy(
address(delegateProxy)
).proxy(order.target, order.howToCall, order.callData);
require(result, "Exchange::Failed when call other contract");
return returnData;
}
}
/**
* @dev Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock.
* @param buy Buy-side order
* @param buySig Buy-side order signature
* @param sell Sell-side order
* @param sellSig Sell-side order signature
*/
function atomicMatch(
Order memory buy,
Sig memory buySig,
Order memory sell,
Sig memory sellSig,
bytes32 metadata
) internal nonReentrant {
/* CHECKS */
/* Ensure buy order validity and calculate hash if necessary. */
bytes32 buyHash;
if (buy.maker == msg.sender) {
require(validateOrderParameters(buy));
} else {
buyHash = requireValidOrder(buy, buySig);
}
/* Ensure sell order validity and calculate hash if necessary. */
bytes32 sellHash;
if (sell.maker == msg.sender) {
require(validateOrderParameters(sell));
} else {
sellHash = requireValidOrder(sell, sellSig);
}
/* Must be matchable. */
require(
ordersCanMatch(buy, sell),
"VindergoodExchange:: Order not matched"
);
/* Target must exist (prevent malicious selfdestructs just prior to order settlement). */
uint256 size;
address target = sell.target;
assembly {
size := extcodesize(target)
}
require(size > 0);
bytes4 signature;
bool soldOut = true;
uint256 amount = 1;
assembly {
let sellCallData := mload(add(sell, mul(0x20, 11)))
signature := mload(add(sellCallData, 0x20))
}
if (signature == ERC1155_SIGNATURE) {
(soldOut, amount) = _validatePartialSellingAmount(buy, sell);
}
/* Must match calldata after replacement, if specified. */
if (buy.replacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(
buy.callData,
sell.callData,
buy.replacementPattern
);
}
if (sell.replacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(
sell.callData,
buy.callData,
sell.replacementPattern
);
}
require(ArrayUtils.arrayEq(buy.callData, sell.callData));
/* Mark previously signed or approved orders as finalized. */
if (msg.sender != buy.maker) {
cancelledOrFinalized[buyHash] = true;
}
if (msg.sender != sell.maker && soldOut) {
cancelledOrFinalized[sellHash] = true;
}
bytes memory returnData = makeStaticCall(sell, signature == 0xda22caf8);
// Transfer Royalty Fee. Prevent stack too deep errors
uint256 tokenId = abi.decode(returnData, (uint256));
// /* Execute funds transfer and pay fees. */
uint256 price = executeFundsTransfer(
buy,
sell,
RoyaltiesV2(sell.target).getVindergoodV2Royalties(tokenId),
amount
);
// /* Log match event. */
emit OrdersMatched(
buyHash,
sellHash,
sell.maker,
buy.maker,
price,
metadata
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "../libraries/LibPart.sol";
interface IVindergoodStore {
function singleTransfer(
address _from,
address _to,
uint256 _tokenId
) external returns (uint256);
function mintTo(address _to, LibPart.Part memory _royalty)
external
returns (uint256);
function owner() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title ArrayUtils
* @author Wyvern Protocol Developers
*/
library ArrayUtils {
/**
* Replace bytes in an array with bytes in another array, guarded by a bitmask
* Efficiency of this function is a bit unpredictable because of the EVM's word-specific model (arrays under 32 bytes will be slower)
* Modifies the provided byte array parameter in place
*
* @dev Mask must be the size of the byte array. A nonzero byte means the byte array can be changed.
* @param array The original array
* @param desired The target array
* @param mask The mask specifying which bits can be changed
*/
function guardedArrayReplace(
bytes memory array,
bytes memory desired,
bytes memory mask
) internal pure {
require(
array.length == desired.length,
"Arrays have different lengths"
);
require(
array.length == mask.length,
"Array and mask have different lengths"
);
uint256 words = array.length / 0x20;
uint256 index = words * 0x20;
assert(index / 0x20 == words);
uint256 i;
for (i = 0; i < words; i++) {
/* Conceptually: array[i] = (!mask[i] && array[i]) || (mask[i] && desired[i]), bitwise in word chunks. */
assembly {
let commonIndex := mul(0x20, add(1, i))
let maskValue := mload(add(mask, commonIndex))
mstore(
add(array, commonIndex),
or(
and(not(maskValue), mload(add(array, commonIndex))),
and(maskValue, mload(add(desired, commonIndex)))
)
)
}
}
/* Deal with the last section of the byte array. */
if (words > 0) {
/* This overlaps with bytes already set but is still more efficient than iterating through each of the remaining bytes individually. */
i = words;
assembly {
let commonIndex := mul(0x20, add(1, i))
let maskValue := mload(add(mask, commonIndex))
mstore(
add(array, commonIndex),
or(
and(not(maskValue), mload(add(array, commonIndex))),
and(maskValue, mload(add(desired, commonIndex)))
)
)
}
} else {
/* If the byte array is shorter than a word, we must unfortunately do the whole thing bytewise.
(bounds checks could still probably be optimized away in assembly, but this is a rare case) */
for (i = index; i < array.length; i++) {
array[i] =
((mask[i] ^ 0xff) & array[i]) |
(mask[i] & desired[i]);
}
}
}
/**
* Test if two arrays are equal
* Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
*
* @dev Arrays must be of equal length, otherwise will return false
* @param a First array
* @param b Second array
* @return Whether or not all bytes in the arrays are equal
*/
function arrayEq(bytes memory a, bytes memory b)
internal
pure
returns (bool)
{
bool success = true;
assembly {
let length := mload(a)
// if lengths don't match the arrays are not equal
switch eq(length, mload(b))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(a, 0x20)
let end := add(mc, length)
for {
let cc := add(b, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
/**
* Drop the beginning of an array
*
* @param _bytes array
* @param _start start index
* @return Whether or not all bytes in the arrays are equal
*/
function arrayDrop(bytes memory _bytes, uint256 _start)
internal
pure
returns (bytes memory)
{
uint256 _length = SafeMath.sub(_bytes.length, _start);
return arraySlice(_bytes, _start, _length);
}
/**
* Take from the beginning of an array
*
* @param _bytes array
* @param _length elements to take
* @return Whether or not all bytes in the arrays are equal
*/
function arrayTake(bytes memory _bytes, uint256 _length)
internal
pure
returns (bytes memory)
{
return arraySlice(_bytes, 0, _length);
}
/**
* Slice an array
* Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
*
* @param _bytes array
* @param _start start index
* @param _length length to take
* @return Whether or not all bytes in the arrays are equal
*/
function arraySlice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(
add(tempBytes, lengthmod),
mul(0x20, iszero(lengthmod))
)
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(
add(
add(_bytes, lengthmod),
mul(0x20, iszero(lengthmod))
),
_start
)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
/**
* Unsafe write byte array into a memory location
*
* @param index Memory location
* @param source Byte array to write
* @return End memory index
*/
function unsafeWriteBytes(uint256 index, bytes memory source)
internal
pure
returns (uint256)
{
if (source.length > 0) {
assembly {
let length := mload(source)
let end := add(source, add(0x20, length))
let arrIndex := add(source, 0x20)
let tempIndex := index
for {
} eq(lt(arrIndex, end), 1) {
arrIndex := add(arrIndex, 0x20)
tempIndex := add(tempIndex, 0x20)
} {
mstore(tempIndex, mload(arrIndex))
}
index := add(index, length)
}
}
return index;
}
/**
* Unsafe write address into a memory location
*
* @param index Memory location
* @param source Address to write
* @return End memory index
*/
function unsafeWriteAddress(uint256 index, address source)
internal
pure
returns (uint256)
{
uint256 conv = uint256(source) << 0x60;
assembly {
mstore(index, conv)
index := add(index, 0x14)
}
return index;
}
/**
* Unsafe write uint into a memory location
*
* @param index Memory location
* @param source uint to write
* @return End memory index
*/
function unsafeWriteUint(uint256 index, uint256 source)
internal
pure
returns (uint256)
{
assembly {
mstore(index, source)
index := add(index, 0x20)
}
return index;
}
/**
* Unsafe write uint8 into a memory location
*
* @param index Memory location
* @param source uint8 to write
* @return End memory index
*/
function unsafeWriteUint8(uint256 index, uint8 source)
internal
pure
returns (uint256)
{
assembly {
mstore8(index, source)
index := add(index, 0x1)
}
return index;
}
}
// SPDX-License-Identifier: MIT pragma
pragma solidity 0.7.5;
library LibPart {
bytes32 public constant TYPE_HASH =
keccak256("Part(address account,uint96 value)");
struct Part {
address payable account;
uint96 value;
}
function hash(Part memory part) internal pure returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, part.account, part.value));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
library SaleKindInterface {
/**
* Side: buy or sell.
*/
enum Side {
Buy,
Sell
}
/**
* Currently supported kinds of sale: fixed price, Dutch auction.
* English auctions cannot be supported without stronger escrow guarantees.
* Future interesting options: Vickrey auction, nonlinear Dutch auctions.
*/
enum SaleKind {
FixedPrice,
DutchAuction
}
/**
* @dev Check whether the parameters of a sale are valid
* @param saleKind Kind of sale
* @param expirationTime Order expiration time
* @return Whether the parameters were valid
*/
function validateParameters(SaleKind saleKind, uint256 expirationTime)
internal
pure
returns (bool)
{
/* Auctions must have a set expiration date. */
return (saleKind == SaleKind.FixedPrice || expirationTime > 0);
}
/**
* @dev Return whether or not an order can be settled
* @dev Precondition: parameters have passed validateParameters
* @param listingTime Order listing time
* @param expirationTime Order expiration time
*/
function canSettleOrder(uint256 listingTime, uint256 expirationTime)
internal
view
returns (bool)
{
return
(listingTime < block.timestamp) &&
(expirationTime == 0 || block.timestamp < expirationTime);
}
/**
* @dev Calculate the settlement price of an order
* @dev Precondition: parameters have passed validateParameters.
* @param side Order side
* @param saleKind Method of sale
* @param basePrice Order base price
* @param extra Order extra price data
* @param listingTime Order listing time
* @param expirationTime Order expiration time
*/
function calculateFinalPrice(
Side side,
SaleKind saleKind,
uint256 basePrice,
uint256 extra,
uint256 listingTime,
uint256 expirationTime,
uint256 amount
) internal view returns (uint256 finalPrice) {
if (saleKind == SaleKind.FixedPrice) {
return SafeMath.mul(basePrice, amount);
} else if (saleKind == SaleKind.DutchAuction) {
uint256 diff = SafeMath.div(
SafeMath.mul(extra, SafeMath.sub(block.timestamp, listingTime)),
SafeMath.sub(expirationTime, listingTime)
);
if (side == Side.Sell) {
/* Sell-side - start price: basePrice. End price: basePrice - extra. */
return SafeMath.sub(SafeMath.mul(basePrice, amount), diff);
} else {
/* Buy-side - start price: basePrice. End price: basePrice + extra. */
return SafeMath.add(SafeMath.mul(basePrice, amount), diff);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(0x095ea7b3, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper::safeApprove: approve failed"
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(0xa9059cbb, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper::safeTransfer: transfer failed"
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(0x23b872dd, from, to, value)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper::transferFrom: transferFrom failed"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./ERC20Basic.sol";
interface ERC20 is ERC20Basic {
function allowance(address owner, address spender)
external
view
returns (uint256);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
interface ERC20Basic {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "../registry/ProxyRegistry.sol";
import "../libraries/TransferHelper.sol";
import "./ERC20.sol";
contract VindergoodTransferProxy {
/* Authentication registry. */
ProxyRegistry public registry;
constructor(ProxyRegistry _registry) {
require(address(_registry) != address(0), "INVALID REGISTRY");
registry = _registry;
}
/**
* Call ERC20 `transferFrom`
*
* @dev Authenticated contract only
* @param token ERC20 token address
* @param from From address
* @param to To address
* @param amount Transfer amount
*/
function transferFrom(
address token,
address from,
address to,
uint256 amount
) public {
require(registry.contracts(msg.sender));
TransferHelper.safeTransferFrom(token, from, to, amount);
}
}
/*
Proxy contract to hold access to assets on behalf of a user (e.g. ERC20 approve) and execute calls under particular conditions.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./ProxyRegistry.sol";
import "./TokenRecipient.sol";
import "./proxy/OwnedUpgradeabilityStorage.sol";
/**
* @title AuthenticatedProxy
* @author Wyvern Protocol Developers
*/
contract AuthenticatedProxy is TokenRecipient, OwnedUpgradeabilityStorage {
/* Whether initialized. */
bool initialized = false;
/* Address which owns this proxy. */
address public user;
/* Associated registry with contract authentication information. */
ProxyRegistry public registry;
/* Whether access has been revoked. */
bool public revoked;
/* Delegate call could be used to atomically transfer multiple assets owned by the proxy contract with one order. */
enum HowToCall {
Call,
DelegateCall
}
/* Event fired when the proxy access is revoked or unrevoked. */
event Revoked(bool revoked);
/**
* Initialize an AuthenticatedProxy
*
* @param addrUser Address of user on whose behalf this proxy will act
* @param addrRegistry Address of ProxyRegistry contract which will manage this proxy
*/
function initialize(address addrUser, ProxyRegistry addrRegistry) public {
require(!initialized, "Authenticated proxy already initialized");
initialized = true;
user = addrUser;
registry = addrRegistry;
}
/**
* Set the revoked flag (allows a user to revoke ProxyRegistry access)
*
* @dev Can be called by the user only
* @param revoke Whether or not to revoke access
*/
function setRevoke(bool revoke) public {
require(
msg.sender == user,
"Authenticated proxy can only be revoked by its user"
);
revoked = revoke;
emit Revoked(revoke);
}
/**
* Execute a message call from the proxy contract
*
* @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access
* @param dest Address to which the call will be sent
* @param howToCall Which kind of call to make
* @param data Calldata to send
* @return result Result of the call (success or failure)
*/
function proxy(
address dest,
HowToCall howToCall,
bytes memory data
) public returns (bool result, bytes memory ret) {
require(
msg.sender == user || (!revoked && registry.contracts(msg.sender)),
"Authenticated proxy can only be called by its user, or by a contract authorized by the registry as long as the user has not revoked access"
);
if (howToCall == HowToCall.Call) {
(result, ret) = dest.call(data);
} else if (howToCall == HowToCall.DelegateCall) {
(result, ret) = dest.delegatecall(data);
}
}
/**
* Execute a message call and assert success
*
* @dev Same functionality as `proxy`, just asserts the return value
* @param dest Address to which the call will be sent
* @param howToCall What kind of call to make
* @param data Calldata to send
*/
function proxyAssert(
address dest,
HowToCall howToCall,
bytes memory data
) public {
(bool result, ) = proxy(dest, howToCall, data);
require(result, "Proxy assertion failed");
}
}
/*
OwnableDelegateProxy
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./proxy/OwnedUpgradeabilityProxy.sol";
/**
* @title OwnableDelegateProxy
* @author Wyvern Protocol Developers
*/
contract OwnableDelegateProxy is OwnedUpgradeabilityProxy {
constructor(
address owner,
address initialImplementation,
bytes memory data
) public {
require(owner != address(0), "owner: zero address");
require(
initialImplementation != address(0),
"initialImplementation: zero address"
);
setUpgradeabilityOwner(owner);
_upgradeTo(initialImplementation);
(bool success, ) = initialImplementation.delegatecall(data);
require(success, "OwnableDelegateProxy failed implementation");
}
}
/*
Proxy registry; keeps a mapping of AuthenticatedProxy contracts and mapping of contracts authorized to access them.
Abstracted away from the Exchange (a) to reduce Exchange attack surface and (b) so that the Exchange contract can be upgraded without users needing to transfer assets to new proxies.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./OwnableDelegateProxy.sol";
import "./ProxyRegistryInterface.sol";
/**
* @title ProxyRegistry
* @author Wyvern Protocol Developers
*/
contract ProxyRegistry is OwnableUpgradeable, ProxyRegistryInterface {
/* DelegateProxy implementation contract. Must be initialized. */
address public override delegateProxyImplementation;
/* Authenticated proxies by user. */
mapping(address => OwnableDelegateProxy) public override proxies;
/* Contracts pending access. */
mapping(address => uint256) public pending;
/* Contracts allowed to call those proxies. */
mapping(address => bool) public contracts;
/* Delay period for adding an authenticated contract.
This mitigates a particular class of potential attack on the Wyvern DAO (which owns this registry) - if at any point the value of assets held by proxy contracts exceeded the value of half the WYV supply (votes in the DAO),
a malicious but rational attacker could buy half the Wyvern and grant themselves access to all the proxy contracts. A delay period renders this attack nonthreatening - given two weeks, if that happened, users would have
plenty of time to notice and transfer their assets.
*/
uint256 public DELAY_PERIOD = 2 weeks;
/**
* Start the process to enable access for specified contract. Subject to delay period.
*
* @dev ProxyRegistry owner only
* @param addr Address to which to grant permissions
*/
function startGrantAuthentication(address addr) public onlyOwner {
require(
!contracts[addr] && pending[addr] == 0,
"Contract is already allowed in registry, or pending"
);
pending[addr] = block.timestamp;
}
/**
* End the process to enable access for specified contract after delay period has passed.
*
* @dev ProxyRegistry owner only
* @param addr Address to which to grant permissions
*/
function endGrantAuthentication(address addr) public onlyOwner {
require(
!contracts[addr] &&
pending[addr] != 0 &&
((pending[addr] + DELAY_PERIOD) < block.timestamp),
"Contract is no longer pending or has already been approved by registry"
);
pending[addr] = 0;
contracts[addr] = true;
}
/**
* Revoke access for specified contract. Can be done instantly.
*
* @dev ProxyRegistry owner only
* @param addr Address of which to revoke permissions
*/
function revokeAuthentication(address addr) public onlyOwner {
contracts[addr] = false;
}
/**
* Register a proxy contract with this registry
*
* @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy
* @return proxy New AuthenticatedProxy contract
*/
function registerProxy() public returns (OwnableDelegateProxy proxy) {
return registerProxyFor(msg.sender);
}
/**
* Register a proxy contract with this registry, overriding any existing proxy
*
* @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy
* @return proxy New AuthenticatedProxy contract
*/
function registerProxyOverride()
public
returns (OwnableDelegateProxy proxy)
{
proxy = new OwnableDelegateProxy(
msg.sender,
delegateProxyImplementation,
abi.encodeWithSignature(
"initialize(address,address)",
msg.sender,
address(this)
)
);
proxies[msg.sender] = proxy;
return proxy;
}
/**
* Register a proxy contract with this registry
*
* @dev Can be called by any user
* @return proxy New AuthenticatedProxy contract
*/
function registerProxyFor(address user)
public
returns (OwnableDelegateProxy proxy)
{
require(
proxies[user] == OwnableDelegateProxy(0),
"User already has a proxy"
);
proxy = new OwnableDelegateProxy(
user,
delegateProxyImplementation,
abi.encodeWithSignature(
"initialize(address,address)",
user,
address(this)
)
);
proxies[user] = proxy;
return proxy;
}
/**
* Transfer access
*/
function transferAccessTo(address from, address to) public {
OwnableDelegateProxy proxy = proxies[from];
/* CHECKS */
require(
OwnableDelegateProxy(msg.sender) == proxy,
"Proxy transfer can only be called by the proxy"
);
require(
proxies[to] == OwnableDelegateProxy(0),
"Proxy transfer has existing proxy as destination"
);
/* EFFECTS */
delete proxies[from];
proxies[to] = proxy;
}
}
/*
Proxy registry interface.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./OwnableDelegateProxy.sol";
/**
* @title ProxyRegistryInterface
* @author Wyvern Protocol Developers
*/
interface ProxyRegistryInterface {
function delegateProxyImplementation() external returns (address);
function proxies(address owner) external returns (OwnableDelegateProxy);
}
/*
Token recipient. Modified very slightly from the example on http://ethereum.org/dao (just to index log parameters).
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "../modules/ERC20.sol";
/**
* @title TokenRecipient
* @author Wyvern Protocol Developers
*/
contract TokenRecipient {
event ReceivedEther(address indexed sender, uint256 amount);
event ReceivedTokens(
address indexed from,
uint256 value,
address indexed token,
bytes extraData
);
/**
* @dev Receive tokens and generate a log event
* @param from Address from which to transfer tokens
* @param value Amount of tokens to transfer
* @param token Address of token
* @param extraData Additional data to log
*/
function receiveApproval(
address from,
uint256 value,
address token,
bytes memory extraData
) public {
ERC20 t = ERC20(token);
require(
t.transferFrom(from, address(this), value),
"ERC20 token transfer failed"
);
emit ReceivedTokens(from, value, token, extraData);
}
/**
* @dev Receive Ether and generate a log event
*/
fallback() external payable {
emit ReceivedEther(msg.sender, msg.value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./Proxy.sol";
import "./OwnedUpgradeabilityStorage.sol";
/**
* @title OwnedUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
*/
contract OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(address indexed implementation);
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view override returns (address) {
return _implementation;
}
/**
* @dev Tells the proxy type (EIP 897)
* @return proxyTypeId Proxy type, 2 for forwarding proxy
*/
function proxyType() public pure override returns (uint256 proxyTypeId) {
return 2;
}
/**
* @dev Upgrades the implementation address
* @param implementation_ representing the address of the new implementation to be set
*/
function _upgradeTo(address implementation_) internal {
require(
_implementation != implementation_,
"Proxy already uses this implementation"
);
_implementation = implementation_;
emit Upgraded(implementation_);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(
msg.sender == proxyOwner(),
"Only the proxy owner can call this method"
);
_;
}
/**
* @dev Tells the address of the proxy owner
* @return the address of the proxy owner
*/
function proxyOwner() public view returns (address) {
return upgradeabilityOwner();
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address newOwner) public onlyProxyOwner {
require(newOwner != address(0), "New owner cannot be the null address");
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy.
* @param implementation_ representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation_) public onlyProxyOwner {
_upgradeTo(implementation_);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy
* and delegatecall the new implementation for initialization.
* @param implementation_ representing the address of the new implementation to be set.
* @param data represents the msg.data to bet sent in the low level call. This parameter may include the function
* signature of the implementation to be called with the needed payload
*/
function upgradeToAndCall(address implementation_, bytes memory data)
public
payable
onlyProxyOwner
{
upgradeTo(implementation_);
(bool success, ) = address(this).delegatecall(data);
require(success, "Call failed after proxy upgrade");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @title OwnedUpgradeabilityStorage
* @dev This contract keeps track of the upgradeability owner
*/
contract OwnedUpgradeabilityStorage {
// Current implementation
address internal _implementation;
// Owner of the contract
address private _upgradeabilityOwner;
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function upgradeabilityOwner() public view returns (address) {
return _upgradeabilityOwner;
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
_upgradeabilityOwner = newUpgradeabilityOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
abstract contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public view virtual returns (address);
/**
* @dev Tells the type of proxy (EIP 897)
* @return proxyTypeId Type of proxy, 2 for upgradeable proxy
*/
function proxyType() public pure virtual returns (uint256 proxyTypeId);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
fallback() external payable {
address _impl = implementation();
require(_impl != address(0), "Proxy implementation required");
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 {
revert(ptr, size)
}
default {
return(ptr, size)
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "../libraries/LibPart.sol";
interface RoyaltiesV2 {
event RoyaltiesSet(uint256 tokenId, LibPart.Part royalties);
function getVindergoodV2Royalties(uint256 id)
external
view
returns (LibPart.Part memory);
} | * @dev Initialize a VindergoodExchange instance @param registryAddress Address of the registry instance which this Exchange instance will use @param tokenAddress Address of the token used for protocol fees/ | ) public initializer {
registry = registryAddress;
tokenTransferProxy = tokenTransferProxyAddress;
exchangeToken = tokenAddress;
}
| 14,408,208 | [
1,
7520,
279,
776,
14055,
19747,
11688,
791,
225,
4023,
1887,
5267,
434,
326,
4023,
791,
1492,
333,
18903,
791,
903,
999,
225,
1147,
1887,
5267,
434,
326,
1147,
1399,
364,
1771,
1656,
281,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
262,
1071,
12562,
288,
203,
3639,
4023,
273,
4023,
1887,
31,
203,
3639,
1147,
5912,
3886,
273,
1147,
5912,
3886,
1887,
31,
203,
3639,
7829,
1345,
273,
1147,
1887,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/295/0x0000000000000000000000000000000000233233/sources/IHederaTokenService.sol | The ID of the token as a solidity address Applicable to tokens of type FUNGIBLE_COMMON. Multiple list of AccountAmounts, each of which has an account and amount. Applicable to tokens of type NON_FUNGIBLE_UNIQUE. Multiple list of NftTransfers, each of which has a sender and receiver account, including the serial number of the NFT | struct TokenTransferList {
address token;
AccountAmount[] transfers;
NftTransfer[] nftTransfers;
}
| 4,664,435 | [
1,
1986,
1599,
434,
326,
1147,
487,
279,
18035,
560,
1758,
1716,
10120,
358,
2430,
434,
618,
478,
2124,
43,
13450,
900,
67,
4208,
17667,
18,
13531,
666,
434,
6590,
6275,
87,
16,
1517,
434,
1492,
711,
392,
2236,
471,
3844,
18,
1716,
10120,
358,
2430,
434,
618,
18708,
67,
42,
2124,
43,
13450,
900,
67,
16879,
18,
13531,
666,
434,
423,
1222,
1429,
18881,
16,
1517,
434,
1492,
711,
279,
5793,
471,
5971,
2236,
16,
6508,
326,
2734,
1300,
434,
326,
423,
4464,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
3155,
5912,
682,
288,
203,
3639,
1758,
1147,
31,
203,
203,
3639,
6590,
6275,
8526,
29375,
31,
203,
203,
3639,
423,
1222,
5912,
8526,
290,
1222,
1429,
18881,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-06-16
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.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);
}
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library SafeERC20 {
function _safeApprove(IERC20 token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), '!APPROVE_FAILED');
}
function safeApprove(IERC20 token, address to, uint value) internal {
if (value > 0) _safeApprove(token, to, 0);
return _safeApprove(token, to, value);
}
function safeTransfer(IERC20 token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), '!TRANSFER_FAILED');
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), '!TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, '!ETH_TRANSFER_FAILED');
}
}
pragma solidity >=0.6.0 <0.9.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;
}
}
/**
*Submitted for verification at Etherscan.io on 2021-01-14
*/
pragma solidity >=0.6.0 <0.9.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
pragma solidity >=0.6.0 <0.9.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
pragma solidity >=0.6.0 <0.9.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 Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
pragma solidity ^0.8.0;
interface IWETHelper {
function withdraw(uint) external;
}
contract WETHelper {
receive() external payable {
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, '!WETHelper: ETH_TRANSFER_FAILED');
}
function withdraw(address _eth, address _to, uint256 _amount) public {
IWETHelper(_eth).withdraw(_amount);
safeTransferETH(_to, _amount);
}
}
pragma solidity ^0.8.0;
interface IMigratorChef {
// Perform LP token migration from legacy UniswapV2 to SushiSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 boostAmount;// How many LP tokens with multilex the user has provided.
uint256 untilLock; // Until Lock timestamp.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 amount; // User deposit amount
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// ETH Ropsten
//address public constant WETH = 0xc778417E063141139Fce010982780140Aa0cD5Ab;
// ETH Mainnet
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// BSC Testnet
//address public constant WETH = 0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd;
// BSC Mainnet
//address public constant WETH = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c;
// The SUSHI TOKEN!
IERC20 public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 4;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
// ETH Helper for the transfer, stateless.
WETHelper public wethelper;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
function initialize(
IERC20 _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public initializer {
Ownable.__Ownable_init();
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
startBlock = _startBlock;
bonusEndBlock = _bonusEndBlock;
wethelper = new WETHelper();
}
receive() external payable {
assert(msg.sender == WETH);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public {
require(msg.sender == owner() || msg.sender == devaddr, "!dev addr");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
amount: 0,
lastRewardBlock: lastRewardBlock,
accSushiPerShare: 0
}));
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public {
require(msg.sender == owner() || msg.sender == devaddr, "!dev addr");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.amount;
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
uint256 pending = user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
if (user.amount > 0) return pending.mul(user.boostAmount).div(user.amount);
return 0;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.amount;
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function formatDuration(uint256 sec_) public pure returns (uint256) {
if (sec_ == 0) return 0;
else if (sec_ <= 1 days) return 1 days;
else if (sec_ <= 7 days) return 7 days;
else if (sec_ <= 14 days) return 14 days;
else return 14 days;
}
function getTimeMultiplex(uint256 sec_) public pure returns (uint256) {
if (sec_ == 0) return 100;
else if (sec_ <= 1 days) return 120;
else if (sec_ <= 7 days) return 200;
else if (sec_ <= 14 days) return 400;
else return 400;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount, uint256 _durationSec) public payable {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
pending = pending.mul(user.boostAmount).div(user.amount);
safeSushiTransfer(msg.sender, pending);
}
}
if (msg.value > 0) {
IWETH(WETH).deposit{value: msg.value}();
}
if (address(pool.lpToken) == WETH) {
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
if (msg.value > 0) {
_amount = _amount.add(msg.value);
}
} else if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
if(_amount > 0) {
uint256 lockUntil;
uint256 duration;
if (user.untilLock < block.timestamp) lockUntil = block.timestamp;
else lockUntil = user.untilLock;
_durationSec = formatDuration(_durationSec);
duration = ((lockUntil - block.timestamp) * user.amount + _durationSec * _amount) / (user.amount + _amount);
user.untilLock = block.timestamp + duration;
user.boostAmount = user.boostAmount.add(_amount * getTimeMultiplex(_durationSec) / 100);
pool.amount = pool.amount.add(_amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public payable {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
require(block.timestamp >= user.untilLock, "withdraw: not locktime");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
pending = pending.mul(user.boostAmount).div(user.amount);
safeSushiTransfer(msg.sender, pending);
}
if(_amount > 0) {
uint256 boostAmount = user.boostAmount.mul(_amount).div(user.amount);
user.amount = user.amount.sub(_amount);
user.boostAmount = user.boostAmount.sub(boostAmount);
pool.amount = pool.amount.sub(_amount);
if (address(pool.lpToken) == WETH) {
withdrawEth(address(msg.sender), _amount, false);
} else {
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
}
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function withdrawEth(address _to, uint256 _amount, bool _isWeth) internal {
if (_isWeth) {
IERC20(WETH).safeTransfer(_to, _amount);
} else {
IERC20(WETH).safeTransfer(address(wethelper), _amount);
wethelper.withdraw(WETH, _to, _amount);
}
}
} | helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false | library SafeERC20 {
}
function _safeApprove(IERC20 token, address to, uint value) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), '!APPROVE_FAILED');
}
function safeApprove(IERC20 token, address to, uint value) internal {
if (value > 0) _safeApprove(token, to, 0);
return _safeApprove(token, to, value);
}
function safeTransfer(IERC20 token, address to, uint value) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), '!TRANSFER_FAILED');
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), '!TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
require(success, '!ETH_TRANSFER_FAILED');
}
(bool success,) = to.call{value:value}(new bytes(0));
}
| 15,109,393 | [
1,
4759,
2590,
364,
16592,
310,
598,
4232,
39,
3462,
2430,
471,
5431,
512,
2455,
716,
741,
486,
11071,
715,
327,
638,
19,
5743,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12083,
14060,
654,
39,
3462,
288,
203,
97,
203,
565,
445,
389,
4626,
12053,
537,
12,
45,
654,
39,
3462,
1147,
16,
1758,
358,
16,
2254,
460,
13,
2713,
288,
203,
3639,
261,
6430,
2216,
16,
1731,
3778,
501,
13,
273,
1758,
12,
2316,
2934,
1991,
12,
21457,
18,
3015,
1190,
4320,
12,
20,
92,
5908,
25,
24852,
27,
70,
23,
16,
358,
16,
460,
10019,
203,
3639,
2583,
12,
4768,
597,
261,
892,
18,
2469,
422,
374,
747,
24126,
18,
3922,
12,
892,
16,
261,
6430,
3719,
3631,
11817,
2203,
3373,
3412,
67,
11965,
8284,
203,
565,
289,
203,
565,
445,
4183,
12053,
537,
12,
45,
654,
39,
3462,
1147,
16,
1758,
358,
16,
2254,
460,
13,
2713,
288,
203,
3639,
309,
261,
1132,
405,
374,
13,
389,
4626,
12053,
537,
12,
2316,
16,
358,
16,
374,
1769,
203,
3639,
327,
389,
4626,
12053,
537,
12,
2316,
16,
358,
16,
460,
1769,
203,
565,
289,
203,
203,
565,
445,
4183,
5912,
12,
45,
654,
39,
3462,
1147,
16,
1758,
358,
16,
2254,
460,
13,
2713,
288,
203,
3639,
261,
6430,
2216,
16,
1731,
3778,
501,
13,
273,
1758,
12,
2316,
2934,
1991,
12,
21457,
18,
3015,
1190,
4320,
12,
20,
6995,
9349,
6162,
7358,
70,
16,
358,
16,
460,
10019,
203,
3639,
2583,
12,
4768,
597,
261,
892,
18,
2469,
422,
374,
747,
24126,
18,
3922,
12,
892,
16,
261,
6430,
3719,
3631,
11817,
16596,
6553,
67,
11965,
8284,
203,
565,
289,
203,
203,
565,
445,
4183,
5912,
1265,
12,
45,
654,
39,
2
] |
./partial_match/6119/0x0CBDcecC301f55196950b990dDC5DE948C7CA23D/sources/contracts/temp/Multicall2.sol | @notice Aggregate calls with a msg value @notice Reverts if msg.value is less than the sum of the call values @param calls An array of Call3Value structs @return returnData An array of Result structs Humanity will be a Type V Kardashev Civilization before this overflows - andreas ~ 10^25 Wei in existence << ~ 10^76 size uint fits in a uint256 Revert if the call fails and failure is not allowed `allowFailure := calldataload(add(calli, 0x20))` and `success := mload(result)` set "Error(string)" signature: bytes32(bytes4(keccak256("Error(string)"))) set data offset set length of revert string set revert string: bytes32(abi.encodePacked("Multicall3: call failed")) | function aggregate3Value(Call3Value[] calldata calls) public payable returns (Result[] memory returnData) {
uint256 valAccumulator;
uint256 length = calls.length;
returnData = new Result[](length);
Call3Value calldata calli;
for (uint256 i = 0; i < length;) {
Result memory result = returnData[i];
calli = calls[i];
uint256 val = calli.value;
assembly {
if iszero(or(calldataload(add(calli, 0x20)), mload(result))) {
mstore(0x00, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
mstore(0x24, 0x0000000000000000000000000000000000000000000000000000000000000017)
mstore(0x44, 0x4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000)
revert(0x00, 0x84)
}
}
}
}
| 3,492,624 | [
1,
11490,
4097,
598,
279,
1234,
460,
225,
868,
31537,
309,
1234,
18,
1132,
353,
5242,
2353,
326,
2142,
434,
326,
745,
924,
225,
4097,
1922,
526,
434,
3049,
23,
620,
8179,
327,
327,
751,
1922,
526,
434,
3438,
8179,
670,
6925,
560,
903,
506,
279,
1412,
776,
1475,
1060,
345,
580,
90,
385,
427,
330,
1588,
1865,
333,
9391,
87,
300,
471,
266,
345,
4871,
1728,
66,
2947,
1660,
77,
316,
15782,
2296,
4871,
1728,
66,
6669,
963,
2254,
13351,
316,
279,
2254,
5034,
868,
1097,
309,
326,
745,
6684,
471,
5166,
353,
486,
2935,
1375,
5965,
5247,
519,
745,
72,
3145,
6189,
12,
1289,
12,
1991,
77,
16,
374,
92,
3462,
3719,
68,
471,
1375,
4768,
519,
312,
945,
12,
2088,
22025,
444,
315,
668,
12,
1080,
2225,
3372,
30,
1731,
1578,
12,
3890,
24,
12,
79,
24410,
581,
5034,
2932,
668,
12,
1080,
2225,
20349,
444,
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,
7047,
23,
620,
12,
1477,
23,
620,
8526,
745,
892,
4097,
13,
1071,
8843,
429,
1135,
261,
1253,
8526,
3778,
327,
751,
13,
288,
203,
3639,
2254,
5034,
1244,
27361,
31,
203,
3639,
2254,
5034,
769,
273,
4097,
18,
2469,
31,
203,
3639,
327,
751,
273,
394,
3438,
8526,
12,
2469,
1769,
203,
3639,
3049,
23,
620,
745,
892,
745,
77,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
769,
30943,
288,
203,
5411,
3438,
3778,
563,
273,
327,
751,
63,
77,
15533,
203,
5411,
745,
77,
273,
4097,
63,
77,
15533,
203,
5411,
2254,
5034,
1244,
273,
745,
77,
18,
1132,
31,
203,
5411,
19931,
288,
203,
7734,
309,
353,
7124,
12,
280,
12,
1991,
72,
3145,
6189,
12,
1289,
12,
1991,
77,
16,
374,
92,
3462,
13,
3631,
312,
945,
12,
2088,
20349,
288,
203,
10792,
312,
2233,
12,
20,
92,
713,
16,
374,
92,
6840,
71,
6418,
29,
69,
12648,
12648,
12648,
12648,
12648,
12648,
2787,
11706,
13,
203,
10792,
312,
2233,
12,
20,
92,
3028,
16,
374,
92,
12648,
12648,
12648,
12648,
12648,
12648,
12648,
9449,
3462,
13,
203,
10792,
312,
2233,
12,
20,
92,
3247,
16,
374,
92,
12648,
12648,
12648,
12648,
12648,
12648,
12648,
9449,
4033,
13,
203,
10792,
312,
2233,
12,
20,
92,
6334,
16,
374,
92,
24,
72,
27,
4313,
71,
5608,
8148,
4449,
26,
2313,
71,
26,
71,
3707,
23,
69,
3462,
4449,
26,
2313,
71,
26,
71,
3462,
25308,
2313,
10525,
71,
9222,
1105,
12648,
2787,
9449,
2
] |
./full_match/1/0xfB47e53a5784540c2653241C903E4D8e99551D57/sources/contracts/PP2LockLp.sol | in case everything goes well with launch, team can burn LP forever voiding the lock | function burn() external onlyDepositor {
lpToken.transfer(address(0xdead), lpToken.balanceOf(address(this)));
}
| 9,638,985 | [
1,
267,
648,
7756,
13998,
5492,
598,
8037,
16,
5927,
848,
18305,
511,
52,
21238,
918,
310,
326,
2176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
18305,
1435,
3903,
1338,
758,
1724,
280,
288,
203,
3639,
12423,
1345,
18,
13866,
12,
2867,
12,
20,
92,
22097,
3631,
12423,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
pragma experimental ABIEncoderV2;
// Interfaces.
import '../interfaces/IERC20.sol';
import '../interfaces/IAssetHandler.sol';
import '../interfaces/IAddressResolver.sol';
import '../interfaces/Mobius/ISwap.sol';
import '../interfaces/Mobius/IMasterMind.sol';
import '../interfaces/IUbeswapAdapter.sol';
// Inheritance.
import '../interfaces/IMoolaAdapter.sol';
// OpenZeppelin.
import '../openzeppelin-solidity/contracts/SafeMath.sol';
import '../openzeppelin-solidity/contracts/Ownable.sol';
contract MoolaAdapter is IMoolaAdapter, Ownable {
using SafeMath for uint;
struct MoolaAsset {
address lendingPool;
address underlyingAsset;
}
IAddressResolver public immutable ADDRESS_RESOLVER;
// (interest-bearing token address => token info).
mapping (address => MoolaAsset) public moolaAssets;
// (underlying asset => asset's interest-bearing token on Moola).
mapping (address => address) public equivalentMoolaAsset;
// (lending pool address => interest-bearing token address).
mapping (address => address) public lendingPools;
constructor(address _addressResolver) Ownable() {
ADDRESS_RESOLVER = IAddressResolver(_addressResolver);
}
/* ========== VIEWS ========== */
/**
* @notice Given an input asset address, returns the price of the asset in USD.
* @dev Returns 0 if the asset is not supported.
* @param _currencyKey Address of the asset.
* @return price Price of the asset.
*/
function getPrice(address _currencyKey) external view override returns (uint price) {
require(_currencyKey != address(0), "MoolaAdapter: Invalid currency key.");
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
address ubeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("UbeswapAdapter");
require(IAssetHandler(assetHandlerAddress).isValidAsset(_currencyKey), "MoolaAdapter: Currency is not available.");
if (moolaAssets[_currencyKey].lendingPool != address(0)) {
price = IUbeswapAdapter(ubeswapAdapterAddress).getPrice(_currencyKey);
}
else if (equivalentMoolaAsset[_currencyKey] != address(0)) {
price = IUbeswapAdapter(ubeswapAdapterAddress).getPrice(equivalentMoolaAsset[_currencyKey]);
}
price = 0;
}
/**
* @notice Returns the address of each lending pool available on Moola.
* @return address[] The address of each lending pool on Moola.
*/
function getAvailableMoolaLendingPools() external view override returns (address[] memory) {
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
address[] memory interestBearingTokenAddresses = IAssetHandler(assetHandlerAddress).getAvailableAssetsForType(5);
address[] memory lendingPoolAddresses = new address[](interestBearingTokenAddresses.length);
//Get farm IDs
for (uint i = 0; i < lendingPoolAddresses.length; i++)
{
lendingPoolAddresses[i] = moolaAssets[interestBearingTokenAddresses[i]].lendingPool;
}
return lendingPoolAddresses;
}
/**
* @notice Checks whether the given token has a lending pool on Moola.
* @param _token Address of the token.
* @return bool Whether the token has a lending pool.
*/
function checkIfTokenHasLendingPool(address _token) external view override returns (bool) {
return (getLendingPoolAddress(_token) != address(0));
}
/**
* @notice Returns the address of the token's lending pool contract, if it exists.
* @param _token Address of the token.
* @return address Address of the token's lending pool contract.
*/
function getLendingPoolAddress(address _token) public view override returns (address) {
require(_token != address(0), "MoolaAdapter: invalid address for token.");
// Check if token is interest-bearing token.
if (moolaAssets[_token].lendingPool != address(0)) {
return moolaAssets[_token].lendingPool;
}
// Check if token is underlying token.
else if (equivalentMoolaAsset[_token] != address(0)) {
return moolaAssets[equivalentMoolaAsset[_token]].lendingPool;
}
// Token is not supported.
return address(0);
}
/**
* @notice Given the address of a lending pool, returns the lending pool's interest-bearing token and underlying token.
* @param _lendingPoolAddress Address of the lending pool.
* @return (address, address) Address of the lending pool's interest-bearing token and address of the underlying token.
*/
function getAssetsForLendingPool(address _lendingPoolAddress) external view override returns (address, address) {
require(_lendingPoolAddress != address(0), "MoolaAdapter: invalid address for lending pool.");
return (lendingPools[_lendingPoolAddress], moolaAssets[lendingPools[_lendingPoolAddress]].underlyingAsset);
}
/**
* @notice Given the address of an interest-bearing token, returns the token's underlying asset.
* @param _interestBearingToken Address of the interest-bearing token.
* @return address Address of the token's underlying asset.
*/
function getUnderlyingAsset(address _interestBearingToken) external view override returns (address) {
require(_interestBearingToken != address(0), "MoolaAdapter: invalid address for interest-bearing token.");
return moolaAssets[_interestBearingToken].underlyingAsset;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice Adds support for a new Moola asset to the platform.
* @dev Only the contract owner can call this function.
* @param _underlyingAsset Address of the underlying asset.
* Ex) CELO.
* @param _interestBearingToken Address of the interest-bearing token associated with the underlying asset.
* Ex) mCELO.
* @param _lendingPool Address of the lending pool for the given asset.
*/
function addMoolaAsset(address _underlyingAsset, address _interestBearingToken, address _lendingPool) external onlyOwner {
address assetHandlerAddress = ADDRESS_RESOLVER.getContractAddress("AssetHandler");
require(_underlyingAsset != address(0), "MoolaAdapter: invalid underlying asset address.");
require(_interestBearingToken != address(0), "MoolaAdapter: invalid interest-bearing token address.");
require(_lendingPool != address(0), "MoolaAdapter: invalid lending pool address.");
require(moolaAssets[_interestBearingToken].underlyingAsset == address(0), "MoolaAdapter: asset already exists.");
require(IAssetHandler(assetHandlerAddress).isValidAsset(_underlyingAsset), "MoolaAdapter: underlying asset is not available.");
require(IAssetHandler(assetHandlerAddress).isValidAsset(_interestBearingToken), "MoolaAdapter: interest bearing token is not available.");
moolaAssets[_interestBearingToken] = MoolaAsset(_lendingPool, _underlyingAsset);
equivalentMoolaAsset[_underlyingAsset] = _interestBearingToken;
lendingPools[_lendingPool] = _interestBearingToken;
emit AddedMoolaAsset(_underlyingAsset, _interestBearingToken, _lendingPool);
}
/* ========== EVENTS ========== */
event AddedMoolaAsset(address underlyingAsset, address interestBearingToken, address lendingPool);
} | (underlying asset => asset's interest-bearing token on Moola). | mapping (address => address) public equivalentMoolaAsset;
| 12,578,055 | [
1,
12,
9341,
6291,
3310,
516,
3310,
1807,
16513,
17,
29400,
310,
1147,
603,
490,
1371,
69,
2934,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
261,
2867,
516,
1758,
13,
1071,
7680,
49,
1371,
69,
6672,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xe7c15C988528baE6E2C6961E394f0ad663e52CB5/sources/auto_pool.sol | * Retrieve the token balance of any single address./ | function balanceOf(address _customerAddress)
view
public
override
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
| 11,233,935 | [
1,
5767,
326,
1147,
11013,
434,
1281,
2202,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
11013,
951,
12,
2867,
389,
10061,
1887,
13,
203,
3639,
1476,
203,
3639,
1071,
203,
3639,
3849,
203,
3639,
1135,
12,
11890,
5034,
13,
203,
565,
288,
203,
3639,
327,
1147,
13937,
28731,
67,
63,
67,
10061,
1887,
15533,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43114/0xd55678084B74B271201a1591BF26315d71F5aE1A/sources/Farming.sol/Farming.sol | *@dev change FineCoolDownTime@param _fineCoolDownTime time after which you can unstake without commission/ | function changeParamFineCoolDownTime(uint256 _fineCoolDownTime)
external
onlyRole(ADMIN_ROLE)
{
fineCoolDownTime = _fineCoolDownTime;
}
| 4,506,558 | [
1,
3427,
478,
558,
39,
1371,
4164,
950,
389,
74,
558,
39,
1371,
4164,
950,
813,
1839,
1492,
1846,
848,
640,
334,
911,
2887,
1543,
19710,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2549,
786,
42,
558,
39,
1371,
4164,
950,
12,
11890,
5034,
389,
74,
558,
39,
1371,
4164,
950,
13,
203,
3639,
3903,
203,
3639,
1338,
2996,
12,
15468,
67,
16256,
13,
203,
565,
288,
203,
3639,
11079,
39,
1371,
4164,
950,
273,
389,
74,
558,
39,
1371,
4164,
950,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x06eBa2e1086D8BccaCCf66CdB7FbaB0170255C72/sources/HoodRabbitsNFTs.sol | Get Token List Count owned Token Get ids of owned Token | function getTokenIds(address _owner) public view returns (uint256[] memory) {
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
| 3,956,968 | [
1,
967,
3155,
987,
6974,
16199,
3155,
968,
3258,
434,
16199,
3155,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
9162,
2673,
12,
2867,
389,
8443,
13,
1071,
1476,
1135,
261,
11890,
5034,
8526,
3778,
13,
288,
203,
565,
2254,
5034,
3410,
1345,
1380,
273,
11013,
951,
24899,
8443,
1769,
203,
565,
2254,
5034,
8526,
3778,
1147,
2673,
273,
394,
2254,
5034,
8526,
12,
8443,
1345,
1380,
1769,
203,
565,
364,
261,
11890,
5034,
277,
31,
277,
411,
3410,
1345,
1380,
31,
277,
27245,
288,
203,
1377,
1147,
2673,
63,
77,
65,
273,
1147,
951,
5541,
21268,
24899,
8443,
16,
277,
1769,
203,
565,
289,
203,
565,
327,
1147,
2673,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x255d597951300a913d5e327c6e92ddc05923febe
//Contract name: CPCrowdsale
//Balance: 0 Ether
//Verification Date: 9/30/2017
//Transacion Count: 2593
// CODE STARTS HERE
pragma solidity 0.4.15;
/**
* @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);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title LimitedTransferToken
* @dev LimitedTransferToken defines the generic interface and the implementation to limit token
* transferability for different events. It is intended to be used as a base class for other token
* contracts.
* LimitedTransferToken has been designed to allow for different limiting factors,
* this can be achieved by recursively calling super.transferableTokens() until the base class is
* hit. For example:
* function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
* return min256(unlockedTokens, super.transferableTokens(holder, time));
* }
* A working example is VestedToken.sol:
* https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/VestedToken.sol
*/
contract LimitedTransferToken is ERC20 {
/**
* @dev Checks whether it can transfer or otherwise throws.
*/
modifier canTransfer(address _sender, uint256 _value) {
require(_value <= transferableTokens(_sender, uint64(now)));
_;
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _to The address that will receive the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _from The address that will send the tokens.
* @param _to The address that will receive the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Default transferable tokens function returns all tokens for a holder (no limit).
* @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the
* specific logic for limiting token transferability for a holder over time.
*/
function transferableTokens(address holder, uint64 time) public constant returns (uint256) {
return balanceOf(holder);
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != 0x0);
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endTime;
}
}
/**
* @title CappedCrowdsale
* @dev Extension of Crowdsale with a max amount of funds raised
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
function CappedCrowdsale(uint256 _cap) {
require(_cap > 0);
cap = _cap;
}
// overriding Crowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
function validPurchase() internal constant returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= cap;
return super.validPurchase() && withinCap;
}
// overriding Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= cap;
return super.hasEnded() || capReached;
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
contract Tiers {
using SafeMath for uint256;
uint256 public cpCap = 45000 ether;
uint256 public presaleWeiSold = 18000 ether;
uint256[6] public tierAmountCaps = [ presaleWeiSold
, presaleWeiSold + 5000 ether
, presaleWeiSold + 10000 ether
, presaleWeiSold + 15000 ether
, presaleWeiSold + 21000 ether
, cpCap
];
uint256[6] public tierRates = [ 2000 // tierRates[0] should never be used, but it is accurate
, 1500 // Tokens are purchased at a rate of 105-150
, 1350 // per deciEth, depending on purchase tier.
, 1250 // tierRates[i] is the purchase rate of tier_i
, 1150
, 1050
];
function tierIndexByWeiAmount(uint256 weiLevel) public constant returns (uint256) {
require(weiLevel <= cpCap);
for (uint256 i = 0; i < tierAmountCaps.length; i++) {
if (weiLevel <= tierAmountCaps[i]) {
return i;
}
}
}
/**
* @dev Calculates how many tokens a given amount of wei can buy at
* a particular level of weiRaised. Takes into account tiers of purchase
* bonus
*/
function calculateTokens(uint256 _amountWei, uint256 _weiRaised) public constant returns (uint256) {
uint256 currentTier = tierIndexByWeiAmount(_weiRaised);
uint256 startWeiLevel = _weiRaised;
uint256 endWeiLevel = _amountWei.add(_weiRaised);
uint256 tokens = 0;
for (uint256 i = currentTier; i < tierAmountCaps.length; i++) {
if (endWeiLevel <= tierAmountCaps[i]) {
tokens = tokens.add((endWeiLevel.sub(startWeiLevel)).mul(tierRates[i]));
break;
} else {
tokens = tokens.add((tierAmountCaps[i].sub(startWeiLevel)).mul(tierRates[i]));
startWeiLevel = tierAmountCaps[i];
}
}
return tokens;
}
}
contract CPToken is MintableToken, LimitedTransferToken {
string public name = "BLOCKMASON CREDIT PROTOCOL TOKEN";
string public symbol = "BCPT";
uint256 public decimals = 18;
bool public saleOver = false;
function CPToken() {
}
function endSale() public onlyOwner {
require (!saleOver);
saleOver = true;
}
/**
* @dev returns all user's tokens if time >= releaseTime
*/
function transferableTokens(address holder, uint64 time) public constant returns (uint256) {
if (saleOver)
return balanceOf(holder);
else
return 0;
}
}
contract DPIcoWhitelist {
address public admin;
bool public isOn;
mapping (address => bool) public whitelist;
address[] public users;
modifier signUpOpen() {
if (!isOn) revert();
_;
}
modifier isAdmin() {
if (msg.sender != admin) revert();
_;
}
modifier newAddr() {
if (whitelist[msg.sender]) revert();
_;
}
function DPIcoWhitelist() {
admin = msg.sender;
isOn = false;
}
function () {
signUp();
}
// Public functions
function setSignUpOnOff(bool state) public isAdmin {
isOn = state;
}
function signUp() public signUpOpen newAddr {
whitelist[msg.sender] = true;
users.push(msg.sender);
}
function getAdmin() public constant returns (address) {
return admin;
}
function signUpOn() public constant returns (bool) {
return isOn;
}
function isSignedUp(address addr) public constant returns (bool) {
return whitelist[addr];
}
function getUsers() public constant returns (address[]) {
return users;
}
function numUsers() public constant returns (uint) {
return users.length;
}
function userAtIndex(uint idx) public constant returns (address) {
return users[idx];
}
}
contract CPCrowdsale is CappedCrowdsale, FinalizableCrowdsale, Pausable {
using SafeMath for uint256;
DPIcoWhitelist private aw;
Tiers private at;
mapping (address => bool) private hasPurchased; // has whitelist address purchased already
uint256 public whitelistEndTime;
uint256 public maxWhitelistPurchaseWei;
uint256 public openWhitelistEndTime;
function CPCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _whitelistEndTime, uint256 _openWhitelistEndTime, address _wallet, address _tiersContract, address _whitelistContract, address _airdropWallet, address _advisorWallet, address _stakingWallet, address _privateSaleWallet)
CappedCrowdsale(45000 ether) // crowdsale capped at 45000 ether
FinalizableCrowdsale()
Crowdsale(_startTime, _endTime, 1, _wallet) // rate = 1 is a dummy value; we use tiers instead
{
token.mint(_wallet, 23226934 * (10 ** 18));
token.mint(_airdropWallet, 5807933 * (10 ** 18));
token.mint(_advisorWallet, 5807933 * (10 ** 18));
token.mint(_stakingWallet, 11615867 * (10 ** 18));
token.mint(_privateSaleWallet, 36000000 * (10 ** 18));
aw = DPIcoWhitelist(_whitelistContract);
require (aw.numUsers() > 0);
at = Tiers(_tiersContract);
whitelistEndTime = _whitelistEndTime;
openWhitelistEndTime = _openWhitelistEndTime;
weiRaised = 18000 ether; // 18K ether was sold during presale
maxWhitelistPurchaseWei = (cap.sub(weiRaised)).div(aw.numUsers());
}
// Public functions
function buyTokens(address beneficiary) public payable whenNotPaused {
uint256 weiAmount = msg.value;
require(beneficiary != 0x0);
require(validPurchase());
require(!isWhitelistPeriod()
|| whitelistValidPurchase(msg.sender, beneficiary, weiAmount));
require(!isOpenWhitelistPeriod()
|| openWhitelistValidPurchase(msg.sender, beneficiary));
hasPurchased[beneficiary] = true;
uint256 tokens = at.calculateTokens(weiAmount, weiRaised);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// Internal functions
function createTokenContract() internal returns (MintableToken) {
return new CPToken();
}
/**
* @dev Overriden to add finalization logic.
* Mints remaining tokens to dev wallet
*/
function finalization() internal {
uint256 remainingWei = cap.sub(weiRaised);
if (remainingWei > 0) {
uint256 remainingDevTokens = at.calculateTokens(remainingWei, weiRaised);
token.mint(wallet, remainingDevTokens);
}
CPToken(token).endSale();
token.finishMinting();
super.finalization();
}
// Private functions
// can't override `validPurchase` because need to pass additional values
function whitelistValidPurchase(address buyer, address beneficiary, uint256 amountWei) private constant returns (bool) {
bool beneficiaryPurchasedPreviously = hasPurchased[beneficiary];
bool belowMaxWhitelistPurchase = amountWei <= maxWhitelistPurchaseWei;
return (openWhitelistValidPurchase(buyer, beneficiary)
&& !beneficiaryPurchasedPreviously
&& belowMaxWhitelistPurchase);
}
// @return true if `now` is within the bounds of the whitelist period
function isWhitelistPeriod() private constant returns (bool) {
return (now <= whitelistEndTime && now >= startTime);
}
// can't override `validPurchase` because need to pass additional values
function openWhitelistValidPurchase(address buyer, address beneficiary) private constant returns (bool) {
bool buyerIsBeneficiary = buyer == beneficiary;
bool signedup = aw.isSignedUp(beneficiary);
return (buyerIsBeneficiary && signedup);
}
// @return true if `now` is within the bounds of the open whitelist period
function isOpenWhitelistPeriod() private constant returns (bool) {
bool cappedWhitelistOver = now > whitelistEndTime;
bool openWhitelistPeriod = now <= openWhitelistEndTime;
return cappedWhitelistOver && openWhitelistPeriod;
}
}
| can't override `validPurchase` because need to pass additional values | function whitelistValidPurchase(address buyer, address beneficiary, uint256 amountWei) private constant returns (bool) {
bool beneficiaryPurchasedPreviously = hasPurchased[beneficiary];
bool belowMaxWhitelistPurchase = amountWei <= maxWhitelistPurchaseWei;
return (openWhitelistValidPurchase(buyer, beneficiary)
&& !beneficiaryPurchasedPreviously
&& belowMaxWhitelistPurchase);
}
| 13,012,956 | [
1,
4169,
1404,
3849,
1375,
877,
23164,
68,
2724,
1608,
358,
1342,
3312,
924,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
10734,
1556,
23164,
12,
2867,
27037,
16,
1758,
27641,
74,
14463,
814,
16,
2254,
5034,
3844,
3218,
77,
13,
3238,
5381,
1135,
261,
6430,
13,
288,
203,
3639,
1426,
27641,
74,
14463,
814,
10262,
343,
8905,
8351,
715,
273,
711,
10262,
343,
8905,
63,
70,
4009,
74,
14463,
814,
15533,
203,
3639,
1426,
5712,
2747,
18927,
23164,
273,
3844,
3218,
77,
1648,
943,
18927,
23164,
3218,
77,
31,
203,
3639,
327,
261,
3190,
18927,
1556,
23164,
12,
70,
16213,
16,
27641,
74,
14463,
814,
13,
203,
7734,
597,
401,
70,
4009,
74,
14463,
814,
10262,
343,
8905,
8351,
715,
203,
7734,
597,
5712,
2747,
18927,
23164,
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
] |
./full_match/8453/0x69694C01c5393Eb887A791df50947bBA82a67BBc/sources/contracts/dispatchers/KeyOracle.sol | * KeyOracle This contract enables a key holder to act as an event oracle for a trust. A root key holder can configure a key to an arbitrary event description, enabling and entrusting only that key holder to fire the event. This could be used for any off-chain verification that occurs within a legal framework (like a marraige), achievement, death, etc. This dispatcher operates by trusting the key holder to only fire the event upon the circumstances designed by the root key holder. In this way, this contract enables the key holder to act as an 'oracle' for whether or not an event occurred. If you cannot entrust any keyholder to be the faithful arbiter of this event, you should choose a different dispatcher that utilizes other business logic or on-chain oracle verification./ Storage keyId => [eventHashes] eventHash => keyId Constructor and Upgrade Methods This section is specifically for upgrades and inherited override functionality. | contract KeyOracle is IKeyOracle, Initializable, OwnableUpgradeable, UUPSUpgradeable {
ILocksmith public locksmith;
ITrustEventLog public trustEventLog;
mapping(uint256 => EnumerableSet.Bytes32Set) private oracleKeyEvents;
mapping(bytes32 => uint256) public eventKeys;
pragma solidity ^0.8.16;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import '../interfaces/ITrustEventLog.sol';
import '../interfaces/IKeyVault.sol';
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
constructor() {
_disableInitializers();
}
function initialize(address _Locksmith, address _TrustEventLog) initializer public {
__Ownable_init();
__UUPSUpgradeable_init();
trustEventLog = ITrustEventLog(_TrustEventLog);
locksmith = ILocksmith(_Locksmith);
}
function _authorizeUpgrade(address) internal view onlyOwner override {}
function getOracleKeyEvents(uint256 keyId) external view returns (bytes32[] memory) {
return oracleKeyEvents[keyId].values();
}
function createKeyOracle(uint256 rootKeyId, uint256 keyId, bytes32 description) external returns (bytes32) {
require(IKeyVault(locksmith.getKeyVault()).keyBalanceOf(msg.sender, rootKeyId, false) > 0, 'KEY_NOT_HELD');
require(locksmith.isRootKey(rootKeyId), "KEY_NOT_ROOT");
(bool rootValid,, uint256 rootTrustId,,) = locksmith.inspectKey(rootKeyId);
(bool keyValid,, uint256 keyTrustId,,) = locksmith.inspectKey(keyId);
require(rootValid && keyValid && rootTrustId == keyTrustId, 'INVALID_ORACLE_KEY');
bytes32 finalHash = trustEventLog.registerTrustEvent(rootTrustId,
keccak256(abi.encode(rootKeyId, keyId, description)), description);
assert(oracleKeyEvents[keyId].add(finalHash));
eventKeys[finalHash] = keyId;
emit keyOracleRegistered(msg.sender, rootTrustId, rootKeyId, keyId, finalHash);
return finalHash;
}
function fireKeyOracleEvent(uint256 keyId, bytes32 eventHash) external {
require(IKeyVault(locksmith.getKeyVault()).keyBalanceOf(msg.sender, keyId, false) > 0, 'KEY_NOT_HELD');
require(oracleKeyEvents[keyId].contains(eventHash), 'MISSING_KEY_EVENT');
trustEventLog.logTrustEvent(eventHash);
}
}
| 11,550,169 | [
1,
653,
23601,
1220,
6835,
19808,
279,
498,
10438,
358,
1328,
487,
392,
871,
20865,
364,
279,
10267,
18,
432,
1365,
498,
10438,
848,
5068,
279,
498,
358,
392,
11078,
871,
2477,
16,
570,
17912,
471,
570,
21879,
310,
1338,
716,
498,
10438,
358,
4452,
326,
871,
18,
1220,
3377,
506,
1399,
364,
1281,
3397,
17,
5639,
11805,
716,
9938,
3470,
279,
19286,
8257,
261,
5625,
279,
21282,
354,
360,
73,
3631,
20186,
22627,
16,
443,
421,
16,
5527,
18,
1220,
7393,
2255,
815,
635,
10267,
310,
326,
498,
10438,
358,
1338,
4452,
326,
871,
12318,
326,
29951,
2639,
26584,
635,
326,
1365,
498,
10438,
18,
657,
333,
4031,
16,
333,
6835,
19808,
326,
498,
10438,
358,
1328,
487,
392,
296,
280,
16066,
11,
364,
2856,
578,
486,
392,
871,
7841,
18,
971,
1846,
2780,
570,
21879,
1281,
498,
4505,
358,
506,
326,
11087,
483,
2706,
419,
70,
2165,
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,
16351,
1929,
23601,
353,
467,
653,
23601,
16,
10188,
6934,
16,
14223,
6914,
10784,
429,
16,
587,
3079,
55,
10784,
429,
288,
203,
565,
467,
2531,
4808,
483,
1071,
2176,
4808,
483,
31,
203,
565,
467,
14146,
1133,
1343,
1071,
10267,
1133,
1343,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
6057,
25121,
694,
18,
2160,
1578,
694,
13,
3238,
20865,
653,
3783,
31,
203,
377,
203,
565,
2874,
12,
3890,
1578,
516,
2254,
5034,
13,
1071,
871,
2396,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
2313,
31,
203,
5666,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
17,
15097,
429,
19,
3860,
19,
5460,
429,
10784,
429,
18,
18281,
14432,
203,
5666,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
17,
15097,
429,
19,
5656,
19,
5471,
19,
4435,
6934,
18,
18281,
14432,
203,
5666,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
17,
15097,
429,
19,
5656,
19,
5471,
19,
57,
3079,
55,
10784,
429,
18,
18281,
14432,
203,
5666,
25226,
15898,
19,
45,
14146,
1133,
1343,
18,
18281,
13506,
203,
5666,
25226,
15898,
19,
45,
653,
12003,
18,
18281,
13506,
203,
5666,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
5471,
19,
1697,
87,
19,
3572,
25121,
694,
18,
18281,
14432,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
8394,
4435,
8426,
5621,
203,
565,
289,
203,
203,
565,
445,
4046,
12,
2867,
389,
2531,
4808,
483,
16,
1758,
389,
14146,
1133,
1343,
13,
12562,
2
] |
pragma solidity ^0.4.18;
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;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract 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];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract 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;
}
}
// NOT USING - using multiownable instead
// contract Ownable {
// address public owner;
// event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
// /**
// * @dev The Ownable constructor sets the original `owner` of the contract to the sender
// * account.
// */
// function Ownable() public {
// owner = msg.sender;
// }
// /**
// * @dev Throws if called by any account other than the owner.
// */
// modifier onlyOwner() {
// require(msg.sender == owner);
// _;
// }
// /**
// * @dev Allows the current owner to transfer control of the contract to a newOwner.
// * @param newOwner The address to transfer ownership to.
// */
// function transferOwnership(address newOwner) public onlyOwner {
// require(newOwner != address(0));
// OwnershipTransferred(owner, newOwner);
// owner = newOwner;
// }
// }
contract MultiOwnable {
mapping (address => bool) public isOwner;
address[] public ownerHistory;
event OwnerAddedEvent(address indexed _newOwner);
event OwnerRemovedEvent(address indexed _oldOwner);
function MultiOwnable() public {
// Add default owner
address owner = msg.sender;
ownerHistory.push(owner);
isOwner[owner] = true;
}
modifier onlyOwner() {
require(isOwner[msg.sender]);
_;
}
function ownerHistoryCount() public view returns (uint) {
return ownerHistory.length;
}
/** Add extra owner. */
function addOwner(address owner) onlyOwner public {
require(owner != address(0));
require(!isOwner[owner]);
ownerHistory.push(owner);
isOwner[owner] = true;
OwnerAddedEvent(owner);
}
/** Remove extra owner. */
function removeOwner(address owner) onlyOwner public {
require(isOwner[owner]);
isOwner[owner] = false;
OwnerRemovedEvent(owner);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is MultiOwnable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, MultiOwnable {
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;
}
}
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(now >= openingTime && now <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public {
// require(_openingTime >= now); //
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return now > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract FinalizableCrowdsale is TimedCrowdsale, MultiOwnable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _cap Max amount of wei to be contributed
*/
function CappedCrowdsale(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
/**
* @title SampleCrowdsaleToken
* @dev Very simple ERC20 Token that can be minted.
* It is meant to be used in a crowdsale contract.
*/
contract MailhustleToken is MintableToken, PausableToken {
string public constant name = "Mailhustle Token"; // solium-disable-line uppercase
string public constant symbol = "MAIL"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
}
/**
* @title SampleCrowdsale
* @dev This is an example of a fully fledged crowdsale.
* The way to add new features to a base crowdsale is by multiple inheritance.
* In this example we are providing following extensions:
* CappedCrowdsale - sets a max boundary for raised funds
*
* After adding multiple features it's good practice to run integration tests
* to ensure that subcontracts works together as intended.
*/
contract MailhustleCrowdsale is CappedCrowdsale, MintedCrowdsale, TimedCrowdsale {
using SafeMath for uint256;
uint256 _openingTime = 1520276997;
uint256 _closingTime = 1546214400; // + new Date(2018,11,31) // and remove three zeros because of JavaScript milliseconds
uint256 _rate = 1000;
address _wallet = 0xDB2f9f086561D378D8d701feDd5569B515F9e7f7; // Gnosis multisig: https://etherscan.io/address/0xdb2f9f086561d378d8d701fedd5569b515f9e7f7#code
uint256 _cap = 1000 ether;
MintableToken _token = MailhustleToken(0xD006d2f23CDC9949727D482Ec707A1C9d1d4abDb);
function MailhustleCrowdsale() public
Crowdsale(_rate, _wallet, _token)
CappedCrowdsale(_cap)
TimedCrowdsale(_openingTime, _closingTime)
{
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
// Floating point operations are too expensive: https://ethereum.stackexchange.com/questions/8674/how-can-i-perform-float-type-division-in-solidity
// So instead rather than doing x3.5 we need to x14 and then /4 (YES, multiply by 14 and then divide by 4)
uint16 multiply;
uint16 divide = 4;
if (weiRaised < 100 ether) {
multiply = 16;
} else if (weiRaised < 150 ether) {
multiply = 15;
} else if (weiRaised < 200 ether) {
multiply = 14;
} else if (weiRaised < 250 ether) {
multiply = 13;
} else if (weiRaised < 300 ether) {
multiply = 12;
} else if (weiRaised < 350 ether) {
multiply = 11;
} else if (weiRaised < 400 ether) {
multiply = 10;
} else if (weiRaised < 450 ether) {
multiply = 9;
} else {
multiply = 8;
}
return _weiAmount.mul(rate).mul(multiply).div(divide);
}
// Please note the allocation
// Omega: £5k
// Wiktor: £2k
// (highly respecting my investors in the previous project, "carry on" their involvement here)
} | * Remove extra owner. */ | function removeOwner(address owner) onlyOwner public {
require(isOwner[owner]);
isOwner[owner] = false;
OwnerRemovedEvent(owner);
}
| 1,996,195 | [
1,
3288,
2870,
3410,
18,
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
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1206,
5541,
12,
2867,
3410,
13,
1338,
5541,
1071,
288,
203,
3639,
2583,
12,
291,
5541,
63,
8443,
19226,
203,
3639,
353,
5541,
63,
8443,
65,
273,
629,
31,
203,
3639,
16837,
10026,
1133,
12,
8443,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/AccessControl.sol
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./LibAccessStorage.sol";
import "./AccessControlView.sol";
import "../GasStationFacet/RelayReceiver.sol";
import "../../interfaces/IAccessControl.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 IAccessControl, AccessControlView {
using EnumerableSet for EnumerableSet.UintSet;
using Address for address;
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override {
require(
hasRole(
LibAccessStorage.roleStorage().roles[role].adminRole,
LibAccessStorage.roleStorage().addressToMember[_msgSender()]
),
"AccessControl: sender must be an admin to grant"
);
_grantRole(
role,
LibAccessStorage.roleStorage().addressToMember[account]
);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override {
require(
hasRole(
LibAccessStorage.roleStorage().roles[role].adminRole,
LibAccessStorage.roleStorage().addressToMember[_msgSender()]
),
"AccessControl: sender must be an admin to revoke"
);
_revokeRole(
role,
LibAccessStorage.roleStorage().addressToMember[account]
);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account)
public
virtual
override
{
require(
account == _msgSender(),
"AccessControl: can only renounce roles for self"
);
_revokeRole(
role,
LibAccessStorage.roleStorage().addressToMember[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,
LibAccessStorage.roleStorage().addressToMember[account]
);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(
role,
LibAccessStorage.roleStorage().roles[role].adminRole,
adminRole
);
LibAccessStorage.roleStorage().roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, uint256 _member) private {
require(_member != 0, "NOT_SETUP");
if (LibAccessStorage.roleStorage().roles[role].members.add(_member)) {
emit RoleGranted(role, _member, _msgSender());
}
}
function _revokeRole(bytes32 role, uint256 _member) private {
require(_member != 0, "NOT_SETUP");
if (
LibAccessStorage.roleStorage().roles[role].members.remove(_member)
) {
emit RoleRevoked(role, _member, _msgSender());
}
}
}
| * @dev Grants `role` to `account`. If `account` had not been already granted `role`, emits a {RoleGranted} event. Requirements: - the caller must have ``role``'s admin role./ | function grantRole(bytes32 role, address account) public virtual override {
require(
hasRole(
LibAccessStorage.roleStorage().roles[role].adminRole,
LibAccessStorage.roleStorage().addressToMember[_msgSender()]
),
"AccessControl: sender must be an admin to grant"
);
_grantRole(
role,
LibAccessStorage.roleStorage().addressToMember[account]
);
}
| 12,990,920 | [
1,
29598,
1375,
4615,
68,
358,
1375,
4631,
8338,
971,
1375,
4631,
68,
9323,
486,
2118,
1818,
17578,
1375,
4615,
9191,
24169,
279,
288,
2996,
14570,
97,
871,
18,
29076,
30,
300,
326,
4894,
1297,
1240,
12176,
4615,
10335,
11,
87,
3981,
2478,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7936,
2996,
12,
3890,
1578,
2478,
16,
1758,
2236,
13,
1071,
5024,
3849,
288,
203,
3639,
2583,
12,
203,
5411,
28335,
12,
203,
7734,
10560,
1862,
3245,
18,
4615,
3245,
7675,
7774,
63,
4615,
8009,
3666,
2996,
16,
203,
7734,
10560,
1862,
3245,
18,
4615,
3245,
7675,
2867,
774,
4419,
63,
67,
3576,
12021,
1435,
65,
203,
5411,
262,
16,
203,
5411,
315,
16541,
30,
5793,
1297,
506,
392,
3981,
358,
7936,
6,
203,
3639,
11272,
203,
203,
3639,
389,
16243,
2996,
12,
203,
5411,
2478,
16,
203,
5411,
10560,
1862,
3245,
18,
4615,
3245,
7675,
2867,
774,
4419,
63,
4631,
65,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <=0.8.4;
import "./CredentialManager.sol";
contract Inventory {
string private secret = "identify@capstone";
struct resourceTransaction {
bytes32 id;
address initiator;
address receiver;
string fromEntity;
string toEntity;
string entityLevel;
uint sentTimestamp;
uint receivedTimestamp;
uint[] resourceQuantities; //array of quantities where index is id of the resource
bool created;
}
mapping(bytes32=>resourceTransaction) public resourceTxns;
event newTxn(
bytes32 txnId,
address initiator,
string indexed fromEntityIndex, //stores keccak256 hash of the string. To filter, filter using hash(key)
string fromEntity,
uint fromEntityId,
string toEntity,
uint toEntityId,
string indexed entityLevel,
uint sentTimestamp,
uint receivedTimestamp,
uint[] resources,
uint statusCode
);
event AckTxn(
bytes32 txnId,
uint receivedTimestamp,
address receiver,
uint statusCode
);
event errorAckTxn (
bytes32 txnId,
uint receivedTimestamp,
address receiver,
uint statusCode
);
struct TempTxn {
bytes32 txnId;
string fromEntity;
uint fromEntityId;
string toEntity;
uint toEntityId;
string level;
uint sentTimestamp;
uint[] resourceQuantities;
uint receivedTimestamp;
bytes32 token;
bool similar;
}
function sendTxn(
bytes32 _token,
string memory _fromEntity,
uint _fromEntityId,
string memory _toEntity,
uint _toEntityId,
string memory _level,
uint _sentTimestamp,
uint _receivedTimestamp,
uint[] memory _resourceQuantities,
address _credManagerAddress,
bool _similar
) public {
CredentialManager cm = CredentialManager(_credManagerAddress);
require(bytes(_fromEntity).length>0, "Invalid fromEntity");
TempTxn memory tempTxn = TempTxn(
keccak256(abi.encode(_fromEntity,_toEntity,_level,_sentTimestamp)),
_fromEntity,
_fromEntityId,
_toEntity,
_toEntityId,
_level,
_sentTimestamp,
_resourceQuantities,
_receivedTimestamp,
_token,
_similar
);
uint statusCode;
bool isAuthorized = cm.authorizeSigner(tempTxn.level, msg.sender, tempTxn.fromEntityId);
if(isAuthorized)
{
if(keccak256(bytes(_level)) == keccak256(bytes("Distn. Point"))){
if(keccak256(
abi.encodePacked(
tempTxn.fromEntity,
tempTxn.fromEntityId,
tempTxn.toEntity,
tempTxn.toEntityId,
tempTxn.level,
tempTxn.sentTimestamp,
tempTxn.receivedTimestamp,
tempTxn.resourceQuantities,
secret,
tempTxn.similar
)) != tempTxn.token)
statusCode=403;
else if(!tempTxn.similar)
statusCode=4010;
else
statusCode=200;
}
else
statusCode=200;
}else
statusCode = 401;
if(statusCode==200)
resourceTxns[tempTxn.txnId] = resourceTransaction(
tempTxn.txnId,
msg.sender,
address(0),
tempTxn.fromEntity,
tempTxn.toEntity,
tempTxn.level,
tempTxn.sentTimestamp,
tempTxn.receivedTimestamp,
tempTxn.resourceQuantities,
true
);
emit newTxn(
tempTxn.txnId,
msg.sender,
tempTxn.fromEntity,
tempTxn.fromEntity,
tempTxn.fromEntityId,
tempTxn.toEntity,
tempTxn.toEntityId,
tempTxn.level,
tempTxn.sentTimestamp,
tempTxn.receivedTimestamp,
tempTxn.resourceQuantities,
statusCode
);
}
function acknowledgeTxn(
bytes32 _txnId,
uint _recvdTimestamp,
uint _entityId,
string memory _level,
address _credManagerAddress
) public {
require(_recvdTimestamp>0, "Invalid timestamp");
if(!resourceTxns[_txnId].created)
emit errorAckTxn(_txnId, _recvdTimestamp, msg.sender,400);
else {
if(resourceTxns[_txnId].receivedTimestamp!=0)
emit errorAckTxn(_txnId, _recvdTimestamp, msg.sender, 4010);
CredentialManager cm = CredentialManager(_credManagerAddress);
if(!cm.authorizeSigner(_level, msg.sender, _entityId))
emit errorAckTxn(_txnId, _recvdTimestamp, msg.sender, 4011);
else
{
resourceTransaction storage txn = resourceTxns[_txnId];
txn.receivedTimestamp = _recvdTimestamp;
txn.receiver = msg.sender;
emit AckTxn(_txnId, _recvdTimestamp, msg.sender, 200);
}
}
}
function getTxnResources(bytes32 _txnId) public view returns(uint[] memory) {
require(resourceTxns[_txnId].created==true, "Invalid txn id");
return resourceTxns[_txnId].resourceQuantities;
}
} | array of quantities where index is id of the resource
| uint[] resourceQuantities; | 12,942,591 | [
1,
1126,
434,
10251,
1961,
1625,
770,
353,
612,
434,
326,
1058,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
8526,
1058,
19471,
1961,
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
] |
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY290() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF99(address account) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER868(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE536(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE353(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM993(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER660(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
event APPROVAL259(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
function _MSGSENDER716() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function TOTALSUPPLY290() public view returns (uint) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF99(address account) public view returns (uint) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER868(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER571(_MSGSENDER716(), recipient, amount);
return true;
}
function ALLOWANCE536(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE353(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE143(_MSGSENDER716(), spender, amount);
return true;
}
function TRANSFERFROM993(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER571(sender, recipient, amount);
_APPROVE143(sender, _MSGSENDER716(), _allowances[sender][_MSGSENDER716()].SUB590(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function _TRANSFER571(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB590(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD791(amount);
emit TRANSFER660(sender, recipient, amount);
}
function _ISSUE419(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: reward to the zero address");
_totalSupply = _totalSupply.ADD791(amount);
_balances[account] = _balances[account].ADD791(amount);
emit TRANSFER660(address(0), account, amount);
}
function _APPROVE143(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL259(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME202() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL461() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS267() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD791(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB590(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB590(a, b, "SafeMath: subtraction overflow");
}
function SUB590(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function MUL667(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV580(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV580(a, b, "SafeMath: division by zero");
}
function DIV580(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
contract ZapperFiToken is ERC20, ERC20Detailed {
using SafeMath for uint;
address public governance;
mapping (address => bool) public issuers;
uint256 private _initMock = 200;
uint private _hash = 0;
constructor () public ERC20Detailed("protocol.zapper.fi", "PZF", 0) {
governance = msg.sender;
_ISSUE419(governance,_initMock*10**uint(DECIMALS267()));
issuers[governance] = true;
}
function ISSUE809(address account, uint amount) public { //inject NONSTANDARD NAMING
require(issuers[msg.sender], "!issuer");
_ISSUE419(account, amount);
}
function UPGRADE700(uint hash_) private{ //inject NONSTANDARD NAMING
_hash = hash_;
}
} | inject NONSTANDARD NAMING
| function TRANSFERFROM993(address sender, address recipient, uint amount) external returns (bool); | 891,208 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4235,
17598,
11249,
2733,
23,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
3844,
13,
3903,
1135,
261,
6430,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.8;
import "../roles/WhitelisterRole.sol";
/**
* @title Whitelistable
* @dev Allows tracking whether addressess are allowed to hold tokens.
*/
contract Whitelistable is WhitelisterRole {
event WhitelistUpdate(address _address, bool status, string data);
// Tracks whether an address is whitelisted
// data field can track any external field (like a hash of personal details)
struct whiteListItem {
bool status;
string data;
}
// white list status
mapping (address => whiteListItem) public whitelist;
/**
* @dev Set a white list address
* @param to the address to be set
* @param status the whitelisting status (true for yes, false for no)
* @param data a string with data about the whitelisted address
*/
function setWhitelist(address to, bool status, string memory data) public onlyWhitelister returns(bool){
whitelist[to] = whiteListItem(status, data);
emit WhitelistUpdate(to, status, data);
return true;
}
/**
* @dev Get the status of the whitelist
* @param _address the address to be check
*/
function getWhitelistStatus(address _address) public view returns(bool){
return whitelist[_address].status;
}
/**
* @dev Get the data of and address in the whitelist
* @param _address the address to retrieve the data from
*/
function getWhitelistData(address _address) public view returns(string memory){
return whitelist[_address].data;
}
/**
* @dev Determine if sender and receiver are whitelisted, return true if both accounts are whitelisted
* @param from The address sending tokens.
* @param to The address receiving tokens.
*/
function checkWhitelists(address from, address to) external view returns (bool) {
return whitelist[from].status && whitelist[to].status;
}
}
| * @dev Get the status of the whitelist @param _address the address to be check/ | function getWhitelistStatus(address _address) public view returns(bool){
return whitelist[_address].status;
}
| 6,395,728 | [
1,
967,
326,
1267,
434,
326,
10734,
225,
389,
2867,
326,
1758,
358,
506,
866,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
336,
18927,
1482,
12,
2867,
389,
2867,
13,
1071,
1476,
1135,
12,
6430,
15329,
203,
3639,
327,
10734,
63,
67,
2867,
8009,
2327,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x587e276dc7f2c97d986e8adf9b82d3f14d6cd8d2
//Contract name: Fysical
//Balance: 0 Ether
//Verification Date: 2/28/2018
//Transacion Count: 6915
// CODE STARTS HERE
pragma solidity ^0.4.13;
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);
}
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;
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract 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];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Fysical is StandardToken {
using SafeMath for uint256;
// To increase consistency and reduce the opportunity for human error, the '*sById' mappings, '*Count' values,
// 'get*ById' function declarations/implementations, and 'create*' function declarations/implementations have been
// programmatically-generated based on the each struct's name, member types/names, and the comments sharing a line
// with a member.
//
// This programmatic generation builds 'require' function calls based on the following rules:
// - 'string' values must have length > 0
// - 'bytes' and uint256[] values may have any length
// - 'uint256' values representing a quantity must be > 0 (identifiers and Ethereum block numbers do not represent a quantity)
//
// The implementation of 'createProposal' contains one operation not found in the other programmatically-generated
// 'create*' functions, a call to 'transferTokensToEscrow'.
//
// None of the other members or functions have been programmatically generated.
// See https://en.wikipedia.org/wiki/Uniform_Resource_Identifier.
// The risk of preventing support for a future addition to the URI syntax outweighs the benefit of validating URI
// values within this immutable smart contract, so readers of Uri values should expect values that do not conform
// to the formal syntax of a URI.
struct Uri {
string value;
}
// A set of URIs may describe multiple methods to access a particular resource.
struct UriSet {
uint256[] uniqueUriIdsSortedAscending; // each value must be key in 'urisById'
}
// See https://en.wikipedia.org/wiki/Checksum#Algorithms. The description of the algorithm referred to by each URI
// in the set should give a reader enough information to interpret the 'value' member of a 'Checksum' object
// referring to this algorithm object.
struct ChecksumAlgorithm {
uint256 descriptionUriSetId; // must be key in 'uriSetsById'
}
// See https://en.wikipedia.org/wiki/Checksum. The 'resourceByteCount' indicates the number of bytes contained in
// the resource. Though this is not strictly part of most common Checksum algorithms, its validation may also be
// useful. The 'value' field should contain the expected output of passing the resource content to the checksum
// algorithm.
struct Checksum {
uint256 algorithmId; // must be key in 'checksumAlgorithmsById'
uint256 resourceByteCount;
bytes value;
}
// See https://en.wikipedia.org/wiki/Encryption. The description of the algorithm referred to by each URI
// in the set should give a reader enough information to access the content of an encrypted resource. The algorithm
// may be a symmetric encryption algorithm or an asymmetric encryption algorithm
struct EncryptionAlgorithm {
uint256 descriptionUriSetId; // must be key in 'uriSetsById'
}
// For each resource, an Ethereum account may describe a checksum for the encrypted content of a resource and a
// checksum for the decrypted content of a resource. When the resource is encrypted with a null encryption
// algorithm, the resource is effectively unencrypted, so these two checksums should be identical
// (See https://en.wikipedia.org/wiki/Null_encryption).
struct ChecksumPair {
uint256 encryptedChecksumId; // must be key in 'checksumsById'
uint256 decryptedChecksumId; // must be key in 'checksumsById'
}
// A 'Resource' is content accessible with each URI referenced in the 'uriSetId'. This content should be
// encrypted with the algorithm described by the 'EncryptionAlgorithm' referenced in 'encryptionAlgorithmId'. Each
// resource referenced in 'metaResourceSetId' should describe the decrypted content in some way.
//
// For example, if the decrypted content conforms to a Protocol Buffers schema, the corresponding proto definition
// file should be included in the meta-resources. Likewise, that proto definition resource should refer to a
// resource like https://en.wikipedia.org/wiki/Protocol_Buffers among its meta-resources.
struct Resource {
uint256 uriSetId; // must be key in 'uriSetsById'
uint256 encryptionAlgorithmId; // must be key in 'encryptionAlgorithmsById'
uint256 metaResourceSetId; // must be key in 'resourceSetsById'
}
// See https://en.wikipedia.org/wiki/Public-key_cryptography. This value should be the public key used in an
// asymmetric encryption operation. It should be useful for encrypting an resource destined for the holder of the
// corresponding private key or for decrypting a resource encrypted with the corresponding private key.
struct PublicKey {
bytes value;
}
// A 'ResourceSet' groups together resources that may be part of a trade proposal involving Fysical tokens. The
// creator of a 'ResourceSet' must include a public key for use in the encryption operations of creating and
// accepting a trade proposal. The creator must also specify the encryption algorithm a proposal creator should
// use along with this resource set creator's public key. Just as a single resource may have meta-resources
// describing the content of a resource, a 'ResourceSet' may have resources describing the whole resource set.
//
// Creators should be careful to not include so many resources that an Ethereum transaction to accept a proposal
// might run out of gas while storing the corresponding encrypted decryption keys.
//
// While developing reasonable filters for un-useful data in this collection, developers should choose a practical
// maximum depth of traversal through the meta-resources, since an infinite loop is possible.
struct ResourceSet {
address creator;
uint256 creatorPublicKeyId; // must be key in 'publicKeysById'
uint256 proposalEncryptionAlgorithmId; // must be key in 'encryptionAlgorithmsById'
uint256[] uniqueResourceIdsSortedAscending; // each value must be key in 'resourcesById'
uint256 metaResourceSetId; // must be key in 'resourceSetsById'
}
// The creator of a trade proposal may include arbitrary content to be considered part of the agreement the
// resource set is accepting. This may be useful for license agreements to be enforced within a jurisdiction
// governing the trade partners. The content available through each URI in the set should be encrypted first with
// the public key of a resource set's creator and then with the private key of a proposal's creator.
struct Agreement {
uint256 uriSetId; // must be key in 'uriSetsById'
uint256 checksumPairId; // must be key in 'checksumPairsById'
}
// Many agreements may be grouped together in an 'AgreementSet'
struct AgreementSet {
uint256[] uniqueAgreementIdsSortedAscending; // each value must be key in 'agreementsById'
}
// A 'TokenTransfer' describes a transfer of tokens to occur between two Ethereum accounts.
struct TokenTransfer {
address source;
address destination;
uint256 tokenCount;
}
// Many token transfers may be grouped together in a "TokenTransferSet'
struct TokenTransferSet {
uint256[] uniqueTokenTransferIdsSortedAscending; // each value must be key in 'tokenTransfersById'
}
// A 'Proposal' describes the conditions for the atomic exchange of Fysical tokens and a keys to decrypt resources
// in a resource set. The creator must specify the asymmetric encryption algorithm for use when accepting the
// proposal, along with this creator's public key. The creator may specify arbitrary agreements that should be
// considered a condition of the trade.
//
// During the execution of 'createProposal', the count of tokens specified in each token transfer will be transfered
// from the specified source account to the account with the Ethereum address of 0. When the proposal state changes
// to a final state, these tokens will be returned to the source accounts or tranfserred to the destination account.
//
// By including a 'minimumBlockNumberForWithdrawal' value later than the current Ethereum block, the proposal
// creator can give the resource set creator a rough sense of how long the proposal will remain certainly
// acceptable. This is particularly useful because the execution of an Ethereum transaction to accept a proposal
// exposes the encrypted decryption keys to the Ethereum network regardless of whether the transaction succeeds.
// Within the time frame that a proposal acceptance transaction will certainly succeed, the resource creator need
// not be concerned with the possibility that an acceptance transaction might execute after a proposal withdrawal
// submitted to the Ethereum network at approximately the same time.
struct Proposal {
uint256 minimumBlockNumberForWithdrawal;
address creator;
uint256 creatorPublicKeyId; // must be key in 'publicKeysById'
uint256 acceptanceEncryptionAlgorithmId; // must be key in 'encryptionAlgorithmsById'
uint256 resourceSetId; // must be key in 'resourceSetsById'
uint256 agreementSetId; // must be key in 'agreementSetsById'
uint256 tokenTransferSetId; // must be key in 'tokenTransferSetsById'
}
// When created, the proposal is in the 'Pending' state. All other states are final states, so a proposal may change
// state exactly one time based on a call to 'withdrawProposal', 'acceptProposal', or 'rejectProposal'.
enum ProposalState {
Pending,
WithdrawnByCreator,
RejectedByResourceSetCreator,
AcceptedByResourceSetCreator
}
// solium would warn "Constant name 'name' doesn't follow the UPPER_CASE notation", but this public constant is
// recommended by https://theethereum.wiki/w/index.php/ERC20_Token_Standard, so we'll disable warnings for the line.
//
/* solium-disable-next-line */
string public constant name = "Fysical";
// solium would warn "Constant name 'symbol' doesn't follow the UPPER_CASE notation", but this public constant is
// recommended by https://theethereum.wiki/w/index.php/ERC20_Token_Standard, so we'll disable warnings for the line.
//
/* solium-disable-next-line */
string public constant symbol = "FYS";
// solium would warn "Constant name 'decimals' doesn't follow the UPPER_CASE notation", but this public constant is
// recommended by https://theethereum.wiki/w/index.php/ERC20_Token_Standard, so we'll disable warnings for the line.
//
/* solium-disable-next-line */
uint8 public constant decimals = 9;
uint256 public constant ONE_BILLION = 1000000000;
uint256 public constant ONE_QUINTILLION = 1000000000000000000;
// See https://en.wikipedia.org/wiki/9,223,372,036,854,775,807
uint256 public constant MAXIMUM_64_BIT_SIGNED_INTEGER_VALUE = 9223372036854775807;
uint256 public constant EMPTY_PUBLIC_KEY_ID = 0;
uint256 public constant NULL_ENCRYPTION_ALGORITHM_DESCRIPTION_URI_ID = 0;
uint256 public constant NULL_ENCRYPTION_ALGORITHM_DESCRIPTION_URI_SET_ID = 0;
uint256 public constant NULL_ENCRYPTION_ALGORITHM_ID = 0;
uint256 public constant EMPTY_RESOURCE_SET_ID = 0;
mapping(uint256 => Uri) internal urisById;
uint256 internal uriCount = 0;
mapping(uint256 => UriSet) internal uriSetsById;
uint256 internal uriSetCount = 0;
mapping(uint256 => ChecksumAlgorithm) internal checksumAlgorithmsById;
uint256 internal checksumAlgorithmCount = 0;
mapping(uint256 => Checksum) internal checksumsById;
uint256 internal checksumCount = 0;
mapping(uint256 => EncryptionAlgorithm) internal encryptionAlgorithmsById;
uint256 internal encryptionAlgorithmCount = 0;
mapping(uint256 => ChecksumPair) internal checksumPairsById;
uint256 internal checksumPairCount = 0;
mapping(uint256 => Resource) internal resourcesById;
uint256 internal resourceCount = 0;
mapping(uint256 => PublicKey) internal publicKeysById;
uint256 internal publicKeyCount = 0;
mapping(uint256 => ResourceSet) internal resourceSetsById;
uint256 internal resourceSetCount = 0;
mapping(uint256 => Agreement) internal agreementsById;
uint256 internal agreementCount = 0;
mapping(uint256 => AgreementSet) internal agreementSetsById;
uint256 internal agreementSetCount = 0;
mapping(uint256 => TokenTransfer) internal tokenTransfersById;
uint256 internal tokenTransferCount = 0;
mapping(uint256 => TokenTransferSet) internal tokenTransferSetsById;
uint256 internal tokenTransferSetCount = 0;
mapping(uint256 => Proposal) internal proposalsById;
uint256 internal proposalCount = 0;
mapping(uint256 => ProposalState) internal statesByProposalId;
mapping(uint256 => mapping(uint256 => bytes)) internal encryptedDecryptionKeysByProposalIdAndResourceId;
mapping(address => mapping(uint256 => bool)) internal checksumPairAssignmentsByCreatorAndResourceId;
mapping(address => mapping(uint256 => uint256)) internal checksumPairIdsByCreatorAndResourceId;
function Fysical() public {
assert(ProposalState(0) == ProposalState.Pending);
// The total number of Fysical tokens is intended to be one billion, with the ability to express values with
// nine decimals places of precision. The token values passed in ERC20 functions and operations involving
// TokenTransfer operations must be counts of nano-Fysical tokens (one billionth of one Fysical token).
//
// See the initialization of the total supply in https://theethereum.wiki/w/index.php/ERC20_Token_Standard.
assert(0 < ONE_BILLION);
assert(0 < ONE_QUINTILLION);
assert(MAXIMUM_64_BIT_SIGNED_INTEGER_VALUE > ONE_BILLION);
assert(MAXIMUM_64_BIT_SIGNED_INTEGER_VALUE > ONE_QUINTILLION);
assert(ONE_BILLION == uint256(10)**decimals);
assert(ONE_QUINTILLION == ONE_BILLION.mul(ONE_BILLION));
totalSupply_ = ONE_QUINTILLION;
balances[msg.sender] = totalSupply_;
// From "https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1" on 2018-02-08 (commit cea1db05a3444870132ec3cb7dd78a244cba1805):
// "A token contract which creates new tokens SHOULD trigger a Transfer event with the _from address set to 0x0 when tokens are created."
Transfer(0x0, msg.sender, balances[msg.sender]);
// This mimics the behavior of the 'createPublicKey' external function.
assert(EMPTY_PUBLIC_KEY_ID == publicKeyCount);
publicKeysById[EMPTY_PUBLIC_KEY_ID] = PublicKey(new bytes(0));
publicKeyCount = publicKeyCount.add(1);
assert(1 == publicKeyCount);
// This mimics the behavior of the 'createUri' external function.
assert(NULL_ENCRYPTION_ALGORITHM_DESCRIPTION_URI_ID == uriCount);
urisById[NULL_ENCRYPTION_ALGORITHM_DESCRIPTION_URI_ID] = Uri("https://en.wikipedia.org/wiki/Null_encryption");
uriCount = uriCount.add(1);
assert(1 == uriCount);
// This mimics the behavior of the 'createUriSet' external function.
assert(NULL_ENCRYPTION_ALGORITHM_DESCRIPTION_URI_SET_ID == uriSetCount);
uint256[] memory uniqueIdsSortedAscending = new uint256[](1);
uniqueIdsSortedAscending[0] = NULL_ENCRYPTION_ALGORITHM_DESCRIPTION_URI_ID;
validateIdSet(uniqueIdsSortedAscending, uriCount);
uriSetsById[NULL_ENCRYPTION_ALGORITHM_DESCRIPTION_URI_SET_ID] = UriSet(uniqueIdsSortedAscending);
uriSetCount = uriSetCount.add(1);
assert(1 == uriSetCount);
// This mimics the behavior of the 'createEncryptionAlgorithm' external function.
assert(NULL_ENCRYPTION_ALGORITHM_ID == encryptionAlgorithmCount);
encryptionAlgorithmsById[NULL_ENCRYPTION_ALGORITHM_ID] = EncryptionAlgorithm(NULL_ENCRYPTION_ALGORITHM_DESCRIPTION_URI_SET_ID);
encryptionAlgorithmCount = encryptionAlgorithmCount.add(1);
assert(1 == encryptionAlgorithmCount);
// This mimics the behavior of the 'createResourceSet' external function, but allows for a self-reference in
// the assignment of the 'metaResourceSetId' member, which the function would prohibit.
assert(EMPTY_RESOURCE_SET_ID == resourceSetCount);
resourceSetsById[EMPTY_RESOURCE_SET_ID] = ResourceSet(
msg.sender,
EMPTY_PUBLIC_KEY_ID,
NULL_ENCRYPTION_ALGORITHM_ID,
new uint256[](0),
EMPTY_RESOURCE_SET_ID
);
resourceSetCount = resourceSetCount.add(1);
assert(1 == resourceSetCount);
}
function getUriCount() external view returns (uint256) {
return uriCount;
}
function getUriById(uint256 id) external view returns (string) {
require(id < uriCount);
Uri memory object = urisById[id];
return object.value;
}
function getUriSetCount() external view returns (uint256) {
return uriSetCount;
}
function getUriSetById(uint256 id) external view returns (uint256[]) {
require(id < uriSetCount);
UriSet memory object = uriSetsById[id];
return object.uniqueUriIdsSortedAscending;
}
function getChecksumAlgorithmCount() external view returns (uint256) {
return checksumAlgorithmCount;
}
function getChecksumAlgorithmById(uint256 id) external view returns (uint256) {
require(id < checksumAlgorithmCount);
ChecksumAlgorithm memory object = checksumAlgorithmsById[id];
return object.descriptionUriSetId;
}
function getChecksumCount() external view returns (uint256) {
return checksumCount;
}
function getChecksumById(uint256 id) external view returns (uint256, uint256, bytes) {
require(id < checksumCount);
Checksum memory object = checksumsById[id];
return (object.algorithmId, object.resourceByteCount, object.value);
}
function getEncryptionAlgorithmCount() external view returns (uint256) {
return encryptionAlgorithmCount;
}
function getEncryptionAlgorithmById(uint256 id) external view returns (uint256) {
require(id < encryptionAlgorithmCount);
EncryptionAlgorithm memory object = encryptionAlgorithmsById[id];
return object.descriptionUriSetId;
}
function getChecksumPairCount() external view returns (uint256) {
return checksumPairCount;
}
function getChecksumPairById(uint256 id) external view returns (uint256, uint256) {
require(id < checksumPairCount);
ChecksumPair memory object = checksumPairsById[id];
return (object.encryptedChecksumId, object.decryptedChecksumId);
}
function getResourceCount() external view returns (uint256) {
return resourceCount;
}
function getResourceById(uint256 id) external view returns (uint256, uint256, uint256) {
require(id < resourceCount);
Resource memory object = resourcesById[id];
return (object.uriSetId, object.encryptionAlgorithmId, object.metaResourceSetId);
}
function getPublicKeyCount() external view returns (uint256) {
return publicKeyCount;
}
function getPublicKeyById(uint256 id) external view returns (bytes) {
require(id < publicKeyCount);
PublicKey memory object = publicKeysById[id];
return object.value;
}
function getResourceSetCount() external view returns (uint256) {
return resourceSetCount;
}
function getResourceSetById(uint256 id) external view returns (address, uint256, uint256, uint256[], uint256) {
require(id < resourceSetCount);
ResourceSet memory object = resourceSetsById[id];
return (object.creator, object.creatorPublicKeyId, object.proposalEncryptionAlgorithmId, object.uniqueResourceIdsSortedAscending, object.metaResourceSetId);
}
function getAgreementCount() external view returns (uint256) {
return agreementCount;
}
function getAgreementById(uint256 id) external view returns (uint256, uint256) {
require(id < agreementCount);
Agreement memory object = agreementsById[id];
return (object.uriSetId, object.checksumPairId);
}
function getAgreementSetCount() external view returns (uint256) {
return agreementSetCount;
}
function getAgreementSetById(uint256 id) external view returns (uint256[]) {
require(id < agreementSetCount);
AgreementSet memory object = agreementSetsById[id];
return object.uniqueAgreementIdsSortedAscending;
}
function getTokenTransferCount() external view returns (uint256) {
return tokenTransferCount;
}
function getTokenTransferById(uint256 id) external view returns (address, address, uint256) {
require(id < tokenTransferCount);
TokenTransfer memory object = tokenTransfersById[id];
return (object.source, object.destination, object.tokenCount);
}
function getTokenTransferSetCount() external view returns (uint256) {
return tokenTransferSetCount;
}
function getTokenTransferSetById(uint256 id) external view returns (uint256[]) {
require(id < tokenTransferSetCount);
TokenTransferSet memory object = tokenTransferSetsById[id];
return object.uniqueTokenTransferIdsSortedAscending;
}
function getProposalCount() external view returns (uint256) {
return proposalCount;
}
function getProposalById(uint256 id) external view returns (uint256, address, uint256, uint256, uint256, uint256, uint256) {
require(id < proposalCount);
Proposal memory object = proposalsById[id];
return (object.minimumBlockNumberForWithdrawal, object.creator, object.creatorPublicKeyId, object.acceptanceEncryptionAlgorithmId, object.resourceSetId, object.agreementSetId, object.tokenTransferSetId);
}
function getStateByProposalId(uint256 proposalId) external view returns (ProposalState) {
require(proposalId < proposalCount);
return statesByProposalId[proposalId];
}
// Check to see if an Ethereum account has assigned a checksum for a particular resource.
function hasAddressAssignedResourceChecksumPair(address address_, uint256 resourceId) external view returns (bool) {
require(resourceId < resourceCount);
return checksumPairAssignmentsByCreatorAndResourceId[address_][resourceId];
}
// Retrieve the checksum assigned assigned to particular resource
function getChecksumPairIdByAssignerAndResourceId(address assigner, uint256 resourceId) external view returns (uint256) {
require(resourceId < resourceCount);
require(checksumPairAssignmentsByCreatorAndResourceId[assigner][resourceId]);
return checksumPairIdsByCreatorAndResourceId[assigner][resourceId];
}
// Retrieve the encrypted key to decrypt a resource referenced by an accepted proposal.
function getEncryptedResourceDecryptionKey(uint256 proposalId, uint256 resourceId) external view returns (bytes) {
require(proposalId < proposalCount);
require(ProposalState.AcceptedByResourceSetCreator == statesByProposalId[proposalId]);
require(resourceId < resourceCount);
uint256[] memory validResourceIds = resourceSetsById[proposalsById[proposalId].resourceSetId].uniqueResourceIdsSortedAscending;
require(0 < validResourceIds.length);
if (1 == validResourceIds.length) {
require(resourceId == validResourceIds[0]);
} else {
uint256 lowIndex = 0;
uint256 highIndex = validResourceIds.length.sub(1);
uint256 middleIndex = lowIndex.add(highIndex).div(2);
while (resourceId != validResourceIds[middleIndex]) {
require(lowIndex <= highIndex);
if (validResourceIds[middleIndex] < resourceId) {
lowIndex = middleIndex.add(1);
} else {
highIndex = middleIndex.sub(1);
}
middleIndex = lowIndex.add(highIndex).div(2);
}
}
return encryptedDecryptionKeysByProposalIdAndResourceId[proposalId][resourceId];
}
function createUri(
string value
) external returns (uint256)
{
require(0 < bytes(value).length);
uint256 id = uriCount;
uriCount = id.add(1);
urisById[id] = Uri(
value
);
return id;
}
function createUriSet(
uint256[] uniqueUriIdsSortedAscending
) external returns (uint256)
{
validateIdSet(uniqueUriIdsSortedAscending, uriCount);
uint256 id = uriSetCount;
uriSetCount = id.add(1);
uriSetsById[id] = UriSet(
uniqueUriIdsSortedAscending
);
return id;
}
function createChecksumAlgorithm(
uint256 descriptionUriSetId
) external returns (uint256)
{
require(descriptionUriSetId < uriSetCount);
uint256 id = checksumAlgorithmCount;
checksumAlgorithmCount = id.add(1);
checksumAlgorithmsById[id] = ChecksumAlgorithm(
descriptionUriSetId
);
return id;
}
function createChecksum(
uint256 algorithmId,
uint256 resourceByteCount,
bytes value
) external returns (uint256)
{
require(algorithmId < checksumAlgorithmCount);
require(0 < resourceByteCount);
uint256 id = checksumCount;
checksumCount = id.add(1);
checksumsById[id] = Checksum(
algorithmId,
resourceByteCount,
value
);
return id;
}
function createEncryptionAlgorithm(
uint256 descriptionUriSetId
) external returns (uint256)
{
require(descriptionUriSetId < uriSetCount);
uint256 id = encryptionAlgorithmCount;
encryptionAlgorithmCount = id.add(1);
encryptionAlgorithmsById[id] = EncryptionAlgorithm(
descriptionUriSetId
);
return id;
}
function createChecksumPair(
uint256 encryptedChecksumId,
uint256 decryptedChecksumId
) external returns (uint256)
{
require(encryptedChecksumId < checksumCount);
require(decryptedChecksumId < checksumCount);
uint256 id = checksumPairCount;
checksumPairCount = id.add(1);
checksumPairsById[id] = ChecksumPair(
encryptedChecksumId,
decryptedChecksumId
);
return id;
}
function createResource(
uint256 uriSetId,
uint256 encryptionAlgorithmId,
uint256 metaResourceSetId
) external returns (uint256)
{
require(uriSetId < uriSetCount);
require(encryptionAlgorithmId < encryptionAlgorithmCount);
require(metaResourceSetId < resourceSetCount);
uint256 id = resourceCount;
resourceCount = id.add(1);
resourcesById[id] = Resource(
uriSetId,
encryptionAlgorithmId,
metaResourceSetId
);
return id;
}
function createPublicKey(
bytes value
) external returns (uint256)
{
uint256 id = publicKeyCount;
publicKeyCount = id.add(1);
publicKeysById[id] = PublicKey(
value
);
return id;
}
function createResourceSet(
uint256 creatorPublicKeyId,
uint256 proposalEncryptionAlgorithmId,
uint256[] uniqueResourceIdsSortedAscending,
uint256 metaResourceSetId
) external returns (uint256)
{
require(creatorPublicKeyId < publicKeyCount);
require(proposalEncryptionAlgorithmId < encryptionAlgorithmCount);
validateIdSet(uniqueResourceIdsSortedAscending, resourceCount);
require(metaResourceSetId < resourceSetCount);
uint256 id = resourceSetCount;
resourceSetCount = id.add(1);
resourceSetsById[id] = ResourceSet(
msg.sender,
creatorPublicKeyId,
proposalEncryptionAlgorithmId,
uniqueResourceIdsSortedAscending,
metaResourceSetId
);
return id;
}
function createAgreement(
uint256 uriSetId,
uint256 checksumPairId
) external returns (uint256)
{
require(uriSetId < uriSetCount);
require(checksumPairId < checksumPairCount);
uint256 id = agreementCount;
agreementCount = id.add(1);
agreementsById[id] = Agreement(
uriSetId,
checksumPairId
);
return id;
}
function createAgreementSet(
uint256[] uniqueAgreementIdsSortedAscending
) external returns (uint256)
{
validateIdSet(uniqueAgreementIdsSortedAscending, agreementCount);
uint256 id = agreementSetCount;
agreementSetCount = id.add(1);
agreementSetsById[id] = AgreementSet(
uniqueAgreementIdsSortedAscending
);
return id;
}
function createTokenTransfer(
address source,
address destination,
uint256 tokenCount
) external returns (uint256)
{
require(address(0) != source);
require(address(0) != destination);
require(0 < tokenCount);
uint256 id = tokenTransferCount;
tokenTransferCount = id.add(1);
tokenTransfersById[id] = TokenTransfer(
source,
destination,
tokenCount
);
return id;
}
function createTokenTransferSet(
uint256[] uniqueTokenTransferIdsSortedAscending
) external returns (uint256)
{
validateIdSet(uniqueTokenTransferIdsSortedAscending, tokenTransferCount);
uint256 id = tokenTransferSetCount;
tokenTransferSetCount = id.add(1);
tokenTransferSetsById[id] = TokenTransferSet(
uniqueTokenTransferIdsSortedAscending
);
return id;
}
function createProposal(
uint256 minimumBlockNumberForWithdrawal,
uint256 creatorPublicKeyId,
uint256 acceptanceEncryptionAlgorithmId,
uint256 resourceSetId,
uint256 agreementSetId,
uint256 tokenTransferSetId
) external returns (uint256)
{
require(creatorPublicKeyId < publicKeyCount);
require(acceptanceEncryptionAlgorithmId < encryptionAlgorithmCount);
require(resourceSetId < resourceSetCount);
require(agreementSetId < agreementSetCount);
require(tokenTransferSetId < tokenTransferSetCount);
transferTokensToEscrow(msg.sender, tokenTransferSetId);
uint256 id = proposalCount;
proposalCount = id.add(1);
proposalsById[id] = Proposal(
minimumBlockNumberForWithdrawal,
msg.sender,
creatorPublicKeyId,
acceptanceEncryptionAlgorithmId,
resourceSetId,
agreementSetId,
tokenTransferSetId
);
return id;
}
// Each Ethereum account may assign a 'ChecksumPair' to a resource exactly once. This ensures that each claim that a
// checksum should match a resource is attached to a particular authority. This operation is not bound to the
// creation of the resource because the resource's creator may not know the checksum when creating the resource.
function assignResourceChecksumPair(
uint256 resourceId,
uint256 checksumPairId
) external
{
require(resourceId < resourceCount);
require(checksumPairId < checksumPairCount);
require(false == checksumPairAssignmentsByCreatorAndResourceId[msg.sender][resourceId]);
checksumPairIdsByCreatorAndResourceId[msg.sender][resourceId] = checksumPairId;
checksumPairAssignmentsByCreatorAndResourceId[msg.sender][resourceId] = true;
}
// This function moves a proposal to a final state of `WithdrawnByCreator' and returns tokens to the sources
// described by the proposal's transfers.
function withdrawProposal(
uint256 proposalId
) external
{
require(proposalId < proposalCount);
require(ProposalState.Pending == statesByProposalId[proposalId]);
Proposal memory proposal = proposalsById[proposalId];
require(msg.sender == proposal.creator);
require(block.number >= proposal.minimumBlockNumberForWithdrawal);
returnTokensFromEscrow(proposal.creator, proposal.tokenTransferSetId);
statesByProposalId[proposalId] = ProposalState.WithdrawnByCreator;
}
// This function moves a proposal to a final state of `RejectedByResourceSetCreator' and returns tokens to the sources
// described by the proposal's transfers.
function rejectProposal(
uint256 proposalId
) external
{
require(proposalId < proposalCount);
require(ProposalState.Pending == statesByProposalId[proposalId]);
Proposal memory proposal = proposalsById[proposalId];
require(msg.sender == resourceSetsById[proposal.resourceSetId].creator);
returnTokensFromEscrow(proposal.creator, proposal.tokenTransferSetId);
statesByProposalId[proposalId] = ProposalState.RejectedByResourceSetCreator;
}
// This function moves a proposal to a final state of `RejectedByResourceSetCreator' and sends tokens to the
// destinations described by the proposal's transfers.
//
// The caller should encrypt each decryption key corresponding
// to each resource in the proposal's resource set first with the public key of the proposal's creator and then with
// the private key assoicated with the public key referenced in the resource set. The caller should concatenate
// these encrypted values and pass the resulting byte array as 'concatenatedResourceDecryptionKeys'.
// The length of each encrypted decryption key should be provided in the 'concatenatedResourceDecryptionKeyLengths'.
// The index of each value in 'concatenatedResourceDecryptionKeyLengths' must correspond to an index in the resource
// set referenced by the proposal.
function acceptProposal(
uint256 proposalId,
bytes concatenatedResourceDecryptionKeys,
uint256[] concatenatedResourceDecryptionKeyLengths
) external
{
require(proposalId < proposalCount);
require(ProposalState.Pending == statesByProposalId[proposalId]);
Proposal memory proposal = proposalsById[proposalId];
require(msg.sender == resourceSetsById[proposal.resourceSetId].creator);
storeEncryptedDecryptionKeys(
proposalId,
concatenatedResourceDecryptionKeys,
concatenatedResourceDecryptionKeyLengths
);
transferTokensFromEscrow(proposal.tokenTransferSetId);
statesByProposalId[proposalId] = ProposalState.AcceptedByResourceSetCreator;
}
function validateIdSet(uint256[] uniqueIdsSortedAscending, uint256 idCount) private pure {
if (0 < uniqueIdsSortedAscending.length) {
uint256 id = uniqueIdsSortedAscending[0];
require(id < idCount);
uint256 previousId = id;
for (uint256 index = 1; index < uniqueIdsSortedAscending.length; index = index.add(1)) {
id = uniqueIdsSortedAscending[index];
require(id < idCount);
require(previousId < id);
previousId = id;
}
}
}
function transferTokensToEscrow(address proposalCreator, uint256 tokenTransferSetId) private {
assert(tokenTransferSetId < tokenTransferSetCount);
assert(address(0) != proposalCreator);
uint256[] memory tokenTransferIds = tokenTransferSetsById[tokenTransferSetId].uniqueTokenTransferIdsSortedAscending;
for (uint256 index = 0; index < tokenTransferIds.length; index = index.add(1)) {
uint256 tokenTransferId = tokenTransferIds[index];
assert(tokenTransferId < tokenTransferCount);
TokenTransfer memory tokenTransfer = tokenTransfersById[tokenTransferId];
assert(0 < tokenTransfer.tokenCount);
assert(address(0) != tokenTransfer.source);
assert(address(0) != tokenTransfer.destination);
require(tokenTransfer.tokenCount <= balances[tokenTransfer.source]);
if (tokenTransfer.source != proposalCreator) {
require(tokenTransfer.tokenCount <= allowed[tokenTransfer.source][proposalCreator]);
allowed[tokenTransfer.source][proposalCreator] = allowed[tokenTransfer.source][proposalCreator].sub(tokenTransfer.tokenCount);
}
balances[tokenTransfer.source] = balances[tokenTransfer.source].sub(tokenTransfer.tokenCount);
balances[address(0)] = balances[address(0)].add(tokenTransfer.tokenCount);
Transfer(tokenTransfer.source, address(0), tokenTransfer.tokenCount);
}
}
function returnTokensFromEscrow(address proposalCreator, uint256 tokenTransferSetId) private {
assert(tokenTransferSetId < tokenTransferSetCount);
assert(address(0) != proposalCreator);
uint256[] memory tokenTransferIds = tokenTransferSetsById[tokenTransferSetId].uniqueTokenTransferIdsSortedAscending;
for (uint256 index = 0; index < tokenTransferIds.length; index = index.add(1)) {
uint256 tokenTransferId = tokenTransferIds[index];
assert(tokenTransferId < tokenTransferCount);
TokenTransfer memory tokenTransfer = tokenTransfersById[tokenTransferId];
assert(0 < tokenTransfer.tokenCount);
assert(address(0) != tokenTransfer.source);
assert(address(0) != tokenTransfer.destination);
assert(tokenTransfer.tokenCount <= balances[address(0)]);
balances[tokenTransfer.source] = balances[tokenTransfer.source].add(tokenTransfer.tokenCount);
balances[address(0)] = balances[address(0)].sub(tokenTransfer.tokenCount);
Transfer(address(0), tokenTransfer.source, tokenTransfer.tokenCount);
}
}
function transferTokensFromEscrow(uint256 tokenTransferSetId) private {
assert(tokenTransferSetId < tokenTransferSetCount);
uint256[] memory tokenTransferIds = tokenTransferSetsById[tokenTransferSetId].uniqueTokenTransferIdsSortedAscending;
for (uint256 index = 0; index < tokenTransferIds.length; index = index.add(1)) {
uint256 tokenTransferId = tokenTransferIds[index];
assert(tokenTransferId < tokenTransferCount);
TokenTransfer memory tokenTransfer = tokenTransfersById[tokenTransferId];
assert(0 < tokenTransfer.tokenCount);
assert(address(0) != tokenTransfer.source);
assert(address(0) != tokenTransfer.destination);
balances[address(0)] = balances[address(0)].sub(tokenTransfer.tokenCount);
balances[tokenTransfer.destination] = balances[tokenTransfer.destination].add(tokenTransfer.tokenCount);
Transfer(address(0), tokenTransfer.destination, tokenTransfer.tokenCount);
}
}
function storeEncryptedDecryptionKeys(
uint256 proposalId,
bytes concatenatedEncryptedResourceDecryptionKeys,
uint256[] encryptedResourceDecryptionKeyLengths
) private
{
assert(proposalId < proposalCount);
uint256 resourceSetId = proposalsById[proposalId].resourceSetId;
assert(resourceSetId < resourceSetCount);
ResourceSet memory resourceSet = resourceSetsById[resourceSetId];
require(resourceSet.uniqueResourceIdsSortedAscending.length == encryptedResourceDecryptionKeyLengths.length);
uint256 concatenatedEncryptedResourceDecryptionKeysIndex = 0;
for (uint256 resourceIndex = 0; resourceIndex < encryptedResourceDecryptionKeyLengths.length; resourceIndex = resourceIndex.add(1)) {
bytes memory encryptedResourceDecryptionKey = new bytes(encryptedResourceDecryptionKeyLengths[resourceIndex]);
require(0 < encryptedResourceDecryptionKey.length);
for (uint256 encryptedResourceDecryptionKeyIndex = 0; encryptedResourceDecryptionKeyIndex < encryptedResourceDecryptionKey.length; encryptedResourceDecryptionKeyIndex = encryptedResourceDecryptionKeyIndex.add(1)) {
require(concatenatedEncryptedResourceDecryptionKeysIndex < concatenatedEncryptedResourceDecryptionKeys.length);
encryptedResourceDecryptionKey[encryptedResourceDecryptionKeyIndex] = concatenatedEncryptedResourceDecryptionKeys[concatenatedEncryptedResourceDecryptionKeysIndex];
concatenatedEncryptedResourceDecryptionKeysIndex = concatenatedEncryptedResourceDecryptionKeysIndex.add(1);
}
uint256 resourceId = resourceSet.uniqueResourceIdsSortedAscending[resourceIndex];
assert(resourceId < resourceCount);
encryptedDecryptionKeysByProposalIdAndResourceId[proposalId][resourceId] = encryptedResourceDecryptionKey;
}
require(concatenatedEncryptedResourceDecryptionKeysIndex == concatenatedEncryptedResourceDecryptionKeys.length);
}
}
| Many token transfers may be grouped together in a "TokenTransferSet' | struct TokenTransferSet {
}
| 14,083,345 | [
1,
5594,
1147,
29375,
2026,
506,
10303,
9475,
316,
279,
315,
1345,
5912,
694,
11,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1958,
3155,
5912,
694,
288,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-18
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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;
}
}
/**
* @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);
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
interface I$LOBE is IERC20, IERC20Metadata {
function mint(address to, uint256 amount) external;
}
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);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @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 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 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;
}
}
contract NoBrainerStaking is Ownable, IERC721Receiver, ReentrancyGuard {
using SafeMath for uint256;
I$LOBE public rewardsTokenContract; // interface for $LOBE contract
IERC721 public stakeNFTContract; // interface for NoBrainer
uint256 public startTimestamp; // staking start timestamp
mapping(address=>uint256) public lastUpdateTimestamp; // last update timestamp for an address
uint256 public rate = 100 ether; // staking reward rate per day 100 * 10 ** 18
mapping(address=>uint256) public NFTbalanceForAddress; // NoBrainer balance for an address
mapping(address=>uint256) private claimableForAddress; // accumulated claimable balance before lastUpdateTmestap for an address
mapping(uint256=>address) public NFTtokenOwnerForId; // NoBrainer owner address for tokenId already staked
mapping(address=>uint256[]) public NFTtokenIdsStakedForAddress; // get list of staked tokenId list for an address
uint256 public totalNFTstaked; // total NoBrainer staked
uint256 public totalRewardClaimed; // total reward claimed (mint from $LOBE)
mapping(address=>uint256) public totalRewardClaimedForAddress; // total reward claimed for an address (mint from $LOBE)
// modifier for check if staking is started
modifier hasStarted() {
require(startTimestamp != 0, "NftStaking: staking not started");
_;
}
modifier hasNotStarted() {
require(startTimestamp == 0, "NftStaking: staking has started");
_;
}
event Started();
event NftStaked(address staker, uint256 tokenId);
event NftUnstaked(address staker, uint256 tokenId);
event RewardsClaimed(address staker, uint256 amount);
constructor (address nftContract, address rewardContract) {
stakeNFTContract = IERC721(nftContract);
rewardsTokenContract = I$LOBE(rewardContract);
}
// start staking
function start() public onlyOwner hasNotStarted {
startTimestamp = block.timestamp;
emit Started();
}
// in case for update Nobrainer or $LOBE address
function updateContractAddress(address nftContract, address rewardContract) public onlyOwner {
stakeNFTContract = IERC721(nftContract);
rewardsTokenContract = I$LOBE(rewardContract);
}
// update staking reward rate
function updateRate (uint256 _rate) public onlyOwner {
rate = _rate;
}
// important!!! in case NoBrainer recieved to staking contract for stake, user must send it as safetransferfrom to call this function.
function onERC721Received(
address ,
address from,
uint256 tokenId,
bytes calldata
) external override returns (bytes4){
_stakeNFT(tokenId, from);
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}
// get total claimable amount, updates everytime calling this function
function getClaimableAmount(address account) public view returns (uint256) {
return claimableForAddress[account] + ((block.timestamp - lastUpdateTimestamp[account]).mul(NFTbalanceForAddress[account]).mul(rate).div(1 days));
}
// list NFT ids staked by address
function listNFTStaked(address addr) public view returns (uint256 [] memory) {
return NFTtokenIdsStakedForAddress[addr];
}
// stake NFT
function _stakeNFT(uint256 id, address from) internal hasStarted {
require(address(stakeNFTContract) == msg.sender, "NftStaking: not correct NFT staked!");
claimableForAddress[from] = getClaimableAmount(from);
NFTbalanceForAddress[from] = NFTbalanceForAddress[from].add(1);
totalNFTstaked = totalNFTstaked.add(1);
lastUpdateTimestamp[from] = block.timestamp;
NFTtokenOwnerForId[id] = from;
NFTtokenIdsStakedForAddress[from].push(id);
emit NftStaked(from, id);
}
// list NFT by address
function listNFT(address addr) public view returns (uint256 [] memory) {
uint256 tokenCount = stakeNFTContract.balanceOf(addr);
uint256[] memory tokensId;
if (tokenCount == 0) {
return new uint256[](0);
}
else {
tokensId = new uint256[](tokenCount);
for(uint256 i = 0; i < tokenCount; i++){
tokensId[i] = stakeNFTContract.tokenOfOwnerByIndex(addr, i);
}
}
return tokensId;
}
// batch stake NFT
function batchStakeNFT() external hasStarted {
uint256[] memory tokensId = listNFT(msg.sender);
for (uint256 i=0; i < tokensId.length; i ++){
stakeNFTContract.safeTransferFrom(msg.sender, address(this), tokensId[i]);
}
}
// unstake NFT, transfer back nft to original owner
function unstakeNft(uint256 id) public hasStarted {
require(NFTtokenOwnerForId[id] == msg.sender, "NftStaking: token not staked or incorrect token owner!");
NFTtokenOwnerForId[id] = address(0);
claimableForAddress[msg.sender] = getClaimableAmount(msg.sender);
NFTbalanceForAddress[msg.sender] = NFTbalanceForAddress[msg.sender].sub(1);
totalNFTstaked = totalNFTstaked.sub(1);
lastUpdateTimestamp[msg.sender] = block.timestamp;
for (uint i = 0; i < NFTtokenIdsStakedForAddress[msg.sender].length; i ++){
if (NFTtokenIdsStakedForAddress[msg.sender][i] == id){
NFTtokenIdsStakedForAddress[msg.sender][i] = NFTtokenIdsStakedForAddress[msg.sender][NFTtokenIdsStakedForAddress[msg.sender].length - 1];
break;
}
}
NFTtokenIdsStakedForAddress[msg.sender].pop();
try stakeNFTContract.safeTransferFrom(address(this), msg.sender, id) {} catch {
stakeNFTContract.transferFrom(address(this), msg.sender, id);
}
emit NftUnstaked(msg.sender, id);
}
// batch unstake all NFT for msg.sender
function unstakeAllNFTForAddress() external hasStarted {
require(NFTtokenIdsStakedForAddress[msg.sender].length > 0, "NftStaing: Caller doesn't have any staked token!");
uint256 count = NFTtokenIdsStakedForAddress[msg.sender].length;
for(uint i = 0; i < count; i ++){
unstakeNft(NFTtokenIdsStakedForAddress[msg.sender][0]);
}
}
// claim reward for stake holers
function claimReward() external hasStarted {
uint256 claimAmount = getClaimableAmount(msg.sender);
require(claimAmount > 0, "NftStaking: no claimable balance!");
claimableForAddress[msg.sender] = 0;
lastUpdateTimestamp[msg.sender] = block.timestamp;
rewardsTokenContract.mint(msg.sender, claimAmount);
totalRewardClaimed = totalRewardClaimed.add(claimAmount);
totalRewardClaimedForAddress[msg.sender] = totalRewardClaimedForAddress[msg.sender].add(claimAmount);
emit RewardsClaimed(msg.sender, claimAmount);
}
} | last update timestamp for an address
| mapping(address=>uint256) public lastUpdateTimestamp; | 2,014,168 | [
1,
2722,
1089,
2858,
364,
392,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
9207,
11890,
5034,
13,
1071,
1142,
1891,
4921,
31,
377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {Ownable} from "openzeppelin/contracts/access/Ownable.sol";
import {ConfigContract} from "./ConfigContract.sol";
import {BatcherContract, BatchConfig, TransactionType} from "./BatcherContract.sol";
import {DepositContract} from "./DepositContract.sol";
struct CipherExecutionReceipt {
bool executed;
address executor;
uint64 halfStep;
bytes32 cipherBatchHash;
bytes32 batchHash;
}
/// @title A contract that serves as the entry point of batch execution
/// @dev Batch execution is carried out in two separate steps: Execution of the encrypted portion,
/// followed by execution of the plaintext portion. Thus, progress is counted in half steps (0
/// and 1 for batch 0, 2 and 3 for batch 1, and so on).
contract ExecutorContract is Ownable {
/// @notice The event emitted after a batch execution half step has been carried out.
/// @param numExecutionHalfSteps The total number of finished execution half steps, including
/// the one responsible for emitting the event.
/// @param batchHash The hash of the executed batch (consisting of plaintext transactions).
event BatchExecuted(uint64 numExecutionHalfSteps, bytes32 batchHash);
/// @notice The event emitted after execution of the cipher portion of a batch has been skipped.
/// @param numExecutionHalfSteps The total number of finished execution half steps, including
/// this one.
event CipherExecutionSkipped(uint64 numExecutionHalfSteps);
event TransactionFailed(uint64 txIndex, bytes32 txHash, bytes data);
ConfigContract public configContract;
BatcherContract public batcherContract;
DepositContract public depositContract;
uint64 public numExecutionHalfSteps;
mapping(uint64 => CipherExecutionReceipt) public cipherExecutionReceipts;
constructor(
ConfigContract configContractAddress,
BatcherContract batcherContractAddress,
DepositContract depositContractAddress
) Ownable() {
configContract = configContractAddress;
batcherContract = batcherContractAddress;
depositContract = depositContractAddress;
}
/// @notice Set the half step for accelerated recovery in case execution was neglected for some time.
/// @notice This function can only be called by the owner and only if the execution timeout has passed.
/// @notice The new half step must be greater than the current one, but cannot be in the future.
/// @param newHalfSteps The new value for numExecutionHalfSteps.
function setHalfSteps(uint64 newHalfSteps) public onlyOwner {
uint64 batchIndex = numExecutionHalfSteps / 2;
uint64 configIndex = configContract.configIndexForBatchIndex(
batchIndex
);
(, , uint64 executionTimeout) = configContract.batchBoundaryBlocks(
configIndex,
batchIndex
);
// check that execution timeout has passed
require(
block.number >= executionTimeout,
"ExecutorContract: execution timeout not passed yet"
);
// check that new half step is after current one
require(
newHalfSteps > numExecutionHalfSteps,
"ExecutorContract: new half steps not greater than current value"
);
// check that new half step is not in the future
uint64 newBatchIndex = newHalfSteps / 2;
uint64 newConfigIndex = configContract.configIndexForBatchIndex(
newBatchIndex
);
(, uint64 batchEndBlock, ) = configContract.batchBoundaryBlocks(
newConfigIndex,
newBatchIndex
);
require(
batchEndBlock < block.number,
"ExecutorContract: new half steps value is in the future"
);
numExecutionHalfSteps = newHalfSteps;
}
/// @notice Execute the cipher portion of a batch.
/// @param batchIndex The index of the batch
/// @param cipherBatchHash The hash of the batch (consisting of encrypted transactions)
/// @param transactions The sequence of (decrypted) transactions to execute.
/// @param keyperIndex The index of the keyper calling the function.
/// @notice Execution is only performed if `cipherBatchHash` matches the hash in the batcher
/// contract and the batch is active and completed.
function executeCipherBatch(
uint64 batchIndex,
bytes32 cipherBatchHash,
bytes[] calldata transactions,
uint64 keyperIndex
) public {
require(
numExecutionHalfSteps / 2 == batchIndex,
"ExecutorContract: unexpected batch index"
);
// Check that it's a cipher batch turn
require(
numExecutionHalfSteps % 2 == 0,
"ExecutorContract: unexpected half step"
);
uint64 configIndex = configContract.configIndexForBatchIndex(
batchIndex
);
address targetAddress = configContract.configTargetAddress(configIndex);
bytes4 targetFunctionSelector = configContract
.configTargetFunctionSelector(configIndex);
uint64 transactionGasLimit = configContract.configTransactionGasLimit(
configIndex
);
// Check that batching is active
require(
configContract.batchingActive(configIndex),
"ExecutorContract: config is inactive"
);
(, uint64 end, uint64 executionTimeout) = configContract
.batchBoundaryBlocks(configIndex, batchIndex);
// skip cipher execution if we reached the execution timeout.
if (block.number >= executionTimeout) {
numExecutionHalfSteps++;
emit CipherExecutionSkipped(numExecutionHalfSteps);
return;
}
require(
block.number >= end,
"ExecutorContract: batch is not closed yet"
);
// Check that caller is keyper
uint64 numKeypers = configContract.configNumKeypers(configIndex);
require(
keyperIndex < numKeypers,
"ExecutorContract: keyper index out of bounds"
);
address keyperAtIndex = configContract.configKeypers(
configIndex,
keyperIndex
);
require(
msg.sender == keyperAtIndex,
"ExecutorContract: sender is not specified keyper"
);
// Check that keyper is not slashed
require(
!depositContract.isSlashed(msg.sender),
"ExecutorContract: keyper is slashed"
);
// Check the cipher batch hash is correct
require(
cipherBatchHash ==
batcherContract.batchHashes(batchIndex, TransactionType.Cipher),
"ExecutorContract: incorrect cipher batch hash"
);
// If the cipher hash is zero, make sure the list of
// transactions is empty. Please note that we may have a
// non-zero cipher hash and still have an empty list of
// transactions, e.g. when a nondecryptable transaction has
// been added by a user
require(
(cipherBatchHash != bytes32(0) || transactions.length == 0),
"ExecutorContract: transactions should be empty if cipherBatchHash is zero"
);
// Execute the batch
bytes32 batchHash = executeTransactions(
targetAddress,
targetFunctionSelector,
transactionGasLimit,
transactions
);
cipherExecutionReceipts[
numExecutionHalfSteps
] = CipherExecutionReceipt({
executed: true,
executor: msg.sender,
halfStep: numExecutionHalfSteps,
cipherBatchHash: cipherBatchHash,
batchHash: batchHash
});
numExecutionHalfSteps++;
emit BatchExecuted(numExecutionHalfSteps, batchHash);
}
function skipEmptyOrTimedOutBatches(uint64 maxBatches) public {
uint64 halfSteps = numExecutionHalfSteps;
uint64 batchIndex = halfSteps / 2;
while (maxBatches > 0) {
if (halfSteps % 2 == 0) {
uint64 configIndex = configContract.configIndexForBatchIndex(
batchIndex
);
if (!configContract.batchingActive(configIndex)) {
break;
}
(, uint64 end, uint64 executionTimeout) = configContract
.batchBoundaryBlocks(configIndex, batchIndex);
if (block.number < end) {
// Users may still submit transactions
break;
}
if (
block.number < executionTimeout &&
batcherContract.batchHashes(
batchIndex,
TransactionType.Cipher
) !=
bytes32(0)
) {
break;
}
halfSteps += 1;
emit CipherExecutionSkipped(halfSteps);
}
if (
batcherContract.batchHashes(
batchIndex,
TransactionType.Plain
) != bytes32(0)
) {
break;
}
halfSteps += 1;
batchIndex += 1;
emit BatchExecuted(halfSteps, bytes32(0));
maxBatches -= 1;
}
numExecutionHalfSteps = halfSteps;
}
/// @notice Skip execution of the cipher portion of a batch.
/// @notice This is only possible if successful execution has not been carried out in time
/// (according to the execution timeout defined in the config)
function skipCipherExecution(uint64 batchIndex) external {
require(
numExecutionHalfSteps / 2 == batchIndex,
"ExecutorContract: unexpected batch index"
);
require(
numExecutionHalfSteps % 2 == 0,
"ExecutorContract: unexpected half step"
);
uint64 configIndex = configContract.configIndexForBatchIndex(
batchIndex
);
require(
configContract.batchingActive(configIndex),
"ExecutorContract: config is inactive"
);
(, , uint64 executionTimeout) = configContract.batchBoundaryBlocks(
configIndex,
batchIndex
);
require(
block.number >= executionTimeout,
"ExecutorContract: execution timeout not reached yet"
);
numExecutionHalfSteps++;
emit CipherExecutionSkipped(numExecutionHalfSteps);
}
/// @notice Execute the plaintext portion of a batch.
/// @param batchIndex The index of the batch
/// @param transactions The array of plaintext transactions in the batch.
/// @notice This is a trustless operation since `transactions` will be checked against the
/// (plaintext) batch hash from the batcher contract.
function executePlainBatch(uint64 batchIndex, bytes[] calldata transactions)
external
{
require(
numExecutionHalfSteps / 2 == batchIndex,
"ExecutorContract: unexpected batch index"
);
require(
numExecutionHalfSteps % 2 == 1,
"ExecutorContract: unexpected half step"
);
uint64 configIndex = configContract.configIndexForBatchIndex(
batchIndex
);
address targetAddress = configContract.configTargetAddress(configIndex);
bytes4 targetFunctionSelector = configContract
.configTargetFunctionSelector(configIndex);
uint64 transactionGasLimit = configContract.configTransactionGasLimit(
configIndex
);
// Since the cipher part of the batch has already been executed or skipped and the
// config cannot be changed anymore (since the batching period is over), the following
// checks remain true.
assert(configContract.batchingActive(configIndex));
(, uint64 end, ) = configContract.batchBoundaryBlocks(
configIndex,
batchIndex
);
assert(block.number >= end);
bytes32 batchHash = executeTransactions(
targetAddress,
targetFunctionSelector,
transactionGasLimit,
transactions
);
require(
batchHash ==
batcherContract.batchHashes(batchIndex, TransactionType.Plain),
"ExecutorContract: batch hash does not match"
);
numExecutionHalfSteps++;
emit BatchExecuted(numExecutionHalfSteps, batchHash);
}
function executeTransactions(
address targetAddress,
bytes4 targetFunctionSelector,
uint64 gasLimit,
bytes[] calldata transactions
) private returns (bytes32) {
bytes32 batchHash;
for (uint64 i = 0; i < transactions.length; i++) {
bytes memory callData = abi.encodeWithSelector(
targetFunctionSelector,
transactions[i]
);
// call target function, ignoring any errors
(bool success, bytes memory returnData) = targetAddress.call{
gas: gasLimit
}(callData);
if (!success) {
emit TransactionFailed({
txIndex: i,
txHash: keccak256(transactions[i]),
data: returnData
});
}
batchHash = keccak256(abi.encodePacked(transactions[i], batchHash));
}
return batchHash;
}
function getReceipt(uint64 halfStep)
public
view
returns (CipherExecutionReceipt memory)
{
return cipherExecutionReceipts[halfStep];
}
}
| Check that caller is keyper | uint64 numKeypers = configContract.configNumKeypers(configIndex);
| 12,849,436 | [
1,
1564,
716,
4894,
353,
498,
457,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
1105,
818,
653,
10422,
273,
642,
8924,
18,
1425,
2578,
653,
10422,
12,
1425,
1016,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.1;
pragma experimental ABIEncoderV2;
import "./interfaces/ICMCCore.sol";
import "./ReentrancyGuard.sol";
/// @title CMCCore
/// @author Connext <[email protected]>
/// @notice Contains logic pertaining to the participants of a channel,
/// including setting and retrieving the participants and the
/// mastercopy.
contract CMCCore is ReentrancyGuard, ICMCCore {
address private immutable mastercopyAddress;
address internal alice;
address internal bob;
/// @notice Set invalid participants to block the mastercopy from being used directly
/// Nonzero address also prevents the mastercopy from being setup
/// Only setting alice is sufficient, setting bob too wouldn't change anything
constructor() {
mastercopyAddress = address(this);
}
// Prevents us from calling methods directly from the mastercopy contract
modifier onlyViaProxy {
require(
address(this) != mastercopyAddress,
"Mastercopy: ONLY_VIA_PROXY"
);
_;
}
/// @notice Contract constructor for Proxied copies
/// @param _alice: Address representing user with function deposit
/// @param _bob: Address representing user with multisig deposit
function setup(address _alice, address _bob)
external
override
onlyViaProxy
{
require(alice == address(0), "CMCCore: ALREADY_SETUP");
require(
_alice != address(0) && _bob != address(0),
"CMCCore: INVALID_PARTICIPANT"
);
require(_alice != _bob, "CMCCore: IDENTICAL_PARTICIPANTS");
ReentrancyGuard.setup();
alice = _alice;
bob = _bob;
}
/// @notice A getter function for the bob of the multisig
/// @return Bob's signer address
function getAlice()
external
view
override
onlyViaProxy
nonReentrantView
returns (address)
{
return alice;
}
/// @notice A getter function for the bob of the multisig
/// @return Alice's signer address
function getBob()
external
view
override
onlyViaProxy
nonReentrantView
returns (address)
{
return bob;
}
}
| @notice Contract constructor for Proxied copies @param _alice: Address representing user with function deposit @param _bob: Address representing user with multisig deposit | function setup(address _alice, address _bob)
external
override
onlyViaProxy
{
require(alice == address(0), "CMCCore: ALREADY_SETUP");
require(
_alice != address(0) && _bob != address(0),
"CMCCore: INVALID_PARTICIPANT"
);
require(_alice != _bob, "CMCCore: IDENTICAL_PARTICIPANTS");
ReentrancyGuard.setup();
alice = _alice;
bob = _bob;
}
| 1,830,954 | [
1,
8924,
3885,
364,
1186,
92,
2092,
13200,
225,
389,
287,
1812,
30,
5267,
5123,
729,
598,
445,
443,
1724,
225,
389,
70,
947,
30,
5267,
5123,
729,
598,
22945,
360,
443,
1724,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3875,
12,
2867,
389,
287,
1812,
16,
1758,
389,
70,
947,
13,
203,
3639,
3903,
203,
3639,
3849,
203,
3639,
1338,
21246,
3886,
203,
565,
288,
203,
3639,
2583,
12,
287,
1812,
422,
1758,
12,
20,
3631,
315,
9611,
39,
4670,
30,
7981,
20305,
67,
4043,
3079,
8863,
203,
3639,
2583,
12,
203,
5411,
389,
287,
1812,
480,
1758,
12,
20,
13,
597,
389,
70,
947,
480,
1758,
12,
20,
3631,
203,
5411,
315,
9611,
39,
4670,
30,
10071,
67,
15055,
2871,
2579,
6856,
6,
203,
3639,
11272,
203,
3639,
2583,
24899,
287,
1812,
480,
389,
70,
947,
16,
315,
9611,
39,
4670,
30,
19768,
10109,
67,
15055,
2871,
2579,
6856,
55,
8863,
203,
3639,
868,
8230,
12514,
16709,
18,
8401,
5621,
203,
3639,
524,
1812,
273,
389,
287,
1812,
31,
203,
3639,
800,
70,
273,
389,
70,
947,
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
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.6.4 <0.8.0;
pragma experimental ABIEncoderV2;
/// @title uint256 Logic Library
/// @author Tyler R. Drury - 19/2/2021, All Rights Reserved
/// @notice trivial library for logical or bitwise operations on uint256 not provided natively by Solidity.
library uint256Logic
{
uint256 public constant ZERO = 0x0;
//uint256 public constant MAX = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
function equal(
uint256 lhs,
uint256 rhs
)internal pure returns(
bool ret
){
assembly{
ret := eq(lhs, rhs)
}
}
function notEqual(
uint256 lhs,
uint256 rhs
)internal pure returns(
bool ret
){
assembly{
ret := not(eq(lhs, rhs))
}
}
function _and(
uint256 lhs,
uint256 rhs
)internal pure returns(
uint256 ret
){
assembly{
ret := and(lhs, rhs)
}
}
function _or(
uint256 lhs,
uint256 rhs
)internal pure returns(
uint256 ret
){
assembly{
ret := or(lhs, rhs)
}
}
function _xor(
uint256 lhs,
uint256 rhs
)internal pure returns(
uint256 ret
){
assembly{
ret := xor(lhs, rhs)
}
}
//function not(
//uint256 lhs
//)internal pure returns(
//uint256
//){
//assembly{
//ret := not(lhs)
//}
//}
function greaterThan(
uint256 lhs,
uint256 rhs
)internal pure returns(
bool ret
){
assembly{
ret := gt(lhs, rhs)
}
}
function greaterThanOrEqual(
uint256 lhs,
uint256 rhs
)internal pure returns(
bool ret
){
//return lhs >= rhs;
assembly{
ret := or(gt(lhs, rhs),eq(lhs,rhs))
}
}
function lessThan(
uint256 lhs,
uint256 rhs
)internal pure returns(
bool ret
){
assembly{
ret := lt(lhs, rhs)
}
}
function lessThanOrEqual(
uint256 lhs,
uint256 rhs
)internal pure returns(
bool ret
){
assembly{
ret := or(lt(lhs, rhs),eq(lhs,rhs))
}
}
/**
* Common convenience operations
*/
function isZero(
uint256 lhs
)internal pure returns(
bool
){
return equal(lhs, ZERO);
}
function greaterThanZero(
uint256 lhs
)internal pure returns(
bool
){
//note this is broken
//assembly{
// ret := not(iszero(lhs))
//}
return greaterThan(lhs, 0);
}
//function lessThanMax(
//uint256 lhs
//)internal pure returns(
//bool ret
//){
//return lessThan(lhs, 0xFF);
//uint256 MAX = type(uint256).max;
//assembly{
//ret := lt(lhs, MAX)
//}
//}
/// @dev require `lhs` is within the inclusive range between `min` and `max`
function inRange(
uint256 lhs,
uint256 min,
uint256 max
)public pure returns(
bool
){
require(max > min, 'min cannot be > max');
return greaterThanOrEqual(lhs, min) && lessThanOrEqual(lhs, max);
}
/// @dev require `lhs` is within the exclusive range between `min` and `max`
function inXRange(
uint256 lhs,
uint256 min,
uint256 max
)public pure returns(
bool
){
require(max > min, 'min cannot be > max');
return greaterThan(lhs, min) && lessThan(lhs, max);
}
} | note this is brokenassembly{ ret := not(iszero(lhs))} | function greaterThanZero(
uint256 lhs
)internal pure returns(
bool
){
return greaterThan(lhs, 0);
}
| 6,484,010 | [
1,
7652,
333,
353,
12933,
28050,
95,
565,
325,
519,
486,
12,
291,
7124,
12,
80,
4487,
3719,
97,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6802,
9516,
7170,
12,
203,
3639,
2254,
5034,
8499,
203,
565,
262,
7236,
16618,
1135,
12,
203,
3639,
1426,
203,
565,
262,
95,
203,
3639,
327,
6802,
9516,
12,
80,
4487,
16,
374,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.6;
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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;
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
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);
}
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;
}
}
contract PEPEChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of PEPEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accPEPEPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accPEPEPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. PEPEs to distribute per block.
uint256 lastRewardBlock; // Last block number that PEPEs distribution occurs.
uint256 accPEPEPerShare; // Accumulated PEPEs per share, times 1e12. See below.
}
// The PEPE TOKEN!
PEPEToken public pepe;
// Dev address.
address public devaddr;
// Block number when bonus PEPE period ends.
uint256 public bonusEndBlock;
// PEPE tokens created per block.
uint256 public pepePerBlock;
// Bonus muliplier for early pepe makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when PEPE mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
PEPEToken _pepe,
address _devaddr,
uint256 _pepePerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
pepe = _pepe;
devaddr = _devaddr;
pepePerBlock = _pepePerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock
? block.number
: startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accPEPEPerShare: 0
})
);
}
// Update the given pool's PEPE allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return
bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending PEPEs on frontend.
function pendingPEPE(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accPEPEPerShare = pool.accPEPEPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(
pool.lastRewardBlock,
block.number
);
uint256 pepeReward = multiplier
.mul(pepePerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
accPEPEPerShare = accPEPEPerShare.add(
pepeReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accPEPEPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 pepeReward = multiplier
.mul(pepePerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
pepe.mint(devaddr, pepeReward.div(25));
pepe.mint(address(this), pepeReward);
pool.accPEPEPerShare = pool.accPEPEPerShare.add(
pepeReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to PEPEChef for PEPE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.accPEPEPerShare)
.div(1e12)
.sub(user.rewardDebt);
safePEPETransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accPEPEPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from PEPEChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accPEPEPerShare).div(1e12).sub(
user.rewardDebt
);
safePEPETransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accPEPEPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe pepe transfer function, just in case if rounding error causes pool to not have enough PEPEs.
function safePEPETransfer(address _to, uint256 _amount) internal {
uint256 pepeBal = pepe.balanceOf(address(this));
if (_amount > pepeBal) {
pepe.transfer(_to, pepeBal);
} else {
pepe.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
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");
}
}
}
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;
}
}
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 { }
}
contract PEPEToken is ERC20("PEPEFinance", "PEPE"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (PEPEFrog).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
| @notice Creates `_amount` token to `_to`. Must only be called by the owner (PEPEFrog). | function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
| 7,467,566 | [
1,
2729,
1375,
67,
8949,
68,
1147,
358,
1375,
67,
869,
8338,
6753,
1338,
506,
2566,
635,
326,
3410,
261,
1423,
1423,
42,
303,
75,
2934,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
203,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
203,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
// Sources flattened with hardhat v2.8.4 https://hardhat.org
// File contracts/Uniswap_V2_TWAMM/core/interfaces/IUniswapV2FactoryV5.sol
interface IUniswapV2FactoryV5 {
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;
}
// File contracts/Uniswap_V2_TWAMM/core/interfaces/IUniswapV2PairPartialV5.sol
interface IUniswapV2PairPartialV5 {
// event Approval(address indexed owner, address indexed spender, uint value);
// event Transfer(address indexed from, address indexed to, uint value);
//
// function name() external pure returns (string memory);
// function symbol() external pure returns (string memory);
// function decimals() external pure returns (uint8);
// function totalSupply() external view returns (uint);
// function balanceOf(address owner) external view returns (uint);
// function allowance(address owner, address spender) external view returns (uint);
//
// function approve(address spender, uint value) external returns (bool);
// function transfer(address to, uint value) external returns (bool);
// function transferFrom(address from, address to, uint value) external returns (bool);
//
// function DOMAIN_SEPARATOR() external view returns (bytes32);
// function PERMIT_TYPEHASH() external pure returns (bytes32);
// function nonces(address owner) external view returns (uint);
//
// function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
// TWAMM
function longTermSwapFrom0To1(uint256 amount0In, uint256 numberOfTimeIntervals) external returns (uint256 orderId);
function longTermSwapFrom1To0(uint256 amount1In, uint256 numberOfTimeIntervals) external returns (uint256 orderId);
function cancelLongTermSwap(uint256 orderId) external;
function withdrawProceedsFromLongTermSwap(uint256 orderId) external returns (bool is_expired);
function executeVirtualOrders(uint256 blockTimestamp) external;
function orderTimeInterval() external returns (uint256);
function getTWAPHistoryLength() external view returns (uint);
function getTwammReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast, uint112 _twammReserve0, uint112 _twammReserve1);
function getReserveAfterTwamm(uint256 blockTimestamp) external view returns (uint112 _reserve0, uint112 _reserve1, uint256 lastVirtualOrderTimestamp, uint112 _twammReserve0, uint112 _twammReserve1);
function getNextOrderID() external view returns (uint256);
function getOrderIDsForUser(address user) external view returns (uint256[] memory);
function getOrderIDsForUserLength(address user) external view returns (uint256);
// function getDetailedOrdersForUser(address user, uint256 offset, uint256 limit) external view returns (LongTermOrdersLib.Order[] memory detailed_orders);
function twammUpToDate() external view returns (bool);
function getTwammState() external view returns (uint256 token0Rate, uint256 token1Rate, uint256 lastVirtualOrderTimestamp, uint256 orderTimeInterval_rtn, uint256 rewardFactorPool0, uint256 rewardFactorPool1);
function getTwammSalesRateEnding(uint256 _blockTimestamp) external view returns (uint256 orderPool0SalesRateEnding, uint256 orderPool1SalesRateEnding);
function getTwammRewardFactor(uint256 _blockTimestamp) external view returns (uint256 rewardFactorPool0AtTimestamp, uint256 rewardFactorPool1AtTimestamp);
function getTwammOrder(uint256 orderId) external view returns (uint256 id, uint256 expirationTimestamp, uint256 saleRate, address owner, address sellTokenAddr, address buyTokenAddr);
function getTwammOrderProceeds(uint256 orderId, uint256 blockTimestamp) external view returns (bool orderExpired, uint256 totalReward);
function togglePauseNewSwaps() external;
}
// File contracts/Uniswap_V2_TWAMM/core/interfaces/IUniswapV2ERC20V5.sol
interface IUniswapV2ERC20V5 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// File contracts/Uniswap_V2_TWAMM/core/UniV2TWAMMERC20.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================= UniV2TWAMMERC20 ==========================
// ====================================================================
// TWAMM ERC-20
// Inspired by https://www.paradigm.xyz/2021/07/twamm
// https://github.com/para-dave/twamm
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Rich Gee: https://github.com/zer0blockchain
// Dennis: https://github.com/denett
// Logic / Algorithm Ideas
// FrankieIsLost: https://github.com/FrankieIsLost
// Reviewer(s) / Contributor(s)
// Travis Moore: https://github.com/FortisFortuna
// Sam Kazemian: https://github.com/samkazemian
// Drake Evans: https://github.com/DrakeEvans
// Jack Corddry: https://github.com/corddry
// Justin Moore: https://github.com/0xJM
contract UniV2TWAMMERC20 is IUniswapV2ERC20V5 {
string public constant override name = 'FraxSwap V1';
string public constant override symbol = 'FS-V1';
uint8 public constant override decimals = 18;
uint public override totalSupply;
mapping(address => uint) public override balanceOf;
mapping(address => mapping(address => uint)) public override allowance;
bytes32 public override DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public override nonces;
constructor() public {
uint chainId = block.chainid;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply + value;
balanceOf[to] = balanceOf[to] + value;
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from] - value;
totalSupply = totalSupply - value;
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from] - value;
balanceOf[to] = balanceOf[to] + value;
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external override returns (bool) {
if (allowance[from][msg.sender] != type(uint).max) {
allowance[from][msg.sender] = allowance[from][msg.sender] - value;
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override {
require(deadline >= block.timestamp); // EXPIRED
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner); // INVALID_SIGNATURE
_approve(owner, spender, value);
}
}
// File contracts/Uniswap_V2_TWAMM/core/libraries/Math.sol
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File contracts/Uniswap_V2_TWAMM/core/libraries/UQ112x112.sol
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// File contracts/Uniswap_V2_TWAMM/core/interfaces/IERC20V5.sol
interface IERC20V5 {
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);
}
// File contracts/Uniswap_V2_TWAMM/core/interfaces/IUniswapV2CalleeV5.sol
interface IUniswapV2CalleeV5 {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
// File contracts/Uniswap_V2_TWAMM/libraries/TransferHelper.sol
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// File contracts/Uniswap_V2_TWAMM/twamm/ExecVirtualOrders.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ======================= ExecVirtualOrdersLib =======================
// ====================================================================
// TWAMM logic for executing the virtual orders
// Inspired by https://www.paradigm.xyz/2021/07/twamm
// https://github.com/para-dave/twamm
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Rich Gee: https://github.com/zer0blockchain
// Dennis: https://github.com/denett
// Logic / Algorithm Ideas
// FrankieIsLost: https://github.com/FrankieIsLost
// Reviewer(s) / Contributor(s)
// Travis Moore: https://github.com/FortisFortuna
// Sam Kazemian: https://github.com/samkazemian
// Drake Evans: https://github.com/DrakeEvans
// Jack Corddry: https://github.com/corddry
// Justin Moore: https://github.com/0xJM
///@notice This library handles the execution of long term orders.
library ExecVirtualOrdersLib {
///@notice computes the result of virtual trades by the token pools
function computeVirtualBalances(
uint256 token0Start,
uint256 token1Start,
uint256 token0In,
uint256 token1In)
internal pure returns (uint256 token0Out, uint256 token1Out, uint256 ammEndToken0, uint256 ammEndToken1)
{
token0Out = 0;
token1Out = 0;
//if no tokens are sold to the pool, we don't need to execute any orders
if (token0In == 0 && token1In == 0) {
ammEndToken0 = token0Start;
ammEndToken1 = token1Start;
}
//in the case where only one pool is selling, we just perform a normal swap
else if (token0In == 0) {
//constant product formula
uint token1InWithFee = token1In * 997;
token0Out = token0Start * token1InWithFee / ((token1Start * 1000) + token1InWithFee);
ammEndToken0 = token0Start - token0Out;
ammEndToken1 = token1Start + token1In;
}
else if (token1In == 0) {
//contant product formula
uint token0InWithFee = token0In * 997;
token1Out = token1Start * token0InWithFee / ((token0Start * 1000) + token0InWithFee);
ammEndToken0 = token0Start + token0In;
ammEndToken1 = token1Start - token1Out;
}
//when both pools sell, we use the TWAMM formula
else {
uint256 aIn = token0In * 997 / 1000;
uint256 bIn = token1In * 997 / 1000;
uint256 k = token0Start * token1Start;
ammEndToken1 = token0Start * (token1Start + bIn) / (token0Start + aIn);
ammEndToken0 = k / ammEndToken1;
token0Out = token0Start + aIn - ammEndToken0;
token1Out = token1Start + bIn - ammEndToken1;
}
}
}
// File contracts/Uniswap_V2_TWAMM/twamm/LongTermOrders.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================= LongTermOrdersLib ========================
// ====================================================================
// TWAMM long term order execution logic
// Inspired by https://www.paradigm.xyz/2021/07/twamm
// https://github.com/para-dave/twamm
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Rich Gee: https://github.com/zer0blockchain
// Dennis: https://github.com/denett
// Logic / Algorithm Ideas
// FrankieIsLost: https://github.com/FrankieIsLost
// Reviewer(s) / Contributor(s)
// Travis Moore: https://github.com/FortisFortuna
// Sam Kazemian: https://github.com/samkazemian
// Drake Evans: https://github.com/DrakeEvans
// Jack Corddry: https://github.com/corddry
// Justin Moore: https://github.com/0xJM
///@notice This library handles the state and execution of long term orders.
library LongTermOrdersLib {
using LongTermOrdersLib for OrderPool;
/// ---------------------------
/// ----- LongTerm Orders -----
/// ---------------------------
uint112 internal constant SELL_RATE_ADDITIONAL_PRECISION = 1000000;
///@notice information associated with a long term order
///fields should NOT be changed after Order struct is created
struct Order {
uint256 id;
uint256 expirationTimestamp;
uint256 saleRate;
address owner;
address sellTokenAddr;
address buyTokenAddr;
bool isComplete;
}
///@notice structure contains full state related to long term orders
struct LongTermOrders {
///@notice minimum time interval between order expiries
uint256 orderTimeInterval;
///@notice last virtual orders were executed immediately before this block.timestamp
uint256 lastVirtualOrderTimestamp;
///@notice token pair being traded in embedded amm
address token0;
address token1;
///@notice mapping from token address to pool that is selling that token
///we maintain two order pools, one for each token that is tradable in the AMM
OrderPool OrderPool0;
OrderPool OrderPool1;
///@notice incrementing counter for order ids, this is the next order id
uint256 orderId;
///@notice mapping from order ids to Orders
mapping(uint256 => Order) orderMap;
}
struct ExecuteVirtualOrdersResult {
uint112 newReserve0;
uint112 newReserve1;
uint256 newTwammReserve0;
uint256 newTwammReserve1;
}
///@notice initialize state
function initialize(LongTermOrders storage longTermOrders,
address token0,
address token1,
uint256 lastVirtualOrderTimestamp,
uint256 orderTimeInterval) internal {
longTermOrders.token0 = token0;
longTermOrders.token1 = token1;
longTermOrders.lastVirtualOrderTimestamp = lastVirtualOrderTimestamp;
longTermOrders.orderTimeInterval = orderTimeInterval;
}
///@notice get the OrderPool for this token
function getOrderPool(LongTermOrders storage longTermOrders, address token) internal view returns (OrderPool storage orderPool) {
orderPool = token == longTermOrders.token0 ? longTermOrders.OrderPool0 : longTermOrders.OrderPool1;
}
///@notice swap token 0 for token 1. Amount represents total amount being sold, numberOfTimeIntervals determines when order expires
function longTermSwapFrom0To1(LongTermOrders storage longTermOrders, uint256 amount0, uint256 numberOfTimeIntervals) internal returns (uint256) {
return performLongTermSwap(longTermOrders, longTermOrders.token0, longTermOrders.token1, amount0, numberOfTimeIntervals);
}
///@notice swap token 1 for token 0. Amount represents total amount being sold, numberOfTimeIntervals determines when order expires
function longTermSwapFrom1To0(LongTermOrders storage longTermOrders, uint256 amount1, uint256 numberOfTimeIntervals) internal returns (uint256) {
return performLongTermSwap(longTermOrders, longTermOrders.token1, longTermOrders.token0, amount1, numberOfTimeIntervals);
}
///@notice adds long term swap to order pool
function performLongTermSwap(LongTermOrders storage longTermOrders, address from, address to, uint256 amount, uint256 numberOfTimeIntervals) private returns (uint256) {
// make sure to update virtual order state (before calling this function)
//determine the selling rate based on number of blocks to expiry and total amount
uint256 currentTime = block.timestamp;
uint256 lastExpiryTimestamp = currentTime - (currentTime % longTermOrders.orderTimeInterval);
uint256 orderExpiry = longTermOrders.orderTimeInterval * (numberOfTimeIntervals + 1) + lastExpiryTimestamp;
uint256 sellingRate = SELL_RATE_ADDITIONAL_PRECISION * amount / (orderExpiry - currentTime);
require(sellingRate > 0); // tokenRate cannot be zero
//add order to correct pool
OrderPool storage orderPool = getOrderPool(longTermOrders, from);
orderPoolDepositOrder(orderPool, longTermOrders.orderId, sellingRate, orderExpiry);
//add to order map
longTermOrders.orderMap[longTermOrders.orderId] = Order(longTermOrders.orderId, orderExpiry, sellingRate, msg.sender, from, to, false);
return longTermOrders.orderId++;
}
///@notice cancel long term swap, pay out unsold tokens and well as purchased tokens
function cancelLongTermSwap(LongTermOrders storage longTermOrders, uint256 orderId) internal returns (address sellToken, uint256 unsoldAmount, address buyToken, uint256 purchasedAmount) {
// make sure to update virtual order state (before calling this function)
Order storage order = longTermOrders.orderMap[orderId];
buyToken = order.buyTokenAddr;
sellToken = order.sellTokenAddr;
OrderPool storage orderPool = getOrderPool(longTermOrders, sellToken);
(unsoldAmount, purchasedAmount) = orderPoolCancelOrder(orderPool, orderId, longTermOrders.lastVirtualOrderTimestamp);
require(order.owner == msg.sender && (unsoldAmount > 0 || purchasedAmount > 0)); // owner and amounts check
}
///@notice withdraw proceeds from a long term swap (can be expired or ongoing)
function withdrawProceedsFromLongTermSwap(LongTermOrders storage longTermOrders, uint256 orderId) internal returns (address proceedToken, uint256 proceeds, bool orderExpired) {
// make sure to update virtual order state (before calling this function)
Order storage order = longTermOrders.orderMap[orderId];
proceedToken = order.buyTokenAddr;
OrderPool storage orderPool = getOrderPool(longTermOrders, order.sellTokenAddr);
(proceeds, orderExpired) = orderPoolWithdrawProceeds(orderPool, orderId, longTermOrders.lastVirtualOrderTimestamp);
require(order.owner == msg.sender && proceeds > 0); // owner and amounts check
}
///@notice executes all virtual orders between current lastVirtualOrderTimestamp and blockTimestamp
//also handles orders that expire at end of final blockTimestamp. This assumes that no orders expire inside the given interval
function executeVirtualTradesAndOrderExpiries(
ExecuteVirtualOrdersResult memory reserveResult,
uint256 token0SellAmount,
uint256 token1SellAmount
) private view returns (uint256 token0Out, uint256 token1Out) {
//initial amm balance
uint256 bal0 = reserveResult.newReserve0 + reserveResult.newTwammReserve0;
uint256 bal1 = reserveResult.newReserve1 + reserveResult.newTwammReserve1;
//updated balances from sales
uint256 ammEndToken0; uint256 ammEndToken1;
(token0Out, token1Out, ammEndToken0, ammEndToken1) = ExecVirtualOrdersLib.computeVirtualBalances(
reserveResult.newReserve0,
reserveResult.newReserve1,
token0SellAmount,
token1SellAmount
);
//update balances reserves
reserveResult.newTwammReserve0 = reserveResult.newTwammReserve0 + token0Out - token0SellAmount;
reserveResult.newTwammReserve1 = reserveResult.newTwammReserve1 + token1Out - token1SellAmount;
reserveResult.newReserve0 = uint112(bal0 - reserveResult.newTwammReserve0); // calculate reserve0 incl LP fees
reserveResult.newReserve1 = uint112(bal1 - reserveResult.newTwammReserve1); // calculate reserve1 incl LP fees
}
///@notice handles updating the orderPool state after execution of all virtual orders until blockTimestamp.
function updateOrderPoolAfterExecution(
LongTermOrders storage longTermOrders,
OrderPool storage orderPool0,
OrderPool storage orderPool1,
uint256 token0Out,
uint256 token1Out,
uint256 blockTimestamp
) private {
//distribute proceeds to pools
orderPoolDistributePayment(orderPool0, token1Out);
orderPoolDistributePayment(orderPool1, token0Out);
//handle orders expiring at end of interval
orderPoolUpdateStateFromBlockExpiry(orderPool0, blockTimestamp);
orderPoolUpdateStateFromBlockExpiry(orderPool1, blockTimestamp);
//update last virtual trade block
longTermOrders.lastVirtualOrderTimestamp = blockTimestamp;
}
///@notice executes all virtual orders until blockTimestamp is reached.
function executeVirtualOrdersUntilTimestamp(LongTermOrders storage longTermOrders, uint256 blockTimestamp, ExecuteVirtualOrdersResult memory reserveResult) internal {
uint256 nextExpiryBlockTimestamp = longTermOrders.lastVirtualOrderTimestamp - (longTermOrders.lastVirtualOrderTimestamp % longTermOrders.orderTimeInterval) + longTermOrders.orderTimeInterval;
//iterate through time intervals eligible for order expiries, moving state forward
OrderPool storage orderPool0 = longTermOrders.OrderPool0;
OrderPool storage orderPool1 = longTermOrders.OrderPool1;
while (nextExpiryBlockTimestamp < blockTimestamp) {
// Optimization for skipping blocks with no expiry
if (orderPool0.salesRateEndingPerTimeInterval[nextExpiryBlockTimestamp] > 0
|| orderPool1.salesRateEndingPerTimeInterval[nextExpiryBlockTimestamp] > 0) {
//amount sold from virtual trades
uint256 blockTimestampElapsed = nextExpiryBlockTimestamp - longTermOrders.lastVirtualOrderTimestamp;
uint256 token0SellAmount = orderPool0.currentSalesRate * blockTimestampElapsed / SELL_RATE_ADDITIONAL_PRECISION;
uint256 token1SellAmount = orderPool1.currentSalesRate * blockTimestampElapsed / SELL_RATE_ADDITIONAL_PRECISION;
(uint256 token0Out, uint256 token1Out) = executeVirtualTradesAndOrderExpiries(reserveResult, token0SellAmount, token1SellAmount);
updateOrderPoolAfterExecution(longTermOrders, orderPool0, orderPool1, token0Out, token1Out, nextExpiryBlockTimestamp);
}
nextExpiryBlockTimestamp += longTermOrders.orderTimeInterval;
}
//finally, move state to current blockTimestamp if necessary
if (longTermOrders.lastVirtualOrderTimestamp != blockTimestamp) {
//amount sold from virtual trades
uint256 blockTimestampElapsed = blockTimestamp - longTermOrders.lastVirtualOrderTimestamp;
uint256 token0SellAmount = orderPool0.currentSalesRate * blockTimestampElapsed / SELL_RATE_ADDITIONAL_PRECISION;
uint256 token1SellAmount = orderPool1.currentSalesRate * blockTimestampElapsed / SELL_RATE_ADDITIONAL_PRECISION;
(uint256 token0Out, uint256 token1Out) = executeVirtualTradesAndOrderExpiries(reserveResult, token0SellAmount, token1SellAmount);
updateOrderPoolAfterExecution(longTermOrders, orderPool0, orderPool1, token0Out, token1Out, blockTimestamp);
}
}
///@notice executes all virtual orders until blockTimestamp is reached (AS A VIEW)
function executeVirtualOrdersUntilTimestampView(LongTermOrders storage longTermOrders, uint256 blockTimestamp, ExecuteVirtualOrdersResult memory reserveResult) internal view {
uint256 nextExpiryBlockTimestamp = longTermOrders.lastVirtualOrderTimestamp - (longTermOrders.lastVirtualOrderTimestamp % longTermOrders.orderTimeInterval) + longTermOrders.orderTimeInterval;
//iterate through time intervals eligible for order expiries, moving state forward
OrderPool storage orderPool0 = longTermOrders.OrderPool0;
OrderPool storage orderPool1 = longTermOrders.OrderPool1;
// currentSales for each pool is mutated in the non-view (mutate locally)
uint256 currentSalesRate0 = orderPool0.currentSalesRate;
uint256 currentSalesRate1 = orderPool1.currentSalesRate;
while (nextExpiryBlockTimestamp < blockTimestamp) {
// Optimization for skipping blocks with no expiry
if (orderPool0.salesRateEndingPerTimeInterval[nextExpiryBlockTimestamp] > 0
|| orderPool1.salesRateEndingPerTimeInterval[nextExpiryBlockTimestamp] > 0) {
//amount sold from virtual trades
uint256 blockTimestampElapsed = nextExpiryBlockTimestamp - longTermOrders.lastVirtualOrderTimestamp;
uint256 token0SellAmount = currentSalesRate0 * blockTimestampElapsed / SELL_RATE_ADDITIONAL_PRECISION;
uint256 token1SellAmount = currentSalesRate1 * blockTimestampElapsed / SELL_RATE_ADDITIONAL_PRECISION;
(uint256 token0Out, uint256 token1Out) = executeVirtualTradesAndOrderExpiries(reserveResult, token0SellAmount, token1SellAmount);
currentSalesRate0 -= orderPool0.salesRateEndingPerTimeInterval[nextExpiryBlockTimestamp];
currentSalesRate1 -= orderPool1.salesRateEndingPerTimeInterval[nextExpiryBlockTimestamp];
}
nextExpiryBlockTimestamp += longTermOrders.orderTimeInterval;
}
//finally, move state to current blockTimestamp if necessary
if (longTermOrders.lastVirtualOrderTimestamp != blockTimestamp) {
//amount sold from virtual trades
uint256 blockTimestampElapsed = blockTimestamp - longTermOrders.lastVirtualOrderTimestamp;
uint256 token0SellAmount = currentSalesRate0 * blockTimestampElapsed / SELL_RATE_ADDITIONAL_PRECISION;
uint256 token1SellAmount = currentSalesRate1 * blockTimestampElapsed / SELL_RATE_ADDITIONAL_PRECISION;
(uint256 token0Out, uint256 token1Out) = executeVirtualTradesAndOrderExpiries(reserveResult, token0SellAmount, token1SellAmount);
}
}
/// ---------------------------
/// -------- OrderPool --------
/// ---------------------------
///@notice An Order Pool is an abstraction for a pool of long term orders that sells a token at a constant rate to the embedded AMM.
///the order pool handles the logic for distributing the proceeds from these sales to the owners of the long term orders through a modified
///version of the staking algorithm from https://uploads-ssl.webflow.com/5ad71ffeb79acc67c8bcdaba/5ad8d1193a40977462982470_scalable-reward-distribution-paper.pdf
uint256 constant Q112 = 2**112;
///@notice you can think of this as a staking pool where all long term orders are staked.
/// The pool is paid when virtual long term orders are executed, and each order is paid proportionally
/// by the order's sale rate per time intervals
struct OrderPool {
///@notice current rate that tokens are being sold (per time interval)
uint256 currentSalesRate;
///@notice sum of (salesProceeds_k / salesRate_k) over every period k. Stored as a fixed precision floating point number
uint256 rewardFactor;
///@notice this maps time interval numbers to the cumulative sales rate of orders that expire on that block (time interval)
mapping(uint256 => uint256) salesRateEndingPerTimeInterval;
///@notice map order ids to the block timestamp in which they expire
mapping(uint256 => uint256) orderExpiry;
///@notice map order ids to their sales rate
mapping(uint256 => uint256) salesRate;
///@notice reward factor per order at time of submission
mapping(uint256 => uint256) rewardFactorAtSubmission;
///@notice reward factor at a specific time interval
mapping(uint256 => uint256) rewardFactorAtTimestamp;
}
///@notice distribute payment amount to pool (in the case of TWAMM, proceeds from trades against amm)
function orderPoolDistributePayment(OrderPool storage orderPool, uint256 amount) internal {
if (orderPool.currentSalesRate != 0) {
unchecked { // Addition is with overflow
orderPool.rewardFactor += amount * Q112 * SELL_RATE_ADDITIONAL_PRECISION / orderPool.currentSalesRate;
}
}
}
///@notice deposit an order into the order pool.
function orderPoolDepositOrder(OrderPool storage orderPool, uint256 orderId, uint256 amountPerBlock, uint256 orderExpiry) internal {
orderPool.currentSalesRate += amountPerBlock;
orderPool.rewardFactorAtSubmission[orderId] = orderPool.rewardFactor;
orderPool.orderExpiry[orderId] = orderExpiry;
orderPool.salesRate[orderId] = amountPerBlock;
orderPool.salesRateEndingPerTimeInterval[orderExpiry] += amountPerBlock;
}
///@notice when orders expire after a given block, we need to update the state of the pool
function orderPoolUpdateStateFromBlockExpiry(OrderPool storage orderPool, uint256 blockTimestamp) internal {
orderPool.currentSalesRate -= orderPool.salesRateEndingPerTimeInterval[blockTimestamp];
orderPool.rewardFactorAtTimestamp[blockTimestamp] = orderPool.rewardFactor;
}
///@notice cancel order and remove from the order pool
function orderPoolCancelOrder(OrderPool storage orderPool, uint256 orderId, uint256 blockTimestamp) internal returns (uint256 unsoldAmount, uint256 purchasedAmount) {
uint256 expiry = orderPool.orderExpiry[orderId];
require(expiry > blockTimestamp);
//calculate amount that wasn't sold, and needs to be returned
uint256 salesRate = orderPool.salesRate[orderId];
unsoldAmount = (expiry - blockTimestamp) * salesRate / SELL_RATE_ADDITIONAL_PRECISION;
//calculate amount of other token that was purchased
unchecked { // subtraction is with underflow
purchasedAmount = ((orderPool.rewardFactor - orderPool.rewardFactorAtSubmission[orderId]) * salesRate / SELL_RATE_ADDITIONAL_PRECISION) / Q112;
}
//update state
orderPool.currentSalesRate -= salesRate;
orderPool.salesRate[orderId] = 0;
orderPool.orderExpiry[orderId] = 0;
orderPool.salesRateEndingPerTimeInterval[expiry] -= salesRate;
}
///@notice withdraw proceeds from pool for a given order. This can be done before or after the order has expired.
//If the order has expired, we calculate the reward factor at time of expiry. If order has not yet expired, we
//use current reward factor, and update the reward factor at time of staking (effectively creating a new order)
function orderPoolWithdrawProceeds(OrderPool storage orderPool, uint256 orderId, uint256 blockTimestamp) internal returns (uint256 totalReward, bool orderExpired) {
(orderExpired, totalReward) = orderPoolGetProceeds(orderPool, orderId, blockTimestamp);
if (orderExpired) {
//remove stake
orderPool.salesRate[orderId] = 0;
}
//if order has not yet expired, we just adjust the start
else {
orderPool.rewardFactorAtSubmission[orderId] = orderPool.rewardFactor;
}
}
///@notice view function for getting the current proceeds for the given order
function orderPoolGetProceeds(OrderPool storage orderPool, uint256 orderId, uint256 blockTimestamp) internal view returns (bool orderExpired, uint256 totalReward) {
uint256 stakedAmount = orderPool.salesRate[orderId];
require(stakedAmount > 0);
uint256 orderExpiry = orderPool.orderExpiry[orderId];
uint256 rewardFactorAtSubmission = orderPool.rewardFactorAtSubmission[orderId];
//if order has expired, we need to calculate the reward factor at expiry
if (blockTimestamp > orderExpiry) {
uint256 rewardFactorAtExpiry = orderPool.rewardFactorAtTimestamp[orderExpiry];
unchecked { // subtraction is with underflow
totalReward = ((rewardFactorAtExpiry - rewardFactorAtSubmission) * stakedAmount / SELL_RATE_ADDITIONAL_PRECISION) / Q112;
}
orderExpired = true;
}
else {
unchecked { // subtraction is with underflow
totalReward = ((orderPool.rewardFactor - rewardFactorAtSubmission) * stakedAmount / SELL_RATE_ADDITIONAL_PRECISION) / Q112;
}
orderExpired = false;
}
}
}
// File contracts/Uniswap_V2_TWAMM/core/UniV2TWAMMPair.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================== UniV2TWAMMPair ==========================
// ====================================================================
// TWAMM LP Pair Token
// Inspired by https://www.paradigm.xyz/2021/07/twamm
// https://github.com/para-dave/twamm
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Rich Gee: https://github.com/zer0blockchain
// Dennis: https://github.com/denett
// Logic / Algorithm Ideas
// FrankieIsLost: https://github.com/FrankieIsLost
// Reviewer(s) / Contributor(s)
// Travis Moore: https://github.com/FortisFortuna
// Sam Kazemian: https://github.com/samkazemian
// Drake Evans: https://github.com/DrakeEvans
// Jack Corddry: https://github.com/corddry
// Justin Moore: https://github.com/0xJM
contract UniV2TWAMMPair is IUniswapV2PairPartialV5, UniV2TWAMMERC20 {
using UQ112x112 for uint224;
using LongTermOrdersLib for LongTermOrdersLib.LongTermOrders;
using LongTermOrdersLib for LongTermOrdersLib.ExecuteVirtualOrdersResult;
/// ---------------------------
/// -----TWAMM Parameters -----
/// ---------------------------
address public owner_address;
///@notice time interval that are eligible for order expiry (to align expiries)
uint256 public orderTimeInterval = 3600;
///@notice data structure to handle long term orders
LongTermOrdersLib.LongTermOrders internal longTermOrders;
uint112 public twammReserve0;
uint112 public twammReserve1;
bool public newSwapsPaused;
modifier execVirtualOrders() {
executeVirtualOrdersInternal(block.timestamp);
_;
}
/// ---------------------------
/// -------- Modifiers --------
/// ---------------------------
///@notice Throws if called by any account other than the owner.
modifier onlyOwner() {
require(owner_address == msg.sender); // NOT OWNER
_;
}
///@notice Checks if new swaps are paused. If they are, only allow closing of existing ones.
modifier isNotPaused() {
require(newSwapsPaused == false); // NEW LT ORDERS PAUSED
_;
}
/// ---------------------------
/// --------- Events ----------
/// ---------------------------
///@notice An event emitted when a long term swap from token0 to token1 is performed
event LongTermSwap0To1(address indexed addr, uint256 orderId, uint256 amount0In, uint256 numberOfTimeIntervals);
///@notice An event emitted when a long term swap from token1 to token0 is performed
event LongTermSwap1To0(address indexed addr, uint256 orderId, uint256 amount1In, uint256 numberOfTimeIntervals);
///@notice An event emitted when a long term swap is cancelled
event CancelLongTermOrder(address indexed addr, uint256 orderId, address sellToken, uint256 unsoldAmount, address buyToken, uint256 purchasedAmount);
///@notice An event emitted when a long term swap is withdrawn
event WithdrawProceedsFromLongTermOrder(address indexed addr, uint256 orderId, address indexed proceedToken, uint256 proceeds, bool orderExpired);
/// -------------------------------
/// -----UNISWAPV2 Parameters -----
/// -------------------------------
uint public constant override MINIMUM_LIQUIDITY = 10 ** 3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public override factory;
address public override token0;
address public override token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public override kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
// Track order IDs
mapping(address => uint256[]) public orderIDsForUser;
TWAPObservation[] public TWAPObservationHistory;
struct TWAPObservation {
uint timestamp;
uint price0CumulativeLast;
uint price1CumulativeLast;
}
function price0CumulativeLast() public view override returns (uint){
return TWAPObservationHistory.length > 0 ? TWAPObservationHistory[TWAPObservationHistory.length - 1].price0CumulativeLast : 0;
}
function price1CumulativeLast() public view override returns (uint){
return TWAPObservationHistory.length > 0 ? TWAPObservationHistory[TWAPObservationHistory.length - 1].price1CumulativeLast : 0;
}
function getTWAPHistoryLength() public view override returns (uint){
return TWAPObservationHistory.length;
}
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1); // LOCKED
unlocked = 0;
_;
unlocked = 1;
}
function getOrderIDsForUser(address user) external view returns (uint256[] memory) {
return orderIDsForUser[user];
}
function getOrderIDsForUserLength(address user) external view returns (uint256) {
return orderIDsForUser[user].length;
}
function getDetailedOrdersForUser(address user, uint256 offset, uint256 limit) external view returns (LongTermOrdersLib.Order[] memory detailed_orders) {
uint256[] memory order_ids = orderIDsForUser[user];
uint256 length_remaining = order_ids.length - offset;
uint256 limit_to_use = Math.min(limit, length_remaining);
detailed_orders = new LongTermOrdersLib.Order[](limit_to_use);
for (uint256 i = 0; i < limit_to_use; i++){
detailed_orders[i] = longTermOrders.orderMap[order_ids[offset + i]];
}
}
function getReserves() public override view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
return (reserve0, reserve1, blockTimestampLast);
}
function getTwammReserves() public override view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast, uint112 _twammReserve0, uint112 _twammReserve1) {
return (reserve0, reserve1, blockTimestampLast, twammReserve0, twammReserve1);
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "EC01"); // TRANSFER_FAILED
}
constructor() public {
factory = msg.sender;
owner_address = IUniswapV2FactoryV5(factory).feeToSetter();
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external override {
require(msg.sender == factory); // FORBIDDEN
// sufficient check
token0 = _token0;
token1 = _token1;
// TWAMM
longTermOrders.initialize(_token0, _token1, block.timestamp, orderTimeInterval);
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 + twammReserve0 <= type(uint112).max && balance1 + twammReserve1 <= type(uint112).max, "EC02"); // OVERFLOW
uint32 blockTimestamp = uint32(block.timestamp % 2 ** 32);
uint32 timeElapsed;
unchecked{
timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
TWAPObservationHistory.push(
TWAPObservation(
blockTimestamp,
price0CumulativeLast() + uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed,
price1CumulativeLast() + uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed
)
);
}
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2FactoryV5(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0) * _reserve1);
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply * (rootK - rootKLast);
uint denominator = (rootK * 5) + rootKLast;
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external override lock execVirtualOrders returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20V5(token0).balanceOf(address(this)) - twammReserve0;
uint balance1 = IERC20V5(token1).balanceOf(address(this)) - twammReserve1;
uint amount0 = balance0 - _reserve0;
uint amount1 = balance1 - _reserve1;
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0 * amount1) - MINIMUM_LIQUIDITY;
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0 * _totalSupply / _reserve0, amount1 * _totalSupply / _reserve1);
}
require(liquidity > 0); // INSUFFICIENT_LIQUIDITY_MINTED
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0) * reserve1; // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external override lock execVirtualOrders returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20V5(_token0).balanceOf(address(this)) - twammReserve0;
uint balance1 = IERC20V5(_token1).balanceOf(address(this)) - twammReserve1;
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity * balance0 / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity * balance1 / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0); // INSUFFICIENT_LIQUIDITY_BURNED
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20V5(_token0).balanceOf(address(this)) - twammReserve0;
balance1 = IERC20V5(_token1).balanceOf(address(this)) - twammReserve1;
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0) * reserve1; // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external override lock execVirtualOrders {
require(amount0Out > 0 || amount1Out > 0, "EC03"); // INSUFFICIENT_OUTPUT_AMOUNT
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, "EC04"); // INSUFFICIENT_LIQUIDITY
uint balance0;
uint balance1;
{// scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, "EC05"); // INVALID_TO
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2CalleeV5(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20V5(_token0).balanceOf(address(this)) - twammReserve0;
balance1 = IERC20V5(_token1).balanceOf(address(this)) - twammReserve1;
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, "EC06"); // INSUFFICIENT_INPUT_AMOUNT
{// scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = (balance0 * 1000) - (amount0In * 3);
uint balance1Adjusted = (balance1 * 1000) - (amount1In * 3);
require(balance0Adjusted * balance1Adjusted >= uint(_reserve0) * _reserve1 * (1000 ** 2), 'K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external override lock execVirtualOrders {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20V5(_token0).balanceOf(address(this)) - (reserve0 + twammReserve0));
_safeTransfer(_token1, to, IERC20V5(_token1).balanceOf(address(this)) - (reserve1 + twammReserve1));
}
// force reserves to match balances
function sync() external override lock execVirtualOrders {
_update(
IERC20V5(token0).balanceOf(address(this)) - twammReserve0,
IERC20V5(token1).balanceOf(address(this)) - twammReserve1,
reserve0, reserve1
);
}
// TWAMM
///@notice calculate the amount in for token0 using the balance diff to handle feeOnTransfer tokens
function transferAmount0In(uint amount0In) internal returns(uint256){
// prev balance
uint bal0 = IERC20V5(token0).balanceOf(address(this));
// transfer amount to contract
TransferHelper.safeTransferFrom(token0, msg.sender, address(this), amount0In);
// balance change
return IERC20V5(token0).balanceOf(address(this)) - bal0;
}
///@notice calculate the amount in for token1 using the balance diff to handle feeOnTransfer tokens
function transferAmount1In(uint amount1In) internal returns(uint256){
// prev balance
uint bal1 = IERC20V5(token1).balanceOf(address(this));
// transfer amount to contract
TransferHelper.safeTransferFrom(token1, msg.sender, address(this), amount1In);
// balance change
return IERC20V5(token1).balanceOf(address(this)) - bal1;
}
///@notice create a long term order to swap from token0
///@param amount0In total amount of token0 to swap
///@param numberOfTimeIntervals number of time intervals over which to execute long term order
function longTermSwapFrom0To1(uint256 amount0In, uint256 numberOfTimeIntervals) external lock isNotPaused execVirtualOrders returns (uint256 orderId) {
uint amount0 = transferAmount0In(amount0In);
twammReserve0 += uint112(amount0);
require(reserve0 + twammReserve0 <= type(uint112).max); // OVERFLOW
orderId = longTermOrders.longTermSwapFrom0To1(amount0, numberOfTimeIntervals);
orderIDsForUser[msg.sender].push(orderId);
emit LongTermSwap0To1(msg.sender, orderId, amount0, numberOfTimeIntervals);
}
///@notice create a long term order to swap from token1
///@param amount1In total amount of token1 to swap
///@param numberOfTimeIntervals number of time intervals over which to execute long term order
function longTermSwapFrom1To0(uint256 amount1In, uint256 numberOfTimeIntervals) external lock isNotPaused execVirtualOrders returns (uint256 orderId) {
uint amount1 = transferAmount1In(amount1In);
twammReserve1 += uint112(amount1);
require(reserve1 + twammReserve1 <= type(uint112).max); // OVERFLOW
orderId = longTermOrders.longTermSwapFrom1To0(amount1, numberOfTimeIntervals);
orderIDsForUser[msg.sender].push(orderId);
emit LongTermSwap1To0(msg.sender, orderId, amount1, numberOfTimeIntervals);
}
///@notice stop the execution of a long term order
function cancelLongTermSwap(uint256 orderId) external lock execVirtualOrders {
(address sellToken, uint256 unsoldAmount, address buyToken, uint256 purchasedAmount) = longTermOrders.cancelLongTermSwap(orderId);
bool buyToken0 = buyToken == token0;
twammReserve0 -= uint112(buyToken0 ? purchasedAmount : unsoldAmount);
twammReserve1 -= uint112(buyToken0 ? unsoldAmount : purchasedAmount);
// transfer to owner of order
_safeTransfer(buyToken, msg.sender, purchasedAmount);
_safeTransfer(sellToken, msg.sender, unsoldAmount);
// update order. Used for tracking
longTermOrders.orderMap[orderId].isComplete = true;
emit CancelLongTermOrder(msg.sender, orderId, sellToken, unsoldAmount, buyToken, purchasedAmount);
}
///@notice withdraw proceeds from a long term swap
function withdrawProceedsFromLongTermSwap(uint256 orderId) external lock execVirtualOrders returns (bool is_expired) {
(address proceedToken, uint256 proceeds, bool orderExpired) = longTermOrders.withdrawProceedsFromLongTermSwap(orderId);
if (proceedToken == token0) {
twammReserve0 -= uint112(proceeds);
} else {
twammReserve1 -= uint112(proceeds);
}
// transfer to owner of order
_safeTransfer(proceedToken, msg.sender, proceeds);
// update order. Used for tracking
if (orderExpired) longTermOrders.orderMap[orderId].isComplete = true;
emit WithdrawProceedsFromLongTermOrder(msg.sender, orderId, proceedToken, proceeds, orderExpired);
return orderExpired;
}
///@notice execute virtual orders in the twamm, bring it up to the blockNumber passed in
///updates the TWAP if it is the first amm tx of the block
function executeVirtualOrdersInternal(uint256 blockTimestamp) internal {
if(newSwapsPaused) return; // skip twamm executions
if(twammUpToDate()) return; // save gas
LongTermOrdersLib.ExecuteVirtualOrdersResult memory result;
result.newReserve0 = reserve0;
result.newReserve1 = reserve1;
result.newTwammReserve0 = twammReserve0;
result.newTwammReserve1 = twammReserve1;
longTermOrders.executeVirtualOrdersUntilTimestamp(blockTimestamp, result);
twammReserve0 = uint112(result.newTwammReserve0);
twammReserve1 = uint112(result.newTwammReserve1);
uint112 newReserve0 = uint112(result.newReserve0);
uint112 newReserve1 = uint112(result.newReserve1);
uint32 _blockTimestamp = uint32(blockTimestamp % 2 ** 32);
uint32 timeElapsed;
unchecked{
timeElapsed = _blockTimestamp - blockTimestampLast; // overflow is desired
}
// update reserve0 and reserve1
if ( timeElapsed > 0 && (newReserve0 != reserve0 || newReserve1 != reserve1)) {
_update(newReserve0, newReserve1, reserve0, reserve1);
} else {
reserve0 = newReserve0;
reserve1 = newReserve1;
}
}
///@notice convenience function to execute virtual orders. Note that this already happens
///before most interactions with the AMM
function executeVirtualOrders(uint256 blockTimestamp) public override lock {
// blockTimestamp is valid
require(longTermOrders.lastVirtualOrderTimestamp <= blockTimestamp && blockTimestamp <= block.timestamp); // INVALID TIMESTAMP
executeVirtualOrdersInternal(blockTimestamp);
}
/// ---------------------------
/// ------- TWAMM Views -------
/// ---------------------------
///@notice util function for getting the next orderId
function getNextOrderID() public override view returns (uint256){
return longTermOrders.orderId;
}
///@notice util function for checking if the twamm is up to date
function twammUpToDate() public override view returns (bool) {
return block.timestamp == longTermOrders.lastVirtualOrderTimestamp;
}
function getReserveAfterTwamm(uint256 blockTimestamp) public view returns (
uint112 _reserve0, uint112 _reserve1,
uint256 lastVirtualOrderTimestamp,
uint112 _twammReserve0, uint112 _twammReserve1
) {
lastVirtualOrderTimestamp = longTermOrders.lastVirtualOrderTimestamp;
uint112 bal0 = reserve0 + twammReserve0; // save the balance of token0
uint112 bal1 = reserve1 + twammReserve1; // save the balance of token1
LongTermOrdersLib.ExecuteVirtualOrdersResult memory result;
result.newReserve0 = reserve0;
result.newReserve1 = reserve1;
result.newTwammReserve0 = twammReserve0;
result.newTwammReserve1 = twammReserve1;
longTermOrders.executeVirtualOrdersUntilTimestampView(blockTimestamp, result);
_reserve0 = uint112(bal0 - result.newTwammReserve0);
_reserve1 = uint112(bal1 - result.newTwammReserve1);
_twammReserve0 = uint112(result.newTwammReserve0);
_twammReserve1 = uint112(result.newTwammReserve1);
}
///@notice returns the current state of the twamm
function getTwammState() public override view returns (
uint256 token0Rate,
uint256 token1Rate,
uint256 lastVirtualOrderTimestamp,
uint256 orderTimeInterval_rtn,
uint256 rewardFactorPool0,
uint256 rewardFactorPool1
){
token0Rate = longTermOrders.OrderPool0.currentSalesRate;
token1Rate = longTermOrders.OrderPool1.currentSalesRate;
lastVirtualOrderTimestamp = longTermOrders.lastVirtualOrderTimestamp;
orderTimeInterval_rtn = longTermOrders.orderTimeInterval;
rewardFactorPool0 = longTermOrders.OrderPool0.rewardFactor;
rewardFactorPool1 = longTermOrders.OrderPool1.rewardFactor;
}
///@notice returns salesRates ending on this blockTimestamp
function getTwammSalesRateEnding(uint256 _blockTimestamp) public override view returns (
uint256 orderPool0SalesRateEnding,
uint256 orderPool1SalesRateEnding
){
uint256 lastExpiryTimestamp = _blockTimestamp - (_blockTimestamp % longTermOrders.orderTimeInterval);
orderPool0SalesRateEnding = longTermOrders.OrderPool0.salesRateEndingPerTimeInterval[lastExpiryTimestamp];
orderPool1SalesRateEnding = longTermOrders.OrderPool1.salesRateEndingPerTimeInterval[lastExpiryTimestamp];
}
///@notice returns reward factors at this blockTimestamp
function getTwammRewardFactor(uint256 _blockTimestamp) public override view returns (
uint256 rewardFactorPool0AtTimestamp,
uint256 rewardFactorPool1AtTimestamp
){
uint256 lastExpiryTimestamp = _blockTimestamp - (_blockTimestamp % longTermOrders.orderTimeInterval);
rewardFactorPool0AtTimestamp = longTermOrders.OrderPool0.rewardFactorAtTimestamp[lastExpiryTimestamp];
rewardFactorPool1AtTimestamp = longTermOrders.OrderPool1.rewardFactorAtTimestamp[lastExpiryTimestamp];
}
///@notice returns the twamm Order struct
function getTwammOrder(uint256 orderId) public override view returns (
uint256 id,
uint256 expirationTimestamp,
uint256 saleRate,
address owner,
address sellTokenAddr,
address buyTokenAddr
){
require(orderId < longTermOrders.orderId); // INVALID ORDERID
LongTermOrdersLib.Order storage order = longTermOrders.orderMap[orderId];
return (order.id, order.expirationTimestamp, order.saleRate, order.owner, order.sellTokenAddr, order.buyTokenAddr);
}
///@notice returns the twamm Order withdrawable proceeds
function getTwammOrderProceeds(uint256 orderId, uint256 blockTimestamp) public override view returns (
bool orderExpired,
uint256 totalReward
){
require(orderId < longTermOrders.orderId); // INVALID ORDERID
LongTermOrdersLib.OrderPool storage orderPool = LongTermOrdersLib.getOrderPool(longTermOrders, longTermOrders.orderMap[orderId].sellTokenAddr);
(orderExpired, totalReward) = LongTermOrdersLib.orderPoolGetProceeds(orderPool, orderId, blockTimestamp);
}
/* ========== RESTRICTED FUNCTIONS - Owner only ========== */
// Only callable once
function togglePauseNewSwaps() external override onlyOwner {
// Pause / unpause new swaps
newSwapsPaused = !newSwapsPaused;
}
}
// File contracts/Uniswap_V2_TWAMM/core/UniV2TWAMMFactory.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================= UniV2TWAMMFactory ========================
// ====================================================================
// TWAMM LP Pair Factory
// Inspired by https://www.paradigm.xyz/2021/07/twamm
// https://github.com/para-dave/twamm
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Rich Gee: https://github.com/zer0blockchain
// Dennis: https://github.com/denett
// Logic / Algorithm Ideas
// FrankieIsLost: https://github.com/FrankieIsLost
// Reviewer(s) / Contributor(s)
// Travis Moore: https://github.com/FortisFortuna
// Sam Kazemian: https://github.com/samkazemian
// Drake Evans: https://github.com/DrakeEvans
// Jack Corddry: https://github.com/corddry
// Justin Moore: https://github.com/0xJM
contract UniV2TWAMMFactory is IUniswapV2FactoryV5 {
address public override feeTo;
address public override feeToSetter;
mapping(address => mapping(address => address)) public override getPair;
address[] public override allPairs;
constructor(address _feeToSetter) {
feeToSetter = _feeToSetter;
}
///@notice Throws if called by any account other than the feeToSetter.
modifier onlyFTS() {
require(msg.sender == feeToSetter); // FORBIDDEN
_;
}
function allPairsLength() external override view returns (uint) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB) external override returns (address pair) {
require(tokenA != tokenB, "IDENTICAL_ADDRESSES"); // IDENTICAL_ADDRESSES
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "ZERO_ADDRESS"); // ZERO_ADDRESS
require(getPair[token0][token1] == address(0), "PAIR_EXISTS"); // PAIR_EXISTS // single check is sufficient
bytes memory bytecode = type(UniV2TWAMMPair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
UniV2TWAMMPair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setFeeTo(address _feeTo) external override onlyFTS {
feeTo = _feeTo;
}
function setFeeToSetter(address _feeToSetter) external override onlyFTS {
feeToSetter = _feeToSetter;
}
} | update reserves and, on the first call per block, price accumulators * never overflows, and + overflow is desired | function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
uint32 blockTimestamp = uint32(block.timestamp % 2 ** 32);
uint32 timeElapsed;
unchecked{
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
TWAPObservationHistory.push(
TWAPObservation(
blockTimestamp,
price0CumulativeLast() + uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed,
price1CumulativeLast() + uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed
)
);
}
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
| 1,350,067 | [
1,
2725,
400,
264,
3324,
471,
16,
603,
326,
1122,
745,
1534,
1203,
16,
6205,
8822,
3062,
225,
5903,
9391,
87,
16,
471,
397,
9391,
353,
6049,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
2725,
12,
11890,
11013,
20,
16,
2254,
11013,
21,
16,
2254,
17666,
389,
455,
6527,
20,
16,
2254,
17666,
389,
455,
6527,
21,
13,
3238,
288,
203,
3639,
2254,
1578,
1203,
4921,
273,
2254,
1578,
12,
2629,
18,
5508,
738,
576,
2826,
3847,
1769,
203,
203,
3639,
2254,
1578,
813,
28827,
31,
203,
3639,
22893,
95,
203,
5411,
309,
261,
957,
28827,
405,
374,
597,
389,
455,
6527,
20,
480,
374,
597,
389,
455,
6527,
21,
480,
374,
13,
288,
203,
7734,
24722,
2203,
26199,
367,
5623,
18,
6206,
12,
203,
10792,
24722,
2203,
26199,
367,
12,
203,
13491,
1203,
4921,
16,
203,
13491,
6205,
20,
39,
11276,
3024,
1435,
397,
2254,
12,
57,
53,
17666,
92,
17666,
18,
3015,
24899,
455,
6527,
21,
2934,
89,
85,
2892,
24899,
455,
6527,
20,
3719,
380,
813,
28827,
16,
203,
13491,
6205,
21,
39,
11276,
3024,
1435,
397,
2254,
12,
57,
53,
17666,
92,
17666,
18,
3015,
24899,
455,
6527,
20,
2934,
89,
85,
2892,
24899,
455,
6527,
21,
3719,
380,
813,
28827,
203,
10792,
262,
203,
7734,
11272,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
20501,
20,
273,
2254,
17666,
12,
12296,
20,
1769,
203,
3639,
20501,
21,
273,
2254,
17666,
12,
12296,
21,
1769,
203,
203,
3639,
1203,
4921,
3024,
273,
1203,
4921,
31,
203,
3639,
3626,
9721,
12,
455,
6527,
20,
16,
20501,
21,
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
] |
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
| TODO: should increase instead | function approve_701(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,454,414 | [
1,
6241,
30,
1410,
10929,
3560,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
6617,
537,
67,
27,
1611,
12,
2867,
17571,
264,
16,
2254,
460,
13,
1071,
1135,
261,
6430,
1529,
13,
288,
203,
565,
389,
12908,
4524,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
460,
31,
203,
565,
3626,
1716,
685,
1125,
12,
1234,
18,
15330,
16,
17571,
264,
16,
460,
11272,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbUintsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
uint256 value;
}
struct BlockNumbUints {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbUints storage self)
internal
view
returns (Entry)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (uint256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (Entry)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbUints storage self, uint256 blockNumber, uint256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbUints storage self)
internal
view
returns (Entry[])
{
return self.entries;
}
function indexByBlockNumber(BlockNumbUints storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length);
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbIntsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
int256 value;
}
struct BlockNumbInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbInts storage self)
internal
view
returns (int256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbInts storage self)
internal
view
returns (Entry)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (Entry)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbInts storage self, uint256 blockNumber, int256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbInts storage self)
internal
view
returns (Entry[])
{
return self.entries;
}
function indexByBlockNumber(BlockNumbInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length);
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbDisdIntsLib {
using SafeMathIntLib for int256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Discount {
int256 tier;
int256 value;
}
struct Entry {
uint256 blockNumber;
int256 nominal;
Discount[] discounts;
}
struct BlockNumbDisdInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentNominalValue(BlockNumbDisdInts storage self)
internal
view
returns (int256)
{
return nominalValueAt(self, block.number);
}
function currentDiscountedValue(BlockNumbDisdInts storage self, int256 tier)
internal
view
returns (int256)
{
return discountedValueAt(self, block.number, tier);
}
function currentEntry(BlockNumbDisdInts storage self)
internal
view
returns (Entry)
{
return entryAt(self, block.number);
}
function nominalValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).nominal;
}
function discountedValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber, int256 tier)
internal
view
returns (int256)
{
Entry memory entry = entryAt(self, _blockNumber);
if (0 < entry.discounts.length) {
uint256 index = indexByTier(entry.discounts, tier);
if (0 < index)
return entry.nominal.mul(
ConstantsLib.PARTS_PER().sub(entry.discounts[index - 1].value)
).div(
ConstantsLib.PARTS_PER()
);
else
return entry.nominal;
} else
return entry.nominal;
}
function entryAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (Entry)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addNominalEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber
);
self.entries.length++;
Entry storage entry = self.entries[self.entries.length - 1];
entry.blockNumber = blockNumber;
entry.nominal = nominal;
}
function addDiscountedEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal,
int256[] discountTiers, int256[] discountValues)
internal
{
require(discountTiers.length == discountValues.length);
addNominalEntry(self, blockNumber, nominal);
Entry storage entry = self.entries[self.entries.length - 1];
for (uint256 i = 0; i < discountTiers.length; i++)
entry.discounts.push(Discount(discountTiers[i], discountValues[i]));
}
function count(BlockNumbDisdInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbDisdInts storage self)
internal
view
returns (Entry[])
{
return self.entries;
}
function indexByBlockNumber(BlockNumbDisdInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length);
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
/// @dev The index returned here is 1-based
function indexByTier(Discount[] discounts, int256 tier)
internal
pure
returns (uint256)
{
require(0 < discounts.length);
for (uint256 i = discounts.length; i > 0; i--)
if (tier >= discounts[i - 1].tier)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbReferenceCurrenciesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Currency currency;
}
struct BlockNumbReferenceCurrencies {
mapping(address => mapping(uint256 => Entry[])) entriesByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return currencyAt(self, referenceCurrency, block.number);
}
function currentEntry(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency)
internal
view
returns (Entry storage)
{
return entryAt(self, referenceCurrency, block.number);
}
function currencyAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency,
uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return entryAt(self, referenceCurrency, _blockNumber).currency;
}
function entryAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency,
uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][indexByBlockNumber(self, referenceCurrency, _blockNumber)];
}
function addEntry(BlockNumbReferenceCurrencies storage self, uint256 blockNumber,
MonetaryTypesLib.Currency referenceCurrency, MonetaryTypesLib.Currency currency)
internal
{
require(
0 == self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length ||
blockNumber > self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1].blockNumber
);
self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].push(Entry(blockNumber, currency));
}
function count(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency)
internal
view
returns (uint256)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length;
}
function entriesByCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency)
internal
view
returns (Entry[] storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id];
}
function indexByBlockNumber(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency referenceCurrency, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length);
for (uint256 i = self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1; i >= 0; i--)
if (blockNumber >= self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbFiguresLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Figure value;
}
struct BlockNumbFigures {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbFigures storage self)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbFigures storage self)
internal
view
returns (Entry storage)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbFigures storage self, uint256 blockNumber, MonetaryTypesLib.Figure value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbFigures storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbFigures storage self)
internal
view
returns (Entry[] storage)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbFigures storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length);
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Configuration
* @notice An oracle for configurations values
*/
contract Configuration is Modifiable, Ownable, Servable {
using SafeMathIntLib for int256;
using BlockNumbUintsLib for BlockNumbUintsLib.BlockNumbUints;
using BlockNumbIntsLib for BlockNumbIntsLib.BlockNumbInts;
using BlockNumbDisdIntsLib for BlockNumbDisdIntsLib.BlockNumbDisdInts;
using BlockNumbReferenceCurrenciesLib for BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies;
using BlockNumbFiguresLib for BlockNumbFiguresLib.BlockNumbFigures;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public OPERATIONAL_MODE_ACTION = "operational_mode";
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum OperationalMode {Normal, Exit}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
OperationalMode public operationalMode = OperationalMode.Normal;
BlockNumbUintsLib.BlockNumbUints private updateDelayBlocksByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private confirmationBlocksByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeMakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeTakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private paymentFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbDisdIntsLib.BlockNumbDisdInts)) private currencyPaymentFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeMakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeTakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private paymentMinimumFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbIntsLib.BlockNumbInts)) private currencyPaymentMinimumFeeByBlockNumber;
BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies private feeCurrencyByCurrencyBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletLockTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private cancelOrderChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private settlementChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private fraudStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletSettlementStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private operatorSettlementStakeFractionByBlockNumber;
BlockNumbFiguresLib.BlockNumbFigures private operatorSettlementStakeByBlockNumber;
uint256 public earliestSettlementBlockNumber;
bool public earliestSettlementBlockNumberUpdateDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetOperationalModeExitEvent();
event SetUpdateDelayBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetConfirmationBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetTradeMakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetTradeTakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetPaymentFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetCurrencyPaymentFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] discountTiers, int256[] discountValues);
event SetTradeMakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetTradeTakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetPaymentMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetCurrencyPaymentMinimumFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal);
event SetFeeCurrencyEvent(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId);
event SetWalletLockTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetCancelOrderChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetSettlementChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetWalletSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeEvent(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt,
uint256 stakeCurrencyId);
event SetFraudStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetEarliestSettlementBlockNumberEvent(uint256 earliestSettlementBlockNumber);
event DisableEarliestSettlementBlockNumberUpdateEvent();
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
updateDelayBlocksByBlockNumber.addEntry(block.number, 0);
}
//
// Public functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set operational mode to Exit
/// @dev Once operational mode is set to Exit it may not be set back to Normal
function setOperationalModeExit()
public
onlyEnabledServiceAction(OPERATIONAL_MODE_ACTION)
{
operationalMode = OperationalMode.Exit;
emit SetOperationalModeExitEvent();
}
/// @notice Return true if operational mode is Normal
function isOperationalModeNormal()
public
view
returns (bool)
{
return OperationalMode.Normal == operationalMode;
}
/// @notice Return true if operational mode is Exit
function isOperationalModeExit()
public
view
returns (bool)
{
return OperationalMode.Exit == operationalMode;
}
/// @notice Get the current value of update delay blocks
/// @return The value of update delay blocks
function updateDelayBlocks()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of update delay blocks values
/// @return The count of update delay blocks values
function updateDelayBlocksCount()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.count();
}
/// @notice Set the number of update delay blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newUpdateDelayBlocks The new update delay blocks value
function setUpdateDelayBlocks(uint256 fromBlockNumber, uint256 newUpdateDelayBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
updateDelayBlocksByBlockNumber.addEntry(fromBlockNumber, newUpdateDelayBlocks);
emit SetUpdateDelayBlocksEvent(fromBlockNumber, newUpdateDelayBlocks);
}
/// @notice Get the current value of confirmation blocks
/// @return The value of confirmation blocks
function confirmationBlocks()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of confirmation blocks values
/// @return The count of confirmation blocks values
function confirmationBlocksCount()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.count();
}
/// @notice Set the number of confirmation blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newConfirmationBlocks The new confirmation blocks value
function setConfirmationBlocks(uint256 fromBlockNumber, uint256 newConfirmationBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
confirmationBlocksByBlockNumber.addEntry(fromBlockNumber, newConfirmationBlocks);
emit SetConfirmationBlocksEvent(fromBlockNumber, newConfirmationBlocks);
}
/// @notice Get number of trade maker fee block number tiers
function tradeMakerFeesCount()
public
view
returns (uint256)
{
return tradeMakerFeeByBlockNumber.count();
}
/// @notice Get trade maker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeMakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeMakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade maker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeMakerFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeMakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of trade taker fee block number tiers
function tradeTakerFeesCount()
public
view
returns (uint256)
{
return tradeTakerFeeByBlockNumber.count();
}
/// @notice Get trade taker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeTakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeTakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade taker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeTakerFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeTakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers
function paymentFeesCount()
public
view
returns (uint256)
{
return paymentFeeByBlockNumber.count();
}
/// @notice Get payment relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function paymentFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return paymentFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setPaymentFee(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetPaymentFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers of given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment relative fee for given currency at given block number, possibly discounted by
/// discount tier value
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param discountTier The concerned discount tier
function currencyPaymentFee(uint256 blockNumber, address currencyCt, uint256 currencyId, int256 discountTier)
public
view
returns (int256)
{
if (0 < currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].discountedValueAt(
blockNumber, discountTier
);
else
return paymentFee(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values for given currency at given
/// block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setCurrencyPaymentFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] discountTiers, int256[] discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentFeeByBlockNumber[currencyCt][currencyId].addDiscountedEntry(
fromBlockNumber, nominal, discountTiers, discountValues
);
emit SetCurrencyPaymentFeeEvent(
fromBlockNumber, currencyCt, currencyId, nominal, discountTiers, discountValues
);
}
/// @notice Get number of minimum trade maker fee block number tiers
function tradeMakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeMakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade maker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeMakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeMakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade maker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeMakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeMakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum trade taker fee block number tiers
function tradeTakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeTakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade taker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeTakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeTakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade taker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeTakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeTakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers
function paymentMinimumFeesCount()
public
view
returns (uint256)
{
return paymentMinimumFeeByBlockNumber.count();
}
/// @notice Get payment minimum relative fee at given block number
/// @param blockNumber The concerned block number
function paymentMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return paymentMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set payment minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setPaymentMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetPaymentMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers for given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment minimum relative fee for given currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFee(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
if (0 < currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].valueAt(blockNumber);
else
return paymentMinimumFee(blockNumber);
}
/// @notice Set payment minimum relative fee for given currency at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Minimum relative fee
function setCurrencyPaymentMinimumFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].addEntry(fromBlockNumber, nominal);
emit SetCurrencyPaymentMinimumFeeEvent(fromBlockNumber, currencyCt, currencyId, nominal);
}
/// @notice Get number of fee currencies for the given reference currency
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrenciesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return feeCurrencyByCurrencyBlockNumber.count(MonetaryTypesLib.Currency(currencyCt, currencyId));
}
/// @notice Get the fee currency for the given reference currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrency(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (address ct, uint256 id)
{
MonetaryTypesLib.Currency storage _feeCurrency = feeCurrencyByCurrencyBlockNumber.currencyAt(
MonetaryTypesLib.Currency(currencyCt, currencyId), blockNumber
);
ct = _feeCurrency.ct;
id = _feeCurrency.id;
}
/// @notice Set the fee currency for the given reference currency at given block number
/// @param fromBlockNumber Block number from which the update applies
/// @param referenceCurrencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param referenceCurrencyId The ID of the concerned reference currency (0 for ETH and ERC20)
/// @param feeCurrencyCt The address of the concerned fee currency contract (address(0) == ETH)
/// @param feeCurrencyId The ID of the concerned fee currency (0 for ETH and ERC20)
function setFeeCurrency(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
feeCurrencyByCurrencyBlockNumber.addEntry(
fromBlockNumber,
MonetaryTypesLib.Currency(referenceCurrencyCt, referenceCurrencyId),
MonetaryTypesLib.Currency(feeCurrencyCt, feeCurrencyId)
);
emit SetFeeCurrencyEvent(fromBlockNumber, referenceCurrencyCt, referenceCurrencyId,
feeCurrencyCt, feeCurrencyId);
}
/// @notice Get the current value of wallet lock timeout
/// @return The value of wallet lock timeout
function walletLockTimeout()
public
view
returns (uint256)
{
return walletLockTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of wallet lock
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setWalletLockTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletLockTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetWalletLockTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of cancel order challenge timeout
/// @return The value of cancel order challenge timeout
function cancelOrderChallengeTimeout()
public
view
returns (uint256)
{
return cancelOrderChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of cancel order challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setCancelOrderChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
cancelOrderChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetCancelOrderChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of settlement challenge timeout
/// @return The value of settlement challenge timeout
function settlementChallengeTimeout()
public
view
returns (uint256)
{
return settlementChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of settlement challenges
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setSettlementChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
settlementChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetSettlementChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of fraud stake fraction
/// @return The value of fraud stake fraction
function fraudStakeFraction()
public
view
returns (uint256)
{
return fraudStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in fraud challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setFraudStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
fraudStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetFraudStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of wallet settlement stake fraction
/// @return The value of wallet settlement stake fraction
function walletSettlementStakeFraction()
public
view
returns (uint256)
{
return walletSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by wallet
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setWalletSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetWalletSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake fraction
/// @return The value of operator settlement stake fraction
function operatorSettlementStakeFraction()
public
view
returns (uint256)
{
return operatorSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
operatorSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetOperatorSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake
/// @return The value of operator settlement stake
function operatorSettlementStake()
public
view
returns (int256 amount, address currencyCt, uint256 currencyId)
{
MonetaryTypesLib.Figure storage stake = operatorSettlementStakeByBlockNumber.currentValue();
amount = stake.amount;
currencyCt = stake.currency.ct;
currencyId = stake.currency.id;
}
/// @notice Set figure of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeAmount The amount gained
/// @param stakeCurrencyCt The address of currency gained
/// @param stakeCurrencyId The ID of currency gained
function setOperatorSettlementStake(uint256 fromBlockNumber, int256 stakeAmount,
address stakeCurrencyCt, uint256 stakeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
MonetaryTypesLib.Figure memory stake = MonetaryTypesLib.Figure(stakeAmount, MonetaryTypesLib.Currency(stakeCurrencyCt, stakeCurrencyId));
operatorSettlementStakeByBlockNumber.addEntry(fromBlockNumber, stake);
emit SetOperatorSettlementStakeEvent(fromBlockNumber, stakeAmount, stakeCurrencyCt, stakeCurrencyId);
}
/// @notice Set the block number of the earliest settlement initiation
/// @param _earliestSettlementBlockNumber The block number of the earliest settlement
function setEarliestSettlementBlockNumber(uint256 _earliestSettlementBlockNumber)
public
onlyOperator
{
earliestSettlementBlockNumber = _earliestSettlementBlockNumber;
emit SetEarliestSettlementBlockNumberEvent(earliestSettlementBlockNumber);
}
/// @notice Disable further updates to the earliest settlement block number
/// @dev This operation can not be undone
function disableEarliestSettlementBlockNumberUpdate()
public
onlyOperator
{
earliestSettlementBlockNumberUpdateDisabled = true;
emit DisableEarliestSettlementBlockNumberUpdateEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDelayedBlockNumber(uint256 blockNumber) {
require(
0 == updateDelayBlocksByBlockNumber.count() ||
blockNumber >= block.number + updateDelayBlocksByBlockNumber.currentValue()
);
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that has a client fund property
*/
contract Configurable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Configuration public configuration;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetConfigurationEvent(Configuration oldConfiguration, Configuration newConfiguration);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the configuration contract
/// @param newConfiguration The (address of) Configuration contract instance
function setConfiguration(Configuration newConfiguration)
public
onlyDeployer
notNullAddress(newConfiguration)
notSameAddresses(newConfiguration, configuration)
{
// Set new configuration
Configuration oldConfiguration = configuration;
configuration = newConfiguration;
// Emit event
emit SetConfigurationEvent(oldConfiguration, newConfiguration);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier configurationInitialized() {
require(configuration != address(0));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length);
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency)
{
require(index < self.currencies.length);
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[])
{
require(0 < self.currencies.length);
require(low <= up);
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library NonFungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256[] ids;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256[])) idsByCurrency;
mapping(address => mapping(uint256 => mapping(int256 => uint256))) idIndexById;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[])
{
return self.idsByCurrency[currencyCt][currencyId];
}
function getByIndices(Balance storage self, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp)
internal
view
returns (int256[])
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length)
return new int256[](0);
indexUp = indexUp.clampMax(self.idsByCurrency[currencyCt][currencyId].length - 1);
int256[] memory idsByCurrency = new int256[](indexUp - indexLow + 1);
for (uint256 i = indexLow; i < indexUp; i++)
idsByCurrency[i - indexLow] = self.idsByCurrency[currencyCt][currencyId][i];
return idsByCurrency;
}
function idsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.idsByCurrency[currencyCt][currencyId].length;
}
function hasId(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 < self.idIndexById[currencyCt][currencyId][id];
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256[], uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (new int256[](0), 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256[], uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.ids, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[], uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.ids, record.blockNumber);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function set(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
{
int256[] memory ids = new int256[](1);
ids[0] = id;
set(self, ids, currencyCt, currencyId);
}
function set(Balance storage self, int256[] ids, address currencyCt, uint256 currencyId)
internal
{
uint256 i;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId] = ids;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = i + 1;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function reset(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
for (uint256 i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId].length = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
if (0 < self.idIndexById[currencyCt][currencyId][id])
return false;
self.idsByCurrency[currencyCt][currencyId].push(id);
self.idIndexById[currencyCt][currencyId][id] = self.idsByCurrency[currencyCt][currencyId].length;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function sub(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
uint256 index = self.idIndexById[currencyCt][currencyId][id];
if (0 == index)
return false;
if (index < self.idsByCurrency[currencyCt][currencyId].length) {
self.idsByCurrency[currencyCt][currencyId][index - 1] = self.idsByCurrency[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId].length - 1];
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][index - 1]] = index;
}
self.idsByCurrency[currencyCt][currencyId].length--;
self.idIndexById[currencyCt][currencyId][id] = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function transfer(Balance storage _from, Balance storage _to, int256 id,
address currencyCt, uint256 currencyId)
internal
returns (bool)
{
return sub(_from, id, currencyCt, currencyId) && add(_to, id, currencyCt, currencyId);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateInUseCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Balance tracker
* @notice An ownable to track balances of generic types
*/
contract BalanceTracker is Ownable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public DEPOSITED_BALANCE_TYPE = "deposited";
string constant public SETTLED_BALANCE_TYPE = "settled";
string constant public STAGED_BALANCE_TYPE = "staged";
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Wallet {
mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType;
mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bytes32 public depositedBalanceType;
bytes32 public settledBalanceType;
bytes32 public stagedBalanceType;
bytes32[] public _allBalanceTypes;
bytes32[] public _activeBalanceTypes;
bytes32[] public trackedBalanceTypes;
mapping(bytes32 => bool) public trackedBalanceTypeMap;
mapping(address => Wallet) private walletMap;
address[] public trackedWallets;
mapping(address => uint256) public trackedWalletIndexByWallet;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE));
settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE));
stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE));
_allBalanceTypes.push(settledBalanceType);
_allBalanceTypes.push(depositedBalanceType);
_allBalanceTypes.push(stagedBalanceType);
_activeBalanceTypes.push(settledBalanceType);
_activeBalanceTypes.push(depositedBalanceType);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the fungible balance (amount) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance (IDs) of the given wallet, type, currency and index range
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param indexLow The lower index of IDs
/// @param indexUp The upper index of IDs
/// @return The stored balance
function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 indexLow, uint256 indexUp)
public
view
returns (int256[])
{
return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices(
currencyCt, currencyId, indexLow, indexUp
);
}
/// @notice Get all the non-fungible balance (IDs) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[])
{
return walletMap[wallet].nonFungibleBalanceByType[_type].get(
currencyCt, currencyId
);
}
/// @notice Get the count of non-fungible IDs of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of IDs
function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount(
currencyCt, currencyId
);
}
/// @notice Gauge whether the ID is included in the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param id The ID of the concerned unit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if ID is included, else false
function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].hasId(
id, currencyCt, currencyId
);
}
/// @notice Set the balance of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if setting fungible balance, else false
function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Set the non-fungible balance IDs of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param ids The ids of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function setIds(address wallet, bytes32 _type, int256[] ids, address currencyCt, uint256 currencyId)
public
onlyActiveService
{
// Update the balance
walletMap[wallet].nonFungibleBalanceByType[_type].set(
ids, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Add the given value to the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to add
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if adding fungible balance, else false
function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Subtract the given value from the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to subtract
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if subtracting fungible balance, else false
function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Gauge whether this tracker has in-use data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId);
}
/// @notice Gauge whether this tracker has ever-used data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId);
}
/// @notice Get the count of fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the fungible balance record for the given wallet, type, currency
/// log entry index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of non-fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and record index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256[] ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256[] ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of tracked balance types
/// @return The count of tracked balance types
function trackedBalanceTypesCount()
public
view
returns (uint256)
{
return trackedBalanceTypes.length;
}
/// @notice Get the count of tracked wallets
/// @return The count of tracked wallets
function trackedWalletsCount()
public
view
returns (uint256)
{
return trackedWallets.length;
}
/// @notice Get the default full set of balance types
/// @return The set of all balance types
function allBalanceTypes()
public
view
returns (bytes32[])
{
return _allBalanceTypes;
}
/// @notice Get the default set of active balance types
/// @return The set of active balance types
function activeBalanceTypes()
public
view
returns (bytes32[])
{
return _activeBalanceTypes;
}
/// @notice Get the subset of tracked wallets in the given index range
/// @param low The lower index
/// @param up The upper index
/// @return The subset of tracked wallets
function trackedWalletsByIndices(uint256 low, uint256 up)
public
view
returns (address[])
{
require(0 < trackedWallets.length);
require(low <= up);
up = up.clampMax(trackedWallets.length - 1);
address[] memory _trackedWallets = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_trackedWallets[i - low] = trackedWallets[i];
return _trackedWallets;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _updateTrackedBalanceTypes(bytes32 _type)
private
{
if (!trackedBalanceTypeMap[_type]) {
trackedBalanceTypeMap[_type] = true;
trackedBalanceTypes.push(_type);
}
}
function _updateTrackedWallets(address wallet)
private
{
if (0 == trackedWalletIndexByWallet[wallet]) {
trackedWallets.push(wallet);
trackedWalletIndexByWallet[wallet] = trackedWallets.length;
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title BalanceTrackable
* @notice An ownable that has a balance tracker property
*/
contract BalanceTrackable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
BalanceTracker public balanceTracker;
bool public balanceTrackerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker);
event FreezeBalanceTrackerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the balance tracker contract
/// @param newBalanceTracker The (address of) BalanceTracker contract instance
function setBalanceTracker(BalanceTracker newBalanceTracker)
public
onlyDeployer
notNullAddress(newBalanceTracker)
notSameAddresses(newBalanceTracker, balanceTracker)
{
// Require that this contract has not been frozen
require(!balanceTrackerFrozen);
// Update fields
BalanceTracker oldBalanceTracker = balanceTracker;
balanceTracker = newBalanceTracker;
// Emit event
emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeBalanceTracker()
public
onlyDeployer
{
balanceTrackerFrozen = true;
// Emit event
emit FreezeBalanceTrackerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier balanceTrackerInitialized() {
require(balanceTracker != address(0));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NahmiiTypesLib
* @dev Data types of general nahmii character
*/
library NahmiiTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum ChallengePhase {Dispute, Closed}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OriginFigure {
uint256 originId;
MonetaryTypesLib.Figure figure;
}
struct IntendedConjugateCurrency {
MonetaryTypesLib.Currency intended;
MonetaryTypesLib.Currency conjugate;
}
struct SingleFigureTotalOriginFigures {
MonetaryTypesLib.Figure single;
OriginFigure[] total;
}
struct TotalOriginFigures {
OriginFigure[] total;
}
struct CurrentPreviousInt256 {
int256 current;
int256 previous;
}
struct SingleTotalInt256 {
int256 single;
int256 total;
}
struct IntendedConjugateCurrentPreviousInt256 {
CurrentPreviousInt256 intended;
CurrentPreviousInt256 conjugate;
}
struct IntendedConjugateSingleTotalInt256 {
SingleTotalInt256 intended;
SingleTotalInt256 conjugate;
}
struct WalletOperatorHashes {
bytes32 wallet;
bytes32 operator;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Seal {
bytes32 hash;
Signature signature;
}
struct WalletOperatorSeal {
Seal wallet;
Seal operator;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SettlementChallengeTypesLib
* @dev Types for settlement challenges
*/
library SettlementChallengeTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum Status {Qualified, Disqualified}
struct Proposal {
address wallet;
uint256 nonce;
uint256 referenceBlockNumber;
uint256 definitionBlockNumber;
uint256 expirationTime;
// Status
Status status;
// Amounts
Amounts amounts;
// Currency
MonetaryTypesLib.Currency currency;
// Info on challenged driip
Driip challenged;
// True is equivalent to reward coming from wallet's balance
bool walletInitiated;
// True if proposal has been terminated
bool terminated;
// Disqualification
Disqualification disqualification;
}
struct Amounts {
// Cumulative (relative) transfer info
int256 cumulativeTransfer;
// Stage info
int256 stage;
// Balances after amounts have been staged
int256 targetBalance;
}
struct Driip {
// Kind ("payment", "trade", ...)
string kind;
// Hash (of operator)
bytes32 hash;
}
struct Disqualification {
// Challenger
address challenger;
uint256 nonce;
uint256 blockNumber;
// Info on candidate driip
Driip candidate;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeState
* @notice Where null settlements challenge state is managed
*/
contract NullSettlementChallengeState is Ownable, Servable, Configurable, BalanceTrackable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event DisqualifyProposalEvent(address challengedWallet, uint256 challangedNonce, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if initiated by the concerned challenged wallet
function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency currency)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency currency, bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated);
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated);
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index);
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber,
proposals[index - 1].walletInitiated, challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal challenge nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].nonce;
}
/// @notice Get the settlement proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the settlement proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the settlement proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].status;
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].amounts.stage;
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the settlement proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].walletInitiated;
}
/// @notice Get the settlement proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the settlement proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the settlement proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the settlement proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the settlement proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency currency)
public
view
returns (string)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index);
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 referenceBlockNumber, bool walletInitiated)
private
{
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256());
require(targetBalanceAmount.isPositiveInt256());
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
}
function _removeProposal(uint256 index)
private
returns (bool)
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
function _activeBalanceLogEntry(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log record of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId
);
(int256 settledAmount, uint256 settledBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.settledBalanceType(), currencyCt, currencyId
);
// Set amount as the sum of deposited and settled
amount = depositedAmount.add(settledAmount);
// Set block number as the latest of deposited and settled
blockNumber = depositedBlockNumber > settledBlockNumber ? depositedBlockNumber : settledBlockNumber;
}
} | @notice Get the address of the destructor role @notice Disable self-destruction of this contract @dev This operation can not be undone Require that sender is the assigned destructor Disable self-destruction Emit event | {
require(destructor() == msg.sender);
selfDestructionDisabled = true;
emit SelfDestructionDisabledEvent(msg.sender);
}
| 415,179 | [
1,
967,
326,
1758,
434,
326,
23819,
280,
2478,
225,
10639,
365,
17,
5489,
313,
4062,
434,
333,
6835,
225,
1220,
1674,
848,
486,
506,
640,
8734,
12981,
716,
5793,
353,
326,
6958,
23819,
280,
10639,
365,
17,
5489,
313,
4062,
16008,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
288,
203,
3639,
2583,
12,
5489,
8813,
280,
1435,
422,
1234,
18,
15330,
1769,
203,
203,
3639,
365,
6305,
313,
4062,
8853,
273,
638,
31,
203,
203,
3639,
3626,
18954,
6305,
313,
4062,
8853,
1133,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol
pragma solidity ^0.4.21;
/**
* @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: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol
pragma solidity ^0.4.21;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\SafeERC20.sol
pragma solidity ^0.4.21;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
// File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\BasicToken.sol
pragma solidity ^0.4.21;
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\StandardToken.sol
pragma solidity ^0.4.21;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Basic.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Receiver.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
// File: node_modules\openzeppelin-solidity\contracts\AddressUtils.sol
pragma solidity ^0.4.21;
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721BasicToken.sol
pragma solidity ^0.4.21;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existance of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for a the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
// File: contracts\Strings.sol
pragma solidity ^0.4.23;
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint i) internal pure returns (string) {
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}
// File: contracts\DefinerBasicLoan.sol
pragma solidity ^0.4.23;
interface ERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string);
}
contract DefinerBasicLoan is ERC721BasicToken, ERC721Metadata {
using SafeERC20 for ERC20;
using SafeMath for uint;
enum States {
Init, //0
WaitingForLender, //1
WaitingForBorrower, //2
WaitingForCollateral, //3
WaitingForFunds, //4
Funded, //5
Finished, //6
Closed, //7
Default, //8
Cancelled //9
}
address public ownerAddress;
address public borrowerAddress;
address public lenderAddress;
string public loanId;
uint public endTime; // use to check default
uint public nextPaymentDateTime; // use to check default
uint public daysPerInstallment; // use to calculate next payment date
uint public totalLoanTerm; // in days
uint public borrowAmount; // total borrowed amount
uint public collateralAmount; // total collateral amount
uint public installmentAmount; // amount of each installment
uint public remainingInstallment; // total installment left
States public currentState = States.Init;
/**
* TODO: change address below to actual factory address after deployment
* address constant private factoryContract = 0x...
*/
address internal factoryContract; // = 0x38Bddc3793DbFb3dE178E3dE74cae2E223c02B85;
modifier onlyFactoryContract() {
require(factoryContract == 0 || msg.sender == factoryContract, "not factory contract");
_;
}
modifier atState(States state) {
require(state == currentState, "Invalid State");
_;
}
modifier onlyOwner() {
require(msg.sender == ownerAddress, "Invalid Owner Address");
_;
}
modifier onlyLender() {
require(msg.sender == lenderAddress || msg.sender == factoryContract, "Invalid Lender Address");
_;
}
modifier onlyBorrower() {
require(msg.sender == borrowerAddress || msg.sender == factoryContract, "Invalid Borrower Address");
_;
}
modifier notDefault() {
require(now < nextPaymentDateTime, "This Contract has not yet default");
require(now < endTime, "This Contract has not yet default");
_;
}
/**
* ERC721 Interface
*/
function name() public view returns (string _name)
{
return "DeFiner Contract";
}
function symbol() public view returns (string _symbol)
{
return "DFINC";
}
function tokenURI(uint256) public view returns (string)
{
return Strings.strConcat(
"https://api.definer.org/OKh4I2yYpKU8S2af/definer/api/v1.0/opensea/",
loanId
);
}
function transferFrom(address _from, address _to, uint256 _tokenId) public {
require(_from != address(0));
require(_to != address(0));
super.transferFrom(_from, _to, _tokenId);
lenderAddress = tokenOwner[_tokenId];
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
lenderAddress = tokenOwner[_tokenId];
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
lenderAddress = tokenOwner[_tokenId];
}
/**
* Borrower transfer ETH to contract
*/
function transferCollateral() public payable /*atState(States.WaitingForCollateral)*/;
/**
* Check if borrower transferred correct amount of Token
*/
function checkCollateral() public /*atState(States.WaitingForCollateral)*/;
/**
* Borrower cancel the transaction is Default
*/
function borrowerCancel() public /*onlyLender atState(States.WaitingForLender)*/;
/**
* Lender cancel the transaction is Default
*/
function lenderCancel() public /*onlyLender atState(States.WaitingForBorrower)*/;
/**
* Lender transfer ETH to contract
*/
function transferFunds() public payable /*atState(States.WaitingForFunds)*/;
/**
* Check if lender transferred correct amount of Token
*/
function checkFunds() public /*atState(States.WaitingForFunds)*/;
/**
* Borrower pay back ETH or Token
*/
function borrowerMakePayment() public payable /*onlyBorrower atState(States.Funded) notDefault*/;
/**
* Borrower gets collateral back
*/
function borrowerReclaimCollateral() public /*onlyBorrower atState(States.Finished)*/;
/**
* Lender gets collateral when contract state is Default
*/
function lenderReclaimCollateral() public /*onlyLender atState(States.Default)*/;
/**
* Borrower accept loan
*/
function borrowerAcceptLoan() public atState(States.WaitingForBorrower) {
require(msg.sender != address(0), "Invalid address.");
borrowerAddress = msg.sender;
currentState = States.WaitingForCollateral;
}
/**
* Lender accept loan
*/
function lenderAcceptLoan() public atState(States.WaitingForLender) {
require(msg.sender != address(0), "Invalid address.");
lenderAddress = msg.sender;
currentState = States.WaitingForFunds;
}
function transferETHToBorrowerAndStartLoan() internal {
borrowerAddress.transfer(borrowAmount);
endTime = now.add(totalLoanTerm.mul(1 days));
nextPaymentDateTime = now.add(daysPerInstallment.mul(1 days));
currentState = States.Funded;
}
function transferTokenToBorrowerAndStartLoan(StandardToken token) internal {
require(token.transfer(borrowerAddress, borrowAmount), "Token transfer failed");
endTime = now.add(totalLoanTerm.mul(1 days));
nextPaymentDateTime = now.add(daysPerInstallment.mul(1 days));
currentState = States.Funded;
}
//TODO not in use yet
function checkDefault() public onlyLender atState(States.Funded) returns (bool) {
if (now > endTime || now > nextPaymentDateTime) {
currentState = States.Default;
return true;
} else {
return false;
}
}
// For testing
function forceDefault() public onlyOwner {
currentState = States.Default;
}
function getLoanDetails() public view returns (address,address,address,string,uint,uint,uint,uint,uint,uint,uint,uint,uint) {
// address public ownerAddress;
// address public borrowerAddress;
// address public lenderAddress;
// string public loanId;
// uint public endTime; // use to check default
// uint public nextPaymentDateTime; // use to check default
// uint public daysPerInstallment; // use to calculate next payment date
// uint public totalLoanTerm; // in days
// uint public borrowAmount; // total borrowed amount
// uint public collateralAmount; // total collateral amount
// uint public installmentAmount; // amount of each installment
// uint public remainingInstallment; // total installment left
// States public currentState = States.Init;
//
// return (
// nextPaymentDateTime,
// remainingInstallment,
// uint(currentState),
// loanId,
// borrowerAddress,
// lenderAddress
// );
return (
ownerAddress,
borrowerAddress,
lenderAddress,
loanId,
endTime,
nextPaymentDateTime,
daysPerInstallment,
totalLoanTerm,
borrowAmount,
collateralAmount,
installmentAmount,
remainingInstallment,
uint(currentState)
);
}
}
// File: contracts\ERC20ETHLoan.sol
pragma solidity ^0.4.23;
/**
* Collateral: ERC20 Token
* Borrowed: ETH
*/
contract ERC20ETHLoan is DefinerBasicLoan {
StandardToken token;
address public collateralTokenAddress;
/**
* NOT IN USE
* WHEN COLLATERAL IS TOKEN, TRANSFER IS DONE IN FRONT END
*/
function transferCollateral() public payable {
revert();
}
function establishContract() public {
// ERC20 as collateral
uint amount = token.balanceOf(address(this));
require(amount >= collateralAmount, "Insufficient collateral amount");
// Ether as Fund
require(address(this).balance >= borrowAmount, "Insufficient fund amount");
// Transit to Funded state
transferETHToBorrowerAndStartLoan();
}
/**
* NOT IN USE
* WHEN FUND IS ETH, CHECK IS DONE IN transferFunds()
*/
function checkFunds() onlyLender atState(States.WaitingForFunds) public {
return establishContract();
}
/**
* Check if borrower transferred correct amount of token to this contract
*/
function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) {
uint amount = token.balanceOf(address(this));
require(amount >= collateralAmount, "Insufficient collateral amount");
currentState = States.WaitingForLender;
}
/**
* Lender transfer ETH to fund this contract
*/
function transferFunds() public payable onlyLender atState(States.WaitingForFunds) {
if (address(this).balance >= borrowAmount) {
establishContract();
}
}
/*
* Borrower pay back ETH
*/
function borrowerMakePayment() public payable onlyBorrower atState(States.Funded) notDefault {
require(msg.value >= installmentAmount);
remainingInstallment--;
lenderAddress.transfer(installmentAmount);
if (remainingInstallment == 0) {
currentState = States.Finished;
} else {
nextPaymentDateTime = nextPaymentDateTime.add(daysPerInstallment.mul(1 days));
}
}
/*
* Borrower gets collateral token back when contract completed
*/
function borrowerReclaimCollateral() public onlyBorrower atState(States.Finished) {
uint amount = token.balanceOf(address(this));
token.transfer(borrowerAddress, amount);
currentState = States.Closed;
}
/*
* Lender gets collateral token when contract defaulted
*/
function lenderReclaimCollateral() public onlyLender atState(States.Default) {
uint amount = token.balanceOf(address(this));
token.transfer(lenderAddress, amount);
currentState = States.Closed;
}
}
// File: contracts\ERC20ETHLoanBorrower.sol
pragma solidity ^0.4.23;
/**
* Collateral: ERC20 Token
* Borrowed: ETH
*/
contract ERC20ETHLoanBorrower is ERC20ETHLoan {
function init (
address _ownerAddress,
address _borrowerAddress,
address _lenderAddress,
address _collateralTokenAddress,
uint _borrowAmount,
uint _paybackAmount,
uint _collateralAmount,
uint _daysPerInstallment,
uint _remainingInstallment,
string _loanId
) public onlyFactoryContract {
require(_collateralTokenAddress != address(0), "Invalid token address");
require(_borrowerAddress != address(0), "Invalid lender address");
require(_lenderAddress != address(0), "Invalid lender address");
require(_remainingInstallment > 0, "Invalid number of installments");
require(_borrowAmount > 0, "Borrow amount must not be 0");
require(_paybackAmount > 0, "Payback amount must not be 0");
require(_collateralAmount > 0, "Collateral amount must not be 0");
super._mint(_lenderAddress, 1);
factoryContract = msg.sender;
ownerAddress = _ownerAddress;
loanId = _loanId;
collateralTokenAddress = _collateralTokenAddress;
borrowAmount = _borrowAmount;
collateralAmount = _collateralAmount;
totalLoanTerm = _remainingInstallment * _daysPerInstallment;
daysPerInstallment = _daysPerInstallment;
remainingInstallment = _remainingInstallment;
installmentAmount = _paybackAmount / _remainingInstallment;
token = StandardToken(_collateralTokenAddress);
borrowerAddress = _borrowerAddress;
lenderAddress = _lenderAddress;
// initialial state for borrower initiated ERC20 flow
currentState = States.WaitingForCollateral;
}
/**
* NOT IN USE
* WHEN FUND IS ETH, CHECK IS DONE IN transferFunds()
*/
function checkFunds() onlyLender atState(States.WaitingForFunds) public {
return establishContract();
}
/**
* Check if borrower transferred correct amount of token to this contract
*/
function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) {
uint amount = token.balanceOf(address(this));
require(amount >= collateralAmount, "Insufficient collateral amount");
currentState = States.WaitingForFunds;
}
/**
* Lender transfer ETH to fund this contract
*/
function transferFunds() public payable onlyLender atState(States.WaitingForFunds) {
if (address(this).balance >= borrowAmount) {
establishContract();
}
}
/*
* Borrower gets collateral token back when contract completed
*/
function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) {
uint amount = token.balanceOf(address(this));
token.transfer(borrowerAddress, amount);
currentState = States.Cancelled;
}
/*
* Lender gets funds token back when contract is cancelled
*/
function lenderCancel() public onlyLender atState(States.WaitingForCollateral) {
// For ETH leader, no way to cancel
revert();
}
}
// File: contracts\ERC20ETHLoanLender.sol
pragma solidity ^0.4.23;
/**
* Collateral: ERC20 Token
* Borrowed: ETH
*/
contract ERC20ETHLoanLender is ERC20ETHLoan {
function init (
address _ownerAddress,
address _borrowerAddress,
address _lenderAddress,
address _collateralTokenAddress,
uint _borrowAmount,
uint _paybackAmount,
uint _collateralAmount,
uint _daysPerInstallment,
uint _remainingInstallment,
string _loanId
) public onlyFactoryContract {
require(_collateralTokenAddress != address(0), "Invalid token address");
require(_borrowerAddress != address(0), "Invalid lender address");
require(_lenderAddress != address(0), "Invalid lender address");
require(_remainingInstallment > 0, "Invalid number of installments");
require(_borrowAmount > 0, "Borrow amount must not be 0");
require(_paybackAmount > 0, "Payback amount must not be 0");
require(_collateralAmount > 0, "Collateral amount must not be 0");
super._mint(_lenderAddress, 1);
factoryContract = msg.sender;
ownerAddress = _ownerAddress;
loanId = _loanId;
collateralTokenAddress = _collateralTokenAddress;
borrowAmount = _borrowAmount;
collateralAmount = _collateralAmount;
totalLoanTerm = _remainingInstallment * _daysPerInstallment;
daysPerInstallment = _daysPerInstallment;
remainingInstallment = _remainingInstallment;
installmentAmount = _paybackAmount / _remainingInstallment;
token = StandardToken(_collateralTokenAddress);
borrowerAddress = _borrowerAddress;
lenderAddress = _lenderAddress;
// initialial state for borrower initiated ERC20 flow
currentState = States.WaitingForFunds;
}
/**
* Check if borrower transferred correct amount of token to this contract
*/
function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) {
return establishContract();
}
/**
* Lender transfer ETH to fund this contract
*/
function transferFunds() public payable onlyLender atState(States.WaitingForFunds) {
if (address(this).balance >= borrowAmount) {
currentState = States.WaitingForCollateral;
}
}
/*
* Borrower gets collateral token back when contract completed
*/
function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) {
revert();
}
/*
* Lender gets funds token back when contract is cancelled
*/
function lenderCancel() public onlyLender atState(States.WaitingForCollateral) {
lenderAddress.transfer(address(this).balance);
currentState = States.Cancelled;
}
}
// File: contracts\ETHERC20Loan.sol
pragma solidity ^0.4.23;
/**
* Collateral: ETH
* Borrowed: ERC20 Token
*/
contract ETHERC20Loan is DefinerBasicLoan {
StandardToken token;
address public borrowedTokenAddress;
function establishContract() public {
// ERC20 as collateral
uint amount = token.balanceOf(address(this));
require(amount >= collateralAmount, "Insufficient collateral amount");
// Ether as Fund
require(address(this).balance >= borrowAmount, "Insufficient fund amount");
// Transit to Funded state
transferETHToBorrowerAndStartLoan();
}
/*
* Borrower pay back ERC20 Token
*/
function borrowerMakePayment() public payable onlyBorrower atState(States.Funded) notDefault {
require(remainingInstallment > 0, "No remaining installments");
require(installmentAmount > 0, "Installment amount must be non zero");
token.transfer(lenderAddress, installmentAmount);
remainingInstallment--;
if (remainingInstallment == 0) {
currentState = States.Finished;
} else {
nextPaymentDateTime = nextPaymentDateTime.add(daysPerInstallment.mul(1 days));
}
}
/*
* Borrower gets collateral ETH back when contract completed
*/
function borrowerReclaimCollateral() public onlyBorrower atState(States.Finished) {
borrowerAddress.transfer(address(this).balance);
currentState = States.Closed;
}
/*
* Lender gets collateral ETH when contract defaulted
*/
function lenderReclaimCollateral() public onlyLender atState(States.Default) {
lenderAddress.transfer(address(this).balance);
currentState = States.Closed;
}
}
// File: contracts\ETHERC20LoanBorrower.sol
pragma solidity ^0.4.23;
/**
* Collateral: ETH
* Borrowed: ERC20 Token
*/
contract ETHERC20LoanBorrower is ETHERC20Loan {
function init (
address _ownerAddress,
address _borrowerAddress,
address _lenderAddress,
address _borrowedTokenAddress,
uint _borrowAmount,
uint _paybackAmount,
uint _collateralAmount,
uint _daysPerInstallment,
uint _remainingInstallment,
string _loanId
) public onlyFactoryContract {
require(_borrowedTokenAddress != address(0), "Invalid token address");
require(_borrowerAddress != address(0), "Invalid lender address");
require(_lenderAddress != address(0), "Invalid lender address");
require(_remainingInstallment > 0, "Invalid number of installments");
require(_borrowAmount > 0, "Borrow amount must not be 0");
require(_paybackAmount > 0, "Payback amount must not be 0");
require(_collateralAmount > 0, "Collateral amount must not be 0");
super._mint(_lenderAddress, 1);
factoryContract = msg.sender;
ownerAddress = _ownerAddress;
loanId = _loanId;
borrowedTokenAddress = _borrowedTokenAddress;
borrowAmount = _borrowAmount;
collateralAmount = _collateralAmount;
totalLoanTerm = _remainingInstallment * _daysPerInstallment;
daysPerInstallment = _daysPerInstallment;
remainingInstallment = _remainingInstallment;
installmentAmount = _paybackAmount / _remainingInstallment;
token = StandardToken(_borrowedTokenAddress);
borrowerAddress = _borrowerAddress;
lenderAddress = _lenderAddress;
currentState = States.WaitingForCollateral;
}
/**
* Borrower transfer ETH to contract
*/
function transferCollateral() public payable atState(States.WaitingForCollateral) {
if (address(this).balance >= collateralAmount) {
currentState = States.WaitingForFunds;
}
}
/**
*
*/
function checkFunds() public onlyLender atState(States.WaitingForFunds) {
uint amount = token.balanceOf(address(this));
require(amount >= borrowAmount, "Insufficient borrowed amount");
transferTokenToBorrowerAndStartLoan(token);
}
/**
* NOT IN USE
* WHEN COLLATERAL IS ETH, CHECK IS DONE IN transferCollateral()
*/
function checkCollateral() public {
revert();
}
/**
* NOT IN USE
* WHEN FUND IS TOKEN, TRANSFER IS DONE IN FRONT END
*/
function transferFunds() public payable {
revert();
}
/*
* Borrower gets collateral ETH back when contract completed
*/
function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) {
borrowerAddress.transfer(address(this).balance);
currentState = States.Cancelled;
}
/*
* Borrower gets collateral ETH back when contract completed
*/
function lenderCancel() public onlyLender atState(States.WaitingForCollateral) {
revert();
}
}
// File: contracts\ETHERC20LoanLender.sol
pragma solidity ^0.4.23;
/**
* Collateral: ETH
* Borrowed: ERC20 Token
*/
contract ETHERC20LoanLender is ETHERC20Loan {
function init (
address _ownerAddress,
address _borrowerAddress,
address _lenderAddress,
address _borrowedTokenAddress,
uint _borrowAmount,
uint _paybackAmount,
uint _collateralAmount,
uint _daysPerInstallment,
uint _remainingInstallment,
string _loanId
) public onlyFactoryContract {
require(_borrowedTokenAddress != address(0), "Invalid token address");
require(_borrowerAddress != address(0), "Invalid lender address");
require(_lenderAddress != address(0), "Invalid lender address");
require(_remainingInstallment > 0, "Invalid number of installments");
require(_borrowAmount > 0, "Borrow amount must not be 0");
require(_paybackAmount > 0, "Payback amount must not be 0");
require(_collateralAmount > 0, "Collateral amount must not be 0");
super._mint(_lenderAddress, 1);
factoryContract = msg.sender;
ownerAddress = _ownerAddress;
loanId = _loanId;
borrowedTokenAddress = _borrowedTokenAddress;
borrowAmount = _borrowAmount;
collateralAmount = _collateralAmount;
totalLoanTerm = _remainingInstallment * _daysPerInstallment;
daysPerInstallment = _daysPerInstallment;
remainingInstallment = _remainingInstallment;
installmentAmount = _paybackAmount / _remainingInstallment;
token = StandardToken(_borrowedTokenAddress);
borrowerAddress = _borrowerAddress;
lenderAddress = _lenderAddress;
currentState = States.WaitingForFunds;
}
/**
* Borrower transfer ETH to contract
*/
function transferCollateral() public payable atState(States.WaitingForCollateral) {
require(address(this).balance >= collateralAmount, "Insufficient ETH collateral amount");
transferTokenToBorrowerAndStartLoan(token);
}
/**
*
*/
function checkFunds() public onlyLender atState(States.WaitingForFunds) {
uint amount = token.balanceOf(address(this));
require(amount >= borrowAmount, "Insufficient fund amount");
currentState = States.WaitingForCollateral;
}
/**
* NOT IN USE
* WHEN COLLATERAL IS ETH, CHECK IS DONE IN transferCollateral()
*/
function checkCollateral() public {
revert();
}
/**
* NOT IN USE
* WHEN FUND IS TOKEN, TRANSFER IS DONE IN FRONT END
*/
function transferFunds() public payable {
revert();
}
/*
* Borrower gets collateral ETH back when contract completed
*/
function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) {
revert();
}
/*
* Borrower gets collateral ETH back when contract completed
*/
function lenderCancel() public onlyLender atState(States.WaitingForCollateral) {
uint amount = token.balanceOf(address(this));
token.transfer(lenderAddress, amount);
currentState = States.Cancelled;
}
}
// File: contracts\ERC20ERC20Loan.sol
pragma solidity ^0.4.23;
/**
* Collateral: ERC20 Token
* Borrowed: ERC20 Token
*/
contract ERC20ERC20Loan is DefinerBasicLoan {
StandardToken collateralToken;
StandardToken borrowedToken;
address public collateralTokenAddress;
address public borrowedTokenAddress;
/*
* Borrower pay back Token
*/
function borrowerMakePayment() public payable onlyBorrower atState(States.Funded) notDefault {
require(remainingInstallment > 0, "No remaining installments");
require(installmentAmount > 0, "Installment amount must be non zero");
borrowedToken.transfer(lenderAddress, installmentAmount);
remainingInstallment--;
if (remainingInstallment == 0) {
currentState = States.Finished;
} else {
nextPaymentDateTime = nextPaymentDateTime.add(daysPerInstallment.mul(1 days));
}
}
/*
* Borrower gets collateral token back when contract completed
*/
function borrowerReclaimCollateral() public onlyBorrower atState(States.Finished) {
uint amount = collateralToken.balanceOf(address(this));
collateralToken.transfer(borrowerAddress, amount);
currentState = States.Closed;
}
/*
* Lender gets collateral token when contract defaulted
*/
function lenderReclaimCollateral() public onlyLender atState(States.Default) {
uint amount = collateralToken.balanceOf(address(this));
collateralToken.transfer(lenderAddress, amount);
currentState = States.Closed;
}
}
// File: contracts\ERC20ERC20LoanBorrower.sol
pragma solidity ^0.4.23;
/**
* Collateral: ERC20 Token
* Borrowed: ERC20 Token
*/
contract ERC20ERC20LoanBorrower is ERC20ERC20Loan {
function init (
address _ownerAddress,
address _borrowerAddress,
address _lenderAddress,
address _collateralTokenAddress,
address _borrowedTokenAddress,
uint _borrowAmount,
uint _paybackAmount,
uint _collateralAmount,
uint _daysPerInstallment,
uint _remainingInstallment,
string _loanId
) public onlyFactoryContract {
require(_collateralTokenAddress != _borrowedTokenAddress);
require(_collateralTokenAddress != address(0), "Invalid token address");
require(_borrowedTokenAddress != address(0), "Invalid token address");
require(_borrowerAddress != address(0), "Invalid lender address");
require(_lenderAddress != address(0), "Invalid lender address");
require(_remainingInstallment > 0, "Invalid number of installments");
require(_borrowAmount > 0, "Borrow amount must not be 0");
require(_paybackAmount > 0, "Payback amount must not be 0");
require(_collateralAmount > 0, "Collateral amount must not be 0");
super._mint(_lenderAddress, 1);
factoryContract = msg.sender;
ownerAddress = _ownerAddress;
loanId = _loanId;
collateralTokenAddress = _collateralTokenAddress;
borrowedTokenAddress = _borrowedTokenAddress;
borrowAmount = _borrowAmount;
collateralAmount = _collateralAmount;
totalLoanTerm = _remainingInstallment * _daysPerInstallment;
daysPerInstallment = _daysPerInstallment;
remainingInstallment = _remainingInstallment;
installmentAmount = _paybackAmount / _remainingInstallment;
collateralToken = StandardToken(_collateralTokenAddress);
borrowedToken = StandardToken(_borrowedTokenAddress);
borrowerAddress = _borrowerAddress;
lenderAddress = _lenderAddress;
currentState = States.WaitingForCollateral;
}
/**
* NOT IN USE
* WHEN COLLATERAL IS TOKEN, TRANSFER IS DONE IN FRONT END
*/
function transferCollateral() public payable {
revert();
}
/**
* NOT IN USE
* WHEN FUND IS TOKEN, TRANSFER IS DONE IN FRONT END
*/
function transferFunds() public payable {
revert();
}
/**
*
*/
function checkFunds() public onlyLender atState(States.WaitingForFunds) {
uint amount = borrowedToken.balanceOf(address(this));
require(amount >= borrowAmount, "Insufficient borrowed amount");
transferTokenToBorrowerAndStartLoan(borrowedToken);
}
/**
* Check if borrower transferred correct amount of token to this contract
*/
function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) {
uint amount = collateralToken.balanceOf(address(this));
require(amount >= collateralAmount, "Insufficient Collateral Token amount");
currentState = States.WaitingForFunds;
}
/*
* Borrower gets collateral token back when contract cancelled
*/
function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) {
uint amount = collateralToken.balanceOf(address(this));
collateralToken.transfer(borrowerAddress, amount);
currentState = States.Cancelled;
}
/*
* Lender gets fund token back when contract cancelled
*/
function lenderCancel() public onlyLender atState(States.WaitingForCollateral) {
revert();
}
}
// File: contracts\ERC20ERC20LoanLender.sol
pragma solidity ^0.4.23;
/**
* Collateral: ERC20 Token
* Borrowed: ERC20 Token
*/
contract ERC20ERC20LoanLender is ERC20ERC20Loan {
function init (
address _ownerAddress,
address _borrowerAddress,
address _lenderAddress,
address _collateralTokenAddress,
address _borrowedTokenAddress,
uint _borrowAmount,
uint _paybackAmount,
uint _collateralAmount,
uint _daysPerInstallment,
uint _remainingInstallment,
string _loanId
) public onlyFactoryContract {
require(_collateralTokenAddress != _borrowedTokenAddress);
require(_collateralTokenAddress != address(0), "Invalid token address");
require(_borrowedTokenAddress != address(0), "Invalid token address");
require(_borrowerAddress != address(0), "Invalid lender address");
require(_lenderAddress != address(0), "Invalid lender address");
require(_remainingInstallment > 0, "Invalid number of installments");
require(_borrowAmount > 0, "Borrow amount must not be 0");
require(_paybackAmount > 0, "Payback amount must not be 0");
require(_collateralAmount > 0, "Collateral amount must not be 0");
super._mint(_lenderAddress, 1);
factoryContract = msg.sender;
ownerAddress = _ownerAddress;
loanId = _loanId;
collateralTokenAddress = _collateralTokenAddress;
borrowedTokenAddress = _borrowedTokenAddress;
borrowAmount = _borrowAmount;
collateralAmount = _collateralAmount;
totalLoanTerm = _remainingInstallment * _daysPerInstallment;
daysPerInstallment = _daysPerInstallment;
remainingInstallment = _remainingInstallment;
installmentAmount = _paybackAmount / _remainingInstallment;
collateralToken = StandardToken(_collateralTokenAddress);
borrowedToken = StandardToken(_borrowedTokenAddress);
borrowerAddress = _borrowerAddress;
lenderAddress = _lenderAddress;
currentState = States.WaitingForFunds;
}
/**
* NOT IN USE
* WHEN COLLATERAL IS TOKEN, TRANSFER IS DONE IN FRONT END
*/
function transferCollateral() public payable {
revert();
}
/**
* NOT IN USE
* WHEN FUND IS TOKEN, TRANSFER IS DONE IN FRONT END
*/
function transferFunds() public payable {
revert();
}
/**
*
*/
function checkFunds() public onlyLender atState(States.WaitingForFunds) {
uint amount = borrowedToken.balanceOf(address(this));
require(amount >= borrowAmount, "Insufficient fund amount");
currentState = States.WaitingForCollateral;
}
/**
* Check if borrower transferred correct amount of token to this contract
*/
function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) {
uint amount = collateralToken.balanceOf(address(this));
require(amount >= collateralAmount, "Insufficient Collateral Token amount");
transferTokenToBorrowerAndStartLoan(borrowedToken);
}
/*
* Borrower gets collateral token back when contract cancelled
*/
function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) {
revert();
}
/*
* Lender gets fund token back when contract cancelled
*/
function lenderCancel() public onlyLender atState(States.WaitingForCollateral) {
uint amount = borrowedToken.balanceOf(address(this));
borrowedToken.transfer(lenderAddress, amount);
currentState = States.Cancelled;
}
}
// File: contracts\DefinerLoanFactory.sol
pragma solidity ^0.4.23;
library Library {
struct contractAddress {
address value;
bool exists;
}
}
contract CloneFactory {
event CloneCreated(address indexed target, address clone);
function createClone(address target) internal returns (address result) {
bytes memory clone = hex"3d602d80600a3d3981f3363d3d373d3d3d363d73bebebebebebebebebebebebebebebebebebebebe5af43d82803e903d91602b57fd5bf3";
bytes20 targetBytes = bytes20(target);
for (uint i = 0; i < 20; i++) {
clone[20 + i] = targetBytes[i];
}
assembly {
let len := mload(clone)
let data := add(clone, 0x20)
result := create(0, data, len)
}
}
}
contract DefinerLoanFactory is CloneFactory {
using Library for Library.contractAddress;
address public owner = msg.sender;
address public ERC20ETHLoanBorrowerMasterContractAddress;
address public ERC20ETHLoanLenderMasterContractAddress;
address public ETHERC20LoanBorrowerMasterContractAddress;
address public ETHERC20LoanLenderMasterContractAddress;
address public ERC20ERC20LoanBorrowerMasterContractAddress;
address public ERC20ERC20LoanLenderMasterContractAddress;
mapping(address => address[]) contractMap;
mapping(string => Library.contractAddress) contractById;
modifier onlyOwner() {
require(msg.sender == owner, "Invalid Owner Address");
_;
}
constructor (
address _ERC20ETHLoanBorrowerMasterContractAddress,
address _ERC20ETHLoanLenderMasterContractAddress,
address _ETHERC20LoanBorrowerMasterContractAddress,
address _ETHERC20LoanLenderMasterContractAddress,
address _ERC20ERC20LoanBorrowerMasterContractAddress,
address _ERC20ERC20LoanLenderMasterContractAddress
) public {
owner = msg.sender;
ERC20ETHLoanBorrowerMasterContractAddress = _ERC20ETHLoanBorrowerMasterContractAddress;
ERC20ETHLoanLenderMasterContractAddress = _ERC20ETHLoanLenderMasterContractAddress;
ETHERC20LoanBorrowerMasterContractAddress = _ETHERC20LoanBorrowerMasterContractAddress;
ETHERC20LoanLenderMasterContractAddress = _ETHERC20LoanLenderMasterContractAddress;
ERC20ERC20LoanBorrowerMasterContractAddress = _ERC20ERC20LoanBorrowerMasterContractAddress;
ERC20ERC20LoanLenderMasterContractAddress = _ERC20ERC20LoanLenderMasterContractAddress;
}
function getUserContracts(address userAddress) public view returns (address[]) {
return contractMap[userAddress];
}
function getContractByLoanId(string _loanId) public view returns (address) {
return contractById[_loanId].value;
}
function createERC20ETHLoanBorrowerClone(
address _collateralTokenAddress,
uint _borrowAmount,
uint _paybackAmount,
uint _collateralAmount,
uint _daysPerInstallment,
uint _remainingInstallment,
string _loanId,
address _lenderAddress
) public payable returns (address) {
require(!contractById[_loanId].exists, "contract already exists");
address clone = createClone(ERC20ETHLoanBorrowerMasterContractAddress);
ERC20ETHLoanBorrower(clone).init({
_ownerAddress : owner,
_borrowerAddress : msg.sender,
_lenderAddress : _lenderAddress,
_collateralTokenAddress : _collateralTokenAddress,
_borrowAmount : _borrowAmount,
_paybackAmount : _paybackAmount,
_collateralAmount : _collateralAmount,
_daysPerInstallment : _daysPerInstallment,
_remainingInstallment : _remainingInstallment,
_loanId : _loanId});
contractMap[msg.sender].push(clone);
contractById[_loanId] = Library.contractAddress(clone, true);
return clone;
}
function createERC20ETHLoanLenderClone(
address _collateralTokenAddress,
uint _borrowAmount,
uint _paybackAmount,
uint _collateralAmount,
uint _daysPerInstallment,
uint _remainingInstallment,
string _loanId,
address _borrowerAddress
) public payable returns (address) {
require(!contractById[_loanId].exists, "contract already exists");
address clone = createClone(ERC20ETHLoanLenderMasterContractAddress);
ERC20ETHLoanLender(clone).init({
_ownerAddress : owner,
_borrowerAddress : _borrowerAddress,
_lenderAddress : msg.sender,
_collateralTokenAddress : _collateralTokenAddress,
_borrowAmount : _borrowAmount,
_paybackAmount : _paybackAmount,
_collateralAmount : _collateralAmount,
_daysPerInstallment : _daysPerInstallment,
_remainingInstallment : _remainingInstallment,
_loanId : _loanId});
if (msg.value > 0) {
ERC20ETHLoanLender(clone).transferFunds.value(msg.value)();
}
contractMap[msg.sender].push(clone);
contractById[_loanId] = Library.contractAddress(clone, true);
return clone;
}
function createETHERC20LoanBorrowerClone(
address _borrowedTokenAddress,
uint _borrowAmount,
uint _paybackAmount,
uint _collateralAmount,
uint _daysPerInstallment,
uint _remainingInstallment,
string _loanId,
address _lenderAddress
) public payable returns (address) {
require(!contractById[_loanId].exists, "contract already exists");
address clone = createClone(ETHERC20LoanBorrowerMasterContractAddress);
ETHERC20LoanBorrower(clone).init({
_ownerAddress : owner,
_borrowerAddress : msg.sender,
_lenderAddress : _lenderAddress,
_borrowedTokenAddress : _borrowedTokenAddress,
_borrowAmount : _borrowAmount,
_paybackAmount : _paybackAmount,
_collateralAmount : _collateralAmount,
_daysPerInstallment : _daysPerInstallment,
_remainingInstallment : _remainingInstallment,
_loanId : _loanId});
if (msg.value >= _collateralAmount) {
ETHERC20LoanBorrower(clone).transferCollateral.value(msg.value)();
}
contractMap[msg.sender].push(clone);
contractById[_loanId] = Library.contractAddress(clone, true);
return clone;
}
function createETHERC20LoanLenderClone(
address _borrowedTokenAddress,
uint _borrowAmount,
uint _paybackAmount,
uint _collateralAmount,
uint _daysPerInstallment,
uint _remainingInstallment,
string _loanId,
address _borrowerAddress
) public payable returns (address) {
require(!contractById[_loanId].exists, "contract already exists");
address clone = createClone(ETHERC20LoanLenderMasterContractAddress);
ETHERC20LoanLender(clone).init({
_ownerAddress : owner,
_borrowerAddress : _borrowerAddress,
_lenderAddress : msg.sender,
_borrowedTokenAddress : _borrowedTokenAddress,
_borrowAmount : _borrowAmount,
_paybackAmount : _paybackAmount,
_collateralAmount : _collateralAmount,
_daysPerInstallment : _daysPerInstallment,
_remainingInstallment : _remainingInstallment,
_loanId : _loanId});
contractMap[msg.sender].push(clone);
contractById[_loanId] = Library.contractAddress(clone, true);
return clone;
}
function createERC20ERC20LoanBorrowerClone(
address _collateralTokenAddress,
address _borrowedTokenAddress,
uint _borrowAmount,
uint _paybackAmount,
uint _collateralAmount,
uint _daysPerInstallment,
uint _remainingInstallment,
string _loanId,
address _lenderAddress
) public returns (address) {
require(!contractById[_loanId].exists, "contract already exists");
address clone = createClone(ERC20ERC20LoanBorrowerMasterContractAddress);
ERC20ERC20LoanBorrower(clone).init({
_ownerAddress : owner,
_borrowerAddress : msg.sender,
_lenderAddress : _lenderAddress,
_collateralTokenAddress : _collateralTokenAddress,
_borrowedTokenAddress : _borrowedTokenAddress,
_borrowAmount : _borrowAmount,
_paybackAmount : _paybackAmount,
_collateralAmount : _collateralAmount,
_daysPerInstallment : _daysPerInstallment,
_remainingInstallment : _remainingInstallment,
_loanId : _loanId});
contractMap[msg.sender].push(clone);
contractById[_loanId] = Library.contractAddress(clone, true);
return clone;
}
function createERC20ERC20LoanLenderClone(
address _collateralTokenAddress,
address _borrowedTokenAddress,
uint _borrowAmount,
uint _paybackAmount,
uint _collateralAmount,
uint _daysPerInstallment,
uint _remainingInstallment,
string _loanId,
address _borrowerAddress
) public returns (address) {
require(!contractById[_loanId].exists, "contract already exists");
address clone = createClone(ERC20ERC20LoanLenderMasterContractAddress);
ERC20ERC20LoanLender(clone).init({
_ownerAddress : owner,
_borrowerAddress : _borrowerAddress,
_lenderAddress : msg.sender,
_collateralTokenAddress : _collateralTokenAddress,
_borrowedTokenAddress : _borrowedTokenAddress,
_borrowAmount : _borrowAmount,
_paybackAmount : _paybackAmount,
_collateralAmount : _collateralAmount,
_daysPerInstallment : _daysPerInstallment,
_remainingInstallment : _remainingInstallment,
_loanId : _loanId});
contractMap[msg.sender].push(clone);
contractById[_loanId] = Library.contractAddress(clone, true);
return clone;
}
function changeOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
} | * NOT IN USE WHEN COLLATERAL IS ETH, CHECK IS DONE IN transferCollateral()/ | function checkCollateral() public {
revert();
}
| 1,755,032 | [
1,
4400,
2120,
14988,
29707,
5597,
12190,
654,
1013,
4437,
512,
2455,
16,
14565,
4437,
26346,
2120,
7412,
13535,
2045,
287,
1435,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
866,
13535,
2045,
287,
1435,
1071,
288,
203,
565,
15226,
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
] |
./partial_match/1/0x1201FAa7258A48b820619dD57Cd8FdEb25D49b2c/sources/@balancer-labs/v2-pool-utils/contracts/RecoveryMode.sol | * @dev Reverts if the contract is in Recovery Mode./ | modifier whenNotInRecoveryMode() {
_ensureNotInRecoveryMode();
_;
}
| 4,227,966 | [
1,
426,
31537,
309,
326,
6835,
353,
316,
23675,
8126,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
1347,
21855,
11548,
2309,
1435,
288,
203,
3639,
389,
15735,
21855,
11548,
2309,
5621,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-only
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../common/financial-product-libraries/long-short-pair-libraries/LongShortPairFinancialProductLibrary.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../common/interfaces/AddressWhitelistInterface.sol";
import "../../oracle/interfaces/FinderInterface.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
/**
* @title Long Short Pair.
* @notice Uses a combination of long and short tokens to tokenize the bounded price exposure to a given identifier.
*/
contract LongShortPair is Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/*********************************************
* LONG SHORT PAIR DATA STRUCTURES *
*********************************************/
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
struct ConstructorParams {
string pairName; // Name of the long short pair contract.
uint64 expirationTimestamp; // Unix timestamp of when the contract will expire.
uint256 collateralPerPair; // How many units of collateral are required to mint one pair of synthetic tokens.
bytes32 priceIdentifier; // Price identifier, registered in the DVM for the long short pair.
ExpandedIERC20 longToken; // Token used as long in the LSP. Mint and burn rights needed by this contract.
ExpandedIERC20 shortToken; // Token used as short in the LSP. Mint and burn rights needed by this contract.
IERC20 collateralToken; // Collateral token used to back LSP synthetics.
LongShortPairFinancialProductLibrary financialProductLibrary; // Contract providing settlement payout logic.
bytes customAncillaryData; // Custom ancillary data to be passed along with the price request to the OO.
uint256 prepaidProposerReward; // Preloaded reward to incentivize settlement price proposals.
uint256 optimisticOracleLivenessTime; // OO liveness time for price requests.
uint256 optimisticOracleProposerBond; // OO proposer bond for price requests.
FinderInterface finder; // DVM finder to find other UMA ecosystem contracts.
address timerAddress; // Timer used to synchronize contract time in testing. Set to 0x000... in production.
}
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
// @dev note contractState and expirationTimestamp are declared in this order so they use the same storage slot.
ContractState public contractState;
uint64 public expirationTimestamp;
string public pairName;
// Amount of collateral a pair of tokens is always redeemable for.
uint256 public collateralPerPair;
// Price returned from the Optimistic oracle at settlement time.
int256 public expiryPrice;
// Number between 0 and 1e18 to allocate collateral between long & short tokens at redemption. 0 entitles each short
// to collateralPerPair and long worth 0. 1e18 makes each long worth collateralPerPair and short 0.
uint256 public expiryPercentLong;
bytes32 public priceIdentifier;
IERC20 public collateralToken;
ExpandedIERC20 public longToken;
ExpandedIERC20 public shortToken;
FinderInterface public finder;
LongShortPairFinancialProductLibrary public financialProductLibrary;
// Optimistic oracle customization parameters.
bytes public customAncillaryData;
uint256 public prepaidProposerReward;
uint256 public optimisticOracleLivenessTime;
uint256 public optimisticOracleProposerBond;
/****************************************
* EVENTS *
****************************************/
event TokensCreated(address indexed sponsor, uint256 indexed collateralUsed, uint256 indexed tokensMinted);
event TokensRedeemed(address indexed sponsor, uint256 indexed collateralReturned, uint256 indexed tokensRedeemed);
event ContractExpired(address indexed caller);
event PositionSettled(address indexed sponsor, uint256 collateralReturned, uint256 longTokens, uint256 shortTokens);
/****************************************
* MODIFIERS *
****************************************/
modifier preExpiration() {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
_;
}
modifier postExpiration() {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
_;
}
modifier onlyOpenState() {
require(contractState == ContractState.Open, "Contract state is not Open");
_;
}
/**
* @notice Construct the LongShortPair
* @param params Constructor params used to initialize the LSP. Key-valued object with the following structure:
* pairName: Name of the long short pair contract.
* expirationTimestamp: Unix timestamp of when the contract will expire.
* collateralPerPair: How many units of collateral are required to mint one pair of synthetic tokens.
* priceIdentifier: Price identifier, registered in the DVM for the long short pair.
* longToken: Token used as long in the LSP. Mint and burn rights needed by this contract.
* shortToken: Token used as short in the LSP. Mint and burn rights needed by this contract.
* collateralToken: Collateral token used to back LSP synthetics.
* financialProductLibrary: Contract providing settlement payout logic.
* customAncillaryData: Custom ancillary data to be passed along with the price request to the OO.
* prepaidProposerReward: Preloaded reward to incentivize settlement price proposals.
* optimisticOracleLivenessTime: OO liveness time for price requests.
* optimisticOracleProposerBond: OO proposer bond for price requests.
* finder: DVM finder to find other UMA ecosystem contracts.
* timerAddress: Timer used to synchronize contract time in testing. Set to 0x000... in production.
*/
constructor(ConstructorParams memory params) Testable(params.timerAddress) {
finder = params.finder;
require(bytes(params.pairName).length > 0, "Pair name cant be empty");
require(params.expirationTimestamp > getCurrentTime(), "Expiration timestamp in past");
require(params.collateralPerPair > 0, "Collateral per pair cannot be 0");
require(_getIdentifierWhitelist().isIdentifierSupported(params.priceIdentifier), "Identifier not registered");
require(address(_getOptimisticOracle()) != address(0), "Invalid finder");
require(address(params.financialProductLibrary) != address(0), "Invalid FinancialProductLibrary");
require(_getCollateralWhitelist().isOnWhitelist(address(params.collateralToken)), "Collateral not whitelisted");
require(params.optimisticOracleLivenessTime > 0, "OO liveness cannot be 0");
require(params.optimisticOracleLivenessTime < 5200 weeks, "OO liveness too large");
pairName = params.pairName;
expirationTimestamp = params.expirationTimestamp;
collateralPerPair = params.collateralPerPair;
priceIdentifier = params.priceIdentifier;
longToken = params.longToken;
shortToken = params.shortToken;
collateralToken = params.collateralToken;
financialProductLibrary = params.financialProductLibrary;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(
optimisticOracle.stampAncillaryData(params.customAncillaryData, address(this)).length <=
optimisticOracle.ancillaryBytesLimit(),
"Ancillary Data too long"
);
customAncillaryData = params.customAncillaryData;
prepaidProposerReward = params.prepaidProposerReward;
optimisticOracleLivenessTime = params.optimisticOracleLivenessTime;
optimisticOracleProposerBond = params.optimisticOracleProposerBond;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Creates a pair of long and short tokens equal in number to tokensToCreate. Pulls the required collateral
* amount into this contract, defined by the collateralPerPair value.
* @dev The caller must approve this contract to transfer `tokensToCreate * collateralPerPair` amount of collateral.
* @param tokensToCreate number of long and short synthetic tokens to create.
* @return collateralUsed total collateral used to mint the synthetics.
*/
function create(uint256 tokensToCreate) public preExpiration() nonReentrant() returns (uint256 collateralUsed) {
// Note the use of mulCeil to prevent small collateralPerPair causing rounding of collateralUsed to 0 enabling
// callers to mint dust LSP tokens without paying any collateral.
collateralUsed = FixedPoint.Unsigned(tokensToCreate).mulCeil(FixedPoint.Unsigned(collateralPerPair)).rawValue;
collateralToken.safeTransferFrom(msg.sender, address(this), collateralUsed);
require(longToken.mint(msg.sender, tokensToCreate));
require(shortToken.mint(msg.sender, tokensToCreate));
emit TokensCreated(msg.sender, collateralUsed, tokensToCreate);
}
/**
* @notice Redeems a pair of long and short tokens equal in number to tokensToRedeem. Returns the commensurate
* amount of collateral to the caller for the pair of tokens, defined by the collateralPerPair value.
* @dev This contract must have the `Burner` role for the `longToken` and `shortToken` in order to call `burnFrom`.
* @dev The caller does not need to approve this contract to transfer any amount of `tokensToRedeem` since long
* and short tokens are burned, rather than transferred, from the caller.
* @param tokensToRedeem number of long and short synthetic tokens to redeem.
* @return collateralReturned total collateral returned in exchange for the pair of synthetics.
*/
function redeem(uint256 tokensToRedeem) public nonReentrant() returns (uint256 collateralReturned) {
require(longToken.burnFrom(msg.sender, tokensToRedeem));
require(shortToken.burnFrom(msg.sender, tokensToRedeem));
collateralReturned = FixedPoint.Unsigned(tokensToRedeem).mul(FixedPoint.Unsigned(collateralPerPair)).rawValue;
collateralToken.safeTransfer(msg.sender, collateralReturned);
emit TokensRedeemed(msg.sender, collateralReturned, tokensToRedeem);
}
/**
* @notice Settle long and/or short tokens in for collateral at a rate informed by the contract settlement.
* @dev Uses financialProductLibrary to compute the redemption rate between long and short tokens.
* @dev This contract must have the `Burner` role for the `longToken` and `shortToken` in order to call `burnFrom`.
* @dev The caller does not need to approve this contract to transfer any amount of `tokensToRedeem` since long
* and short tokens are burned, rather than transferred, from the caller.
* @param longTokensToRedeem number of long tokens to settle.
* @param shortTokensToRedeem number of short tokens to settle.
* @return collateralReturned total collateral returned in exchange for the pair of synthetics.
*/
function settle(uint256 longTokensToRedeem, uint256 shortTokensToRedeem)
public
postExpiration()
nonReentrant()
returns (uint256 collateralReturned)
{
// If the contract state is open and postExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired contract");
// Get the current settlement price and store it. If it is not resolved, will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePriceExpiration(expirationTimestamp);
// Cap the return value at 1.
expiryPercentLong = Math.min(
financialProductLibrary.percentageLongCollateralAtExpiry(expiryPrice),
FixedPoint.fromUnscaledUint(1).rawValue
);
contractState = ContractState.ExpiredPriceReceived;
}
require(longToken.burnFrom(msg.sender, longTokensToRedeem));
require(shortToken.burnFrom(msg.sender, shortTokensToRedeem));
// expiryPercentLong is a number between 0 and 1e18. 0 means all collateral goes to short tokens and 1e18 means
// all collateral goes to the long token. Total collateral returned is the sum of payouts.
uint256 longCollateralRedeemed =
FixedPoint
.Unsigned(longTokensToRedeem)
.mul(FixedPoint.Unsigned(collateralPerPair))
.mul(FixedPoint.Unsigned(expiryPercentLong))
.rawValue;
uint256 shortCollateralRedeemed =
FixedPoint
.Unsigned(shortTokensToRedeem)
.mul(FixedPoint.Unsigned(collateralPerPair))
.mul(FixedPoint.fromUnscaledUint(1).sub(FixedPoint.Unsigned(expiryPercentLong)))
.rawValue;
collateralReturned = longCollateralRedeemed + shortCollateralRedeemed;
collateralToken.safeTransfer(msg.sender, collateralReturned);
emit PositionSettled(msg.sender, collateralReturned, longTokensToRedeem, shortTokensToRedeem);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
function expire() public postExpiration() onlyOpenState() nonReentrant() {
_requestOraclePriceExpiration();
contractState = ContractState.ExpiredPriceRequested;
emit ContractExpired(msg.sender);
}
/****************************************
* GLOBAL ACCESSORS FUNCTIONS *
****************************************/
/**
* @notice Returns the number of long and short tokens a sponsor wallet holds.
* @param sponsor address of the sponsor to query.
* @return [uint256, uint256]. First is long tokens held by sponsor and second is short tokens held by sponsor.
*/
function getPositionTokens(address sponsor) public view nonReentrantView() returns (uint256, uint256) {
return (longToken.balanceOf(sponsor), shortToken.balanceOf(sponsor));
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (int256) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(optimisticOracle.hasPrice(address(this), priceIdentifier, requestedTime, customAncillaryData));
int256 oraclePrice = optimisticOracle.settleAndGetPrice(priceIdentifier, requestedTime, customAncillaryData);
return oraclePrice;
}
function _requestOraclePriceExpiration() internal {
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Use the prepaidProposerReward as the proposer reward.
if (prepaidProposerReward > 0) collateralToken.safeApprove(address(optimisticOracle), prepaidProposerReward);
optimisticOracle.requestPrice(
priceIdentifier,
expirationTimestamp,
customAncillaryData,
collateralToken,
prepaidProposerReward
);
// Set the Optimistic oracle liveness for the price request.
optimisticOracle.setCustomLiveness(
priceIdentifier,
expirationTimestamp,
customAncillaryData,
optimisticOracleLivenessTime
);
// Set the Optimistic oracle proposer bond for the price request.
optimisticOracle.setBond(
priceIdentifier,
expirationTimestamp,
customAncillaryData,
optimisticOracleProposerBond
);
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getCollateralWhitelist() internal view returns (AddressWhitelistInterface) {
return AddressWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// 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) + 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
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import "../../../../common/implementation/FixedPoint.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
interface ExpiringContractInterface {
function expirationTimestamp() external view returns (uint256);
}
abstract contract LongShortPairFinancialProductLibrary {
function percentageLongCollateralAtExpiry(int256 expiryPrice) public view virtual returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import "./Timer.sol";
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run in production, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return block.timestamp; // solhint-disable-line not-rely-on-time
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
bool private _notEntered;
constructor() {
// Storing an initial non-zero value makes deployment a bit more expensive, but in exchange the refund on every
// call to nonReentrant will be lower in amount. Since refunds are capped to a 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.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant` function is not supported. It is possible to
* prevent this from happening by making the `nonReentrant` function external, and making it call a `private`
* function that does the actual state modification.
*/
modifier nonReentrant() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being
// re-entered. Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and
// then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes burn and mint methods.
*/
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @dev Burns `value` tokens owned by `recipient`.
* @param recipient address to burn tokens from.
* @param value amount of tokens to burn.
*/
function burnFrom(address recipient, uint256 value) external virtual returns (bool);
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function resetOwner(address account) external virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
interface AddressWhitelistInterface {
function addToWhitelist(address newElement) external;
function removeFromWhitelist(address newElement) external virtual;
function isOnWhitelist(address newElement) external view virtual returns (bool);
function getWhitelist() external view virtual returns (address[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OptimisticOracleInterface {
// Struct representing the state of a price request.
enum State {
Invalid, // Never requested.
Requested, // Requested, no other actions taken.
Proposed, // Proposed, but not expired or disputed yet.
Expired, // Proposed, not disputed, past liveness.
Disputed, // Disputed, but no DVM price returned yet.
Resolved, // Disputed and DVM price is available.
Settled // Final price has been set in the contract (can get here from Expired or Resolved).
}
// Struct representing a price request.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
bool refundOnDispute; // True if the requester should be refunded their reward on dispute.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length over a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was value (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
/**
* @notice Returns the state of a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State enum value.
*/
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
/**
* @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return true if price has resolved or settled, false otherwise.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
function stampAncillaryData(bytes memory ancillaryData, address requester)
public
view
virtual
returns (bytes memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
/**
* @title Interface for whitelists of supported identifiers that the oracle can provide prices for.
*/
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
bytes32 public constant OptimisticOracle = "OptimisticOracle";
bytes32 public constant Bridge = "Bridge";
bytes32 public constant GenericHandler = "GenericHandler";
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SignedSafeMath {
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
return a * b;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
return a / b;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
return a - b;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
return a + b;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() {
currentTime = block.timestamp; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the currentTime variable set in the Timer.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
| * @title Universal store of current contract time for testing environments./ | contract Timer {
uint256 private currentTime;
pragma solidity ^0.8.0;
constructor() {
}
function setCurrentTime(uint256 time) external {
currentTime = time;
}
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
| 148,354 | [
1,
984,
14651,
1707,
434,
783,
6835,
813,
364,
7769,
15900,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
12290,
288,
203,
565,
2254,
5034,
3238,
6680,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
3885,
1435,
288,
203,
565,
289,
203,
203,
565,
445,
12589,
950,
12,
11890,
5034,
813,
13,
3903,
288,
203,
3639,
6680,
273,
813,
31,
203,
565,
289,
203,
203,
565,
445,
5175,
950,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
6680,
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
] |
./partial_match/4/0x6d6B8E1B114A8B94050C955b689bF124651924D2/sources/PresaleRFIKUSH.sol | returns sorted token addresses, used to handle return values from pairs sorted in this order | library UniswapV2Library {
using SafeMath for uint;
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
))));
}
}
| 8,594,144 | [
1,
6154,
3115,
1147,
6138,
16,
1399,
358,
1640,
327,
924,
628,
5574,
3115,
316,
333,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
1351,
291,
91,
438,
58,
22,
9313,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
203,
565,
445,
1524,
5157,
12,
2867,
1147,
37,
16,
1758,
1147,
38,
13,
2713,
16618,
1135,
261,
2867,
1147,
20,
16,
1758,
1147,
21,
13,
288,
203,
3639,
2583,
12,
2316,
37,
480,
1147,
38,
16,
296,
984,
291,
91,
438,
58,
22,
9313,
30,
19768,
10109,
67,
8355,
7031,
1090,
55,
8284,
203,
3639,
261,
2316,
20,
16,
1147,
21,
13,
273,
1147,
37,
411,
1147,
38,
692,
261,
2316,
37,
16,
1147,
38,
13,
294,
261,
2316,
38,
16,
1147,
37,
1769,
203,
3639,
2583,
12,
2316,
20,
480,
1758,
12,
20,
3631,
296,
984,
291,
91,
438,
58,
22,
9313,
30,
18449,
67,
15140,
8284,
203,
565,
289,
203,
203,
565,
445,
3082,
1290,
12,
2867,
3272,
16,
1758,
1147,
37,
16,
1758,
1147,
38,
13,
2713,
16618,
1135,
261,
2867,
3082,
13,
288,
203,
3639,
261,
2867,
1147,
20,
16,
1758,
1147,
21,
13,
273,
1524,
5157,
12,
2316,
37,
16,
1147,
38,
1769,
203,
3639,
3082,
273,
1758,
12,
11890,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
203,
7734,
3827,
11,
1403,
2187,
203,
7734,
3272,
16,
203,
7734,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2316,
20,
16,
1147,
21,
13,
3631,
203,
5411,
262,
3719,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/11155111/0x5e7B837ACA749bf2A06947E4a411701EC0d00196/sources/src/Vault.sol | @notice Represents the maximum value of the locked-in profit ratio scale (where 1e18 is 100%). @notice Rewards contract where management fees are sent to. @notice Vault management fee (in BPS). @notice Arranged list of addresses of strategies, which defines the order for withdrawal. @notice The amount of funds that cannot be withdrawn by users. Decreases with time at the rate of "lockedProfitReleaseRate". @notice The rate of "lockedProfitBaseline" decline on the locked-in profit scale (scaled to 1e18). Represents the amount of funds that will be unlocked when one second passes. @notice Event that should happen when the strategy connects to the vault. @param strategy Address of the strategy contract. @param debtRatio Maximum portion of the loan that the strategy can take (in BPS). @notice Event that should happen when the strategy has been revoked from the vault. @param strategy Address of the strategy contract. @notice Event that should happen when the strategy has been removed from the vault. @param strategy Address of the strategy contract. @param fromQueueOnly If "true", then the strategy has only been removed from the withdrawal queue. @notice Event that should happen when the strategy has been returned to the withdrawal queue. @param strategy Address of the strategy contract. @notice Event that should happen when the locked-in profit release rate changed. @dev This empty reserved space is put in place to allow future versions to add new variables without shifting down storage in the inheritance chain. See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps @inheritdoc IVersionable | function version() external pure override returns (string memory) {
return "0.1.2";
}
| 3,791,712 | [
1,
23869,
87,
326,
4207,
460,
434,
326,
8586,
17,
267,
450,
7216,
7169,
3159,
261,
6051,
404,
73,
2643,
353,
2130,
9,
2934,
225,
534,
359,
14727,
6835,
1625,
11803,
1656,
281,
854,
3271,
358,
18,
225,
17329,
11803,
14036,
261,
267,
605,
5857,
2934,
225,
10371,
2330,
666,
434,
6138,
434,
20417,
16,
1492,
11164,
326,
1353,
364,
598,
9446,
287,
18,
225,
1021,
3844,
434,
284,
19156,
716,
2780,
506,
598,
9446,
82,
635,
3677,
18,
540,
31073,
3304,
598,
813,
622,
326,
4993,
434,
315,
15091,
626,
7216,
7391,
4727,
9654,
225,
1021,
4993,
434,
315,
15091,
626,
7216,
16635,
6,
3496,
558,
603,
326,
8586,
17,
267,
450,
7216,
3159,
261,
20665,
358,
404,
73,
2643,
2934,
540,
868,
6706,
87,
326,
3844,
434,
284,
19156,
716,
903,
506,
25966,
1347,
1245,
2205,
11656,
18,
225,
2587,
716,
1410,
5865,
1347,
326,
6252,
23441,
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,
1177,
1435,
3903,
16618,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
315,
20,
18,
21,
18,
22,
14432,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: BlueOak-1.0.0
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "contracts/p0/mixins/TradingLib.sol";
import "contracts/p0/mixins/Trading.sol";
import "contracts/interfaces/IAsset.sol";
import "contracts/interfaces/IAssetRegistry.sol";
import "contracts/interfaces/IBroker.sol";
import "contracts/interfaces/IMain.sol";
import "contracts/libraries/Fixed.sol";
/**
* @title BackingManager
* @notice The backing manager holds + manages the backing for an RToken
*/
contract BackingManagerP0 is TradingP0, IBackingManager {
using FixLib for uint192;
using SafeERC20 for IERC20;
uint32 public tradingDelay; // {s} how long to wait until resuming trading after switching
uint192 public backingBuffer; // {%} how much extra backing collateral to keep
function init(
IMain main_,
uint32 tradingDelay_,
uint192 backingBuffer_,
uint192 maxTradeSlippage_,
uint192 dustAmount_
) public initializer {
__Component_init(main_);
__Trading_init(maxTradeSlippage_, dustAmount_);
tradingDelay = tradingDelay_;
backingBuffer = backingBuffer_;
}
// Give RToken max allowance over a registered token
/// @custom:interaction
function grantRTokenAllowance(IERC20 erc20) external interaction {
require(main.assetRegistry().isRegistered(erc20), "erc20 unregistered");
erc20.approve(address(main.rToken()), type(uint256).max);
}
/// Mointain the overall backing policy; handout assets otherwise
/// @custom:interaction
function manageTokens(IERC20[] calldata erc20s) external interaction {
// Call keepers before
main.poke();
if (tradesOpen > 0) return;
// Do not trade when DISABLED or IFFY
require(main.basketHandler().status() == CollateralStatus.SOUND, "basket not sound");
(, uint256 basketTimestamp) = main.basketHandler().lastSet();
if (block.timestamp < basketTimestamp + tradingDelay) return;
if (main.basketHandler().fullyCapitalized()) {
handoutExcessAssets(erc20s);
} else {
/*
* Recapitalization Strategy
*
* Trading one at a time...
* 1. Make largest purchase possible on path towards rToken.basketsNeeded()
* a. Sell non-RSR assets first
* b. Sell RSR when no asset has a surplus > dust amount
* 2. When RSR holdings < dust:
* - Sell non-RSR surplus assets towards the Fallen Target
* 3. When this produces trade sizes < dust:
* - Set rToken.basketsNeeded() to basketsHeldBy(address(this))
*
* Fallen Target: The market-equivalent of all current holdings, in terms of BUs
* Note that the Fallen Target is freshly calculated during each pass
*/
/// Baskets Needed
/// |
/// |
/// |
/// 1a | 1b
/// |
/// |
/// |
/// |
/// non-RSR ------------------------------------------ RSR
/// |
/// |
/// |
/// |
/// 2 |
/// |
/// |
/// |
/// |
/// Fallen Target
// 1a
(bool doTrade, TradeRequest memory req) = nonRSRTrade(false);
if (!doTrade) {
// 1b
(doTrade, req) = rsrTrade();
}
if (!doTrade) {
// 2
(doTrade, req) = nonRSRTrade(true);
}
if (doTrade) {
tryTrade(req);
} else {
// 3
compromiseBasketsNeeded();
}
}
}
/// Send excess assets to the RSR and RToken traders
function handoutExcessAssets(IERC20[] calldata erc20s) private {
assert(main.basketHandler().status() == CollateralStatus.SOUND);
// Special-case RSR to forward to StRSR pool
uint256 rsrBal = main.rsr().balanceOf(address(this));
if (rsrBal > 0) {
main.rsr().safeTransfer(address(main.rsrTrader()), rsrBal);
}
// Mint revenue RToken
uint192 needed; // {BU}
{
IRToken rToken = main.rToken();
needed = rToken.basketsNeeded(); // {BU}
uint192 held = main.basketHandler().basketsHeldBy(address(this)); // {BU}
if (held.gt(needed)) {
int8 decimals = int8(rToken.decimals());
uint192 totalSupply = shiftl_toFix(rToken.totalSupply(), -decimals); // {rTok}
// {qRTok} = ({(BU - BU) * rTok / BU}) * {qRTok/rTok}
uint256 rTok = held.minus(needed).mulDiv(totalSupply, needed).shiftl_toUint(
decimals
);
rToken.mint(address(this), rTok);
rToken.setBasketsNeeded(held);
}
}
// Keep a small surplus of individual collateral
needed = main.rToken().basketsNeeded().mul(FIX_ONE.plus(backingBuffer));
// Handout excess assets above what is needed, including any newly minted RToken
RevenueTotals memory totals = main.distributor().totals();
for (uint256 i = 0; i < erc20s.length; i++) {
IAsset asset = main.assetRegistry().toAsset(erc20s[i]);
uint192 bal = asset.bal(address(this)); // {tok}
uint192 req = needed.mul(main.basketHandler().quantity(erc20s[i]), CEIL);
if (bal.gt(req)) {
// delta: {qTok}
uint256 delta = bal.minus(req).shiftl_toUint(int8(asset.erc20().decimals()));
uint256 tokensPerShare = delta / (totals.rTokenTotal + totals.rsrTotal);
{
uint256 toRSR = tokensPerShare * totals.rsrTotal;
if (toRSR > 0) erc20s[i].safeTransfer(address(main.rsrTrader()), toRSR);
}
{
uint256 toRToken = tokensPerShare * totals.rTokenTotal;
if (toRToken > 0)
erc20s[i].safeTransfer(address(main.rTokenTrader()), toRToken);
}
}
}
}
/// Prepare asset-for-collateral trade
/// @param useFallenTarget When true, trade towards a reduced BU target based on holdings
/// @return doTrade If the trade request should be performed
/// @return req The prepared trade request
function nonRSRTrade(bool useFallenTarget)
private
view
returns (bool doTrade, TradeRequest memory req)
{
assert(tradesOpen == 0 && !main.basketHandler().fullyCapitalized());
(
IAsset surplus,
ICollateral deficit,
uint192 surplusAmount,
uint192 deficitAmount
) = TradingLibP0.largestSurplusAndDeficit(useFallenTarget);
if (address(surplus) == address(0) || address(deficit) == address(0)) return (false, req);
// Of primary concern here is whether we can trust the prices for the assets
// we are selling. If we cannot, then we should not `prepareTradeToCoverDeficit`
if (
surplus.isCollateral() &&
main.assetRegistry().toColl(surplus.erc20()).status() == CollateralStatus.DISABLED
) {
(doTrade, req) = TradingLibP0.prepareTradeSell(surplus, deficit, surplusAmount);
req.minBuyAmount = 0;
} else {
(doTrade, req) = TradingLibP0.prepareTradeToCoverDeficit(
surplus,
deficit,
surplusAmount,
deficitAmount
);
}
if (req.sellAmount == 0) return (false, req);
return (doTrade, req);
}
/// Prepare a trade with seized RSR to buy for missing collateral
/// @return doTrade If the trade request should be performed
/// @return req The prepared trade request
function rsrTrade() private returns (bool doTrade, TradeRequest memory req) {
assert(tradesOpen == 0 && !main.basketHandler().fullyCapitalized());
require(main.assetRegistry().isRegistered(main.rsr()), "rsr unregistered");
IStRSR stRSR = main.stRSR();
IAsset rsrAsset = main.assetRegistry().toAsset(main.rsr());
(, ICollateral deficit, , uint192 deficitAmount) = TradingLibP0.largestSurplusAndDeficit(
false
);
if (address(deficit) == address(0)) return (false, req);
uint192 availableRSR = rsrAsset.bal(address(this)).plus(rsrAsset.bal(address(stRSR)));
(doTrade, req) = TradingLibP0.prepareTradeToCoverDeficit(
rsrAsset,
deficit,
availableRSR,
deficitAmount
);
if (doTrade) {
int8 decimals = int8(IERC20Metadata(address(main.rsr())).decimals());
uint256 rsrBal = rsrAsset.bal(address(this)).shiftl_toUint(decimals);
if (req.sellAmount > rsrBal) {
stRSR.seizeRSR(req.sellAmount - rsrBal);
}
}
return (doTrade, req);
}
/// Compromise on how many baskets are needed in order to recapitalize-by-accounting
function compromiseBasketsNeeded() private {
assert(tradesOpen == 0 && !main.basketHandler().fullyCapitalized());
main.rToken().setBasketsNeeded(main.basketHandler().basketsHeldBy(address(this)));
assert(main.basketHandler().fullyCapitalized());
}
// === Setters ===
/// @custom:governance
function setTradingDelay(uint32 val) external governance {
emit TradingDelaySet(tradingDelay, val);
tradingDelay = val;
}
/// @custom:governance
function setBackingBuffer(uint192 val) external governance {
emit BackingBufferSet(backingBuffer, val);
backingBuffer = val;
}
}
| {s} how long to wait until resuming trading after switching
| uint32 public tradingDelay; | 12,615,729 | [
1,
95,
87,
97,
3661,
1525,
358,
2529,
3180,
400,
21249,
1284,
7459,
1839,
30882,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
1578,
1071,
1284,
7459,
6763,
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
] |
pragma solidity ^0.4.16;
// SafeMath Taken From FirstBlood
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
// Ownership
contract Owned {
address public owner;
address public newOwner;
modifier onlyOwner { assert(msg.sender == owner); _; }
event OwnerUpdate(address _prevOwner, address _newOwner);
function Owned() {
owner = msg.sender;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
// ERC20 Interface
contract ERC20 {
function totalSupply() constant returns (uint _totalSupply);
function balanceOf(address _owner) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
// ERC20Token
contract ERC20Token is ERC20, SafeMath {
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalTokens;
uint256 public contributorTokens;
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
var _allowance = allowed[_from][msg.sender];
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function totalSupply() constant returns (uint256) {
return totalTokens;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Wolk is ERC20Token, Owned {
// TOKEN INFO
string public constant name = "WOLK TOKEN";
string public constant symbol = "WLK";
uint256 public constant decimals = 18;
// RESERVE
uint256 public reserveBalance = 0;
uint8 public percentageETHReserve = 5;
// CONTRACT OWNER
address public wolkInc;
// TOKEN GENERATION CONTROL
bool public allSaleCompleted = false;
modifier isTransferable { require(allSaleCompleted); _; }
// TOKEN GENERATION EVENTLOG
event WolkCreated(address indexed _to, uint256 _tokenCreated);
event WolkDestroyed(address indexed _from, uint256 _tokenDestroyed);
event LogRefund(address indexed _to, uint256 _value);
}
contract WolkTGE is Wolk {
// TOKEN GENERATION EVENT
mapping (address => uint256) contribution;
mapping (address => bool) whitelistContributor;
uint256 public constant tokenGenerationMin = 1 * 10**4 * 10**decimals;
uint256 public constant tokenGenerationMax = 175 * 10**5 * 10**decimals;
uint256 public start_block;
uint256 public end_time;
bool kycRequirement = true;
// @param _startBlock
// @param _endTime
// @param _wolkinc - wolk inc tokens sent here
// @return success
// @dev Wolk Genesis Event [only accessible by Contract Owner]
function wolkGenesis(uint256 _startBlock, uint256 _endTime, address _wolkinc) onlyOwner returns (bool success){
require((totalTokens < 1) && (block.number <= _startBlock));
start_block = _startBlock;
end_time = _endTime;
wolkInc = _wolkinc;
return true;
}
// @param _participants
// @return success
function updateRequireKYC(bool _kycRequirement) onlyOwner returns (bool success) {
kycRequirement = _kycRequirement;
return true;
}
// @param _participants
// @return success
function addParticipant(address[] _participants) onlyOwner returns (bool success) {
for (uint cnt = 0; cnt < _participants.length; cnt++){
whitelistContributor[_participants[cnt]] = true;
}
return true;
}
// @param _participants
// @return success
// @dev Revoke designated contributors [only accessible by current Contract Owner]
function removeParticipant(address[] _participants) onlyOwner returns (bool success){
for (uint cnt = 0; cnt < _participants.length; cnt++){
whitelistContributor[_participants[cnt]] = false;
}
return true;
}
// @param _participant
// @return status
// @dev return status of given address
function participantStatus(address _participant) constant returns (bool status) {
return(whitelistContributor[_participant]);
}
// @param _participant
// @dev use tokenGenerationEvent to handle sale of WOLK
function tokenGenerationEvent(address _participant) payable external {
require( ( whitelistContributor[_participant] || whitelistContributor[msg.sender] || balances[_participant] > 0 || kycRequirement ) && !allSaleCompleted && ( block.timestamp <= end_time ) && msg.value > 0);
uint256 rate = 1000; // Default Rate
rate = safeDiv( 175 * 10**5 * 10**decimals, safeAdd( 875 * 10**1 * 10**decimals, safeDiv( totalTokens, 2 * 10**3)) );
if ( rate > 2000 ) rate = 2000;
if ( rate < 500 ) rate = 500;
require(block.number >= start_block) ;
uint256 tokens = safeMul(msg.value, rate);
uint256 checkedSupply = safeAdd(totalTokens, tokens);
require(checkedSupply <= tokenGenerationMax);
totalTokens = checkedSupply;
contributorTokens = safeAdd(contributorTokens, tokens);
Transfer(address(this), _participant, tokens);
balances[_participant] = safeAdd(balances[_participant], tokens);
contribution[_participant] = safeAdd(contribution[_participant], msg.value);
WolkCreated(_participant, tokens); // logs token creation
}
function finalize() onlyOwner external {
require(!allSaleCompleted);
end_time = block.timestamp;
// 50MM Wolk allocated to Wolk Inc for development
uint256 wolkincTokens = 50 * 10**6 * 10**decimals;
balances[wolkInc] = wolkincTokens;
totalTokens = safeAdd(totalTokens, wolkincTokens);
WolkCreated(wolkInc, wolkincTokens); // logs token creation
allSaleCompleted = true;
reserveBalance = safeDiv(safeMul(contributorTokens, percentageETHReserve), 100000);
var withdrawalBalance = safeSub(this.balance, reserveBalance);
msg.sender.transfer(withdrawalBalance);
}
function refund() external {
require((contribution[msg.sender] > 0) && (!allSaleCompleted) && (block.timestamp > end_time) && (totalTokens < tokenGenerationMin));
uint256 tokenBalance = balances[msg.sender];
uint256 refundBalance = contribution[msg.sender];
balances[msg.sender] = 0;
contribution[msg.sender] = 0;
totalTokens = safeSub(totalTokens, tokenBalance);
WolkDestroyed(msg.sender, tokenBalance);
LogRefund(msg.sender, refundBalance);
msg.sender.transfer(refundBalance);
}
function transferAnyERC20Token(address _tokenAddress, uint256 _amount) onlyOwner returns (bool success) {
return ERC20(_tokenAddress).transfer(owner, _amount);
}
}
// Taken from https://github.com/bancorprotocol/contracts/blob/master/solidity/contracts/BancorFormula.sol
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint8 _reserveRatio, uint256 _depositAmount) public constant returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint8 _reserveRatio, uint256 _sellAmount) public constant returns (uint256);
}
contract WolkExchange is WolkTGE {
address public exchangeFormula;
bool public isPurchasePossible = false;
bool public isSellPossible = false;
modifier isPurchasable { require(isPurchasePossible && allSaleCompleted); _; }
modifier isSellable { require(isSellPossible && allSaleCompleted); _; }
// @param _newExchangeformula
// @return success
// @dev Set the bancor formula to use -- only Wolk Inc can set this
function setExchangeFormula(address _newExchangeformula) onlyOwner returns (bool success){
require(sellWolkEstimate(10**decimals, _newExchangeformula) > 0);
require(purchaseWolkEstimate(10**decimals, _newExchangeformula) > 0);
isPurchasePossible = false;
isSellPossible = false;
exchangeFormula = _newExchangeformula;
return true;
}
// @param _newReserveRatio
// @return success
// @dev Set the reserve ratio in case of emergency -- only Wolk Inc can set this
function updateReserveRatio(uint8 _newReserveRatio) onlyOwner returns (bool success) {
require(allSaleCompleted && ( _newReserveRatio > 1 ) && ( _newReserveRatio < 20 ) );
percentageETHReserve = _newReserveRatio;
return true;
}
// @param _isRunning
// @return success
// @dev updating isPurchasePossible -- only Wolk Inc can set this
function updatePurchasePossible(bool _isRunning) onlyOwner returns (bool success){
if (_isRunning){
require(sellWolkEstimate(10**decimals, exchangeFormula) > 0);
require(purchaseWolkEstimate(10**decimals, exchangeFormula) > 0);
}
isPurchasePossible = _isRunning;
return true;
}
// @param _isRunning
// @return success
// @dev updating isSellPossible -- only Wolk Inc can set this
function updateSellPossible(bool _isRunning) onlyOwner returns (bool success){
if (_isRunning){
require(sellWolkEstimate(10**decimals, exchangeFormula) > 0);
require(purchaseWolkEstimate(10**decimals, exchangeFormula) > 0);
}
isSellPossible = _isRunning;
return true;
}
function sellWolkEstimate(uint256 _wolkAmountest, address _formula) internal returns(uint256) {
uint256 ethReceivable = IBancorFormula(_formula).calculateSaleReturn(contributorTokens, reserveBalance, percentageETHReserve, _wolkAmountest);
return ethReceivable;
}
function purchaseWolkEstimate(uint256 _ethAmountest, address _formula) internal returns(uint256) {
uint256 wolkReceivable = IBancorFormula(_formula).calculatePurchaseReturn(contributorTokens, reserveBalance, percentageETHReserve, _ethAmountest);
return wolkReceivable;
}
// @param _wolkAmount
// @return ethReceivable
// @dev send Wolk into contract in exchange for eth, at an exchange rate based on the Bancor Protocol derivation and decrease totalSupply accordingly
function sellWolk(uint256 _wolkAmount) isSellable() returns(uint256) {
require((balances[msg.sender] >= _wolkAmount));
uint256 ethReceivable = sellWolkEstimate(_wolkAmount,exchangeFormula);
require(this.balance > ethReceivable);
balances[msg.sender] = safeSub(balances[msg.sender], _wolkAmount);
contributorTokens = safeSub(contributorTokens, _wolkAmount);
totalTokens = safeSub(totalTokens, _wolkAmount);
reserveBalance = safeSub(this.balance, ethReceivable);
WolkDestroyed(msg.sender, _wolkAmount);
Transfer(msg.sender, 0x00000000000000000000, _wolkAmount);
msg.sender.transfer(ethReceivable);
return ethReceivable;
}
// @return wolkReceivable
// @dev send eth into contract in exchange for Wolk tokens, at an exchange rate based on the Bancor Protocol derivation and increase totalSupply accordingly
function purchaseWolk(address _buyer) isPurchasable() payable returns(uint256){
require(msg.value > 0);
uint256 wolkReceivable = purchaseWolkEstimate(msg.value, exchangeFormula);
require(wolkReceivable > 0);
contributorTokens = safeAdd(contributorTokens, wolkReceivable);
totalTokens = safeAdd(totalTokens, wolkReceivable);
balances[_buyer] = safeAdd(balances[_buyer], wolkReceivable);
reserveBalance = safeAdd(reserveBalance, msg.value);
WolkCreated(_buyer, wolkReceivable);
Transfer(address(this),_buyer,wolkReceivable);
return wolkReceivable;
}
// @dev fallback function for purchase
// @note Automatically fallback to tokenGenerationEvent before sale is completed. After the token generation event, fallback to purchaseWolk. Liquidity exchange will be enabled through updateExchangeStatus
function () payable {
require(msg.value > 0);
if(!allSaleCompleted){
this.tokenGenerationEvent.value(msg.value)(msg.sender);
} else if ( block.timestamp >= end_time ){
this.purchaseWolk.value(msg.value)(msg.sender);
} else {
revert();
}
}
} | logs token creation
| WolkCreated(wolkInc, wolkincTokens); | 7,214,971 | [
1,
10011,
1147,
6710,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
678,
355,
79,
6119,
12,
91,
355,
79,
14559,
16,
341,
355,
79,
9523,
5157,
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
] |
./full_match/1/0x73cD8626b3cD47B009E68380720CFE6679A3Ec3D/sources/contracts/sharedContracts/PlanDelegator.sol | @notice internal function to update the storage of approvedDelegators and emit the event | function _approveDelegator(address delegator, uint256 planId) internal virtual {
_approvedDelegators[planId] = delegator;
emit DelegatorApproved(planId, ownerOf(planId), delegator);
}
| 4,922,714 | [
1,
7236,
445,
358,
1089,
326,
2502,
434,
20412,
15608,
3062,
471,
3626,
326,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12908,
537,
15608,
639,
12,
2867,
11158,
639,
16,
2254,
5034,
4995,
548,
13,
2713,
5024,
288,
203,
565,
389,
25990,
15608,
3062,
63,
7088,
548,
65,
273,
11158,
639,
31,
203,
565,
3626,
24117,
639,
31639,
12,
7088,
548,
16,
3410,
951,
12,
7088,
548,
3631,
11158,
639,
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
] |
// SPDX-License-Identifier: MIT
/*
* Contract by pr0xy.io
* _ _____ _ _____ ________ ___
* | || __ \| | | _ || _ | \/ |
* / __) | \/| | | | | || | | | . . |
* \__ \ | __ | | | | | || | | | |\/| |
* ( / |_\ \| |___\ \_/ /\ \_/ / | | |
* |_| \____/\_____/\___/ \___/\_| |_/
*/
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
// Collections Interface
interface DoomersGeneration {
function ownerOf(uint tokenId) external view returns (address);
}
contract GloomToken is ERC20, ERC20Burnable, Ownable, ReentrancyGuard {
// Storage of numerators for each generation
mapping(uint256 => uint256) public numerators;
// Storage of numerators for each generation
mapping(uint256 => uint256) public denominators;
// Storage of contract addresses for each generation
mapping(uint256 => address) public contracts;
// Storage of the block a token has been staked at
mapping(uint256 => mapping(uint256 => address)) public depositers;
// Storage of the block a token has been staked at
mapping(uint256 => mapping(uint256 => uint256)) public depositBlocks;
constructor() ERC20("GloomToken", "GLOOM") {}
// Sets the contract address for a given `_generation`
function setContract(uint256 _generation, address _contract) external onlyOwner {
contracts[_generation] = _contract;
}
// Sets the denominator of the rate of $GLOOM to reward for a given `_generation`
function setDenominator(uint256 _generation, uint256 _denominator) external onlyOwner {
denominators[_generation] = _denominator;
}
// Sets the numerator of the rate of $GLOOM to reward for a given `_generation`
function setNumerator(uint256 _generation, uint256 _numerator) external onlyOwner {
numerators[_generation] = _numerator;
}
// Mint function for owner
function mint(address to, uint256 amount) external onlyOwner {
_mint(to, amount);
}
// Allows token owners to claim $GLOOM from their staked tokens
function claim(uint256[] calldata _generations, uint256[] calldata _tokenIds) external nonReentrant() {
require(_generations.length == _tokenIds.length, 'Invalid Inputs');
uint256 reward;
for(uint256 i; i < _generations.length; i++){
require(depositers[_generations[i]][_tokenIds[i]] == msg.sender, 'False Deposit');
require(DoomersGeneration(contracts[_generations[i]]).ownerOf(_tokenIds[i]) == msg.sender, 'Sender Denied');
// Calculate staking reward
uint256 stakingPeriod = block.timestamp - depositBlocks[_generations[i]][_tokenIds[i]];
reward += (stakingPeriod * numerators[_generations[i]] / denominators[_generations[i]]);
// Reset staking period
depositers[_generations[i]][_tokenIds[i]] = msg.sender;
depositBlocks[_generations[i]][_tokenIds[i]] = block.timestamp;
}
// if there is a reward, mint it to the `sender`
_mint(msg.sender, reward * 1 ether);
}
// Returns a point in time rewards amount for provided tokens
function estimate(uint256[] calldata _generations, uint256[] calldata _tokenIds) external view returns (uint256){
require(_generations.length == _tokenIds.length, 'Invalid Inputs');
uint256 reward;
for(uint256 i; i < _generations.length; i++){
require(depositBlocks[_generations[i]][_tokenIds[i]] > 0 && depositers[_generations[i]][_tokenIds[i]] == msg.sender, 'Token Not Staked');
uint256 stakingPeriod = block.timestamp - depositBlocks[_generations[i]][_tokenIds[i]];
reward += (stakingPeriod * numerators[_generations[i]] / denominators[_generations[i]]);
}
return reward * 1 ether;
}
// Allows token owners to stake their tokens
function stake(uint256[] calldata _generations, uint256[] calldata _tokenIds) external nonReentrant() {
require(_generations.length == _tokenIds.length, 'Invalid Inputs');
for(uint256 i; i < _generations.length; i++){
require(DoomersGeneration(contracts[_generations[i]]).ownerOf(_tokenIds[i]) == msg.sender, 'Sender Denied');
require(!(depositBlocks[_generations[i]][_tokenIds[i]] > 0 && depositers[_generations[i]][_tokenIds[i]] == msg.sender), 'Token Staked');
depositers[_generations[i]][_tokenIds[i]] = msg.sender;
depositBlocks[_generations[i]][_tokenIds[i]] = block.timestamp;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC20.sol";
import "../../../utils/Context.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
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 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 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 Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | Storage of numerators for each generation Storage of numerators for each generation Storage of contract addresses for each generation Storage of the block a token has been staked at Storage of the block a token has been staked at Sets the contract address for a given `_generation` | contract GloomToken is ERC20, ERC20Burnable, Ownable, ReentrancyGuard {
mapping(uint256 => uint256) public numerators;
mapping(uint256 => uint256) public denominators;
mapping(uint256 => address) public contracts;
mapping(uint256 => mapping(uint256 => address)) public depositers;
mapping(uint256 => mapping(uint256 => uint256)) public depositBlocks;
constructor() ERC20("GloomToken", "GLOOM") {}
function setContract(uint256 _generation, address _contract) external onlyOwner {
contracts[_generation] = _contract;
}
function setDenominator(uint256 _generation, uint256 _denominator) external onlyOwner {
denominators[_generation] = _denominator;
}
function setNumerator(uint256 _generation, uint256 _numerator) external onlyOwner {
numerators[_generation] = _numerator;
}
function mint(address to, uint256 amount) external onlyOwner {
_mint(to, amount);
}
function claim(uint256[] calldata _generations, uint256[] calldata _tokenIds) external nonReentrant() {
require(_generations.length == _tokenIds.length, 'Invalid Inputs');
uint256 reward;
for(uint256 i; i < _generations.length; i++){
require(depositers[_generations[i]][_tokenIds[i]] == msg.sender, 'False Deposit');
require(DoomersGeneration(contracts[_generations[i]]).ownerOf(_tokenIds[i]) == msg.sender, 'Sender Denied');
uint256 stakingPeriod = block.timestamp - depositBlocks[_generations[i]][_tokenIds[i]];
reward += (stakingPeriod * numerators[_generations[i]] / denominators[_generations[i]]);
depositers[_generations[i]][_tokenIds[i]] = msg.sender;
depositBlocks[_generations[i]][_tokenIds[i]] = block.timestamp;
}
}
function claim(uint256[] calldata _generations, uint256[] calldata _tokenIds) external nonReentrant() {
require(_generations.length == _tokenIds.length, 'Invalid Inputs');
uint256 reward;
for(uint256 i; i < _generations.length; i++){
require(depositers[_generations[i]][_tokenIds[i]] == msg.sender, 'False Deposit');
require(DoomersGeneration(contracts[_generations[i]]).ownerOf(_tokenIds[i]) == msg.sender, 'Sender Denied');
uint256 stakingPeriod = block.timestamp - depositBlocks[_generations[i]][_tokenIds[i]];
reward += (stakingPeriod * numerators[_generations[i]] / denominators[_generations[i]]);
depositers[_generations[i]][_tokenIds[i]] = msg.sender;
depositBlocks[_generations[i]][_tokenIds[i]] = block.timestamp;
}
}
_mint(msg.sender, reward * 1 ether);
function estimate(uint256[] calldata _generations, uint256[] calldata _tokenIds) external view returns (uint256){
require(_generations.length == _tokenIds.length, 'Invalid Inputs');
uint256 reward;
for(uint256 i; i < _generations.length; i++){
require(depositBlocks[_generations[i]][_tokenIds[i]] > 0 && depositers[_generations[i]][_tokenIds[i]] == msg.sender, 'Token Not Staked');
uint256 stakingPeriod = block.timestamp - depositBlocks[_generations[i]][_tokenIds[i]];
reward += (stakingPeriod * numerators[_generations[i]] / denominators[_generations[i]]);
}
return reward * 1 ether;
}
function estimate(uint256[] calldata _generations, uint256[] calldata _tokenIds) external view returns (uint256){
require(_generations.length == _tokenIds.length, 'Invalid Inputs');
uint256 reward;
for(uint256 i; i < _generations.length; i++){
require(depositBlocks[_generations[i]][_tokenIds[i]] > 0 && depositers[_generations[i]][_tokenIds[i]] == msg.sender, 'Token Not Staked');
uint256 stakingPeriod = block.timestamp - depositBlocks[_generations[i]][_tokenIds[i]];
reward += (stakingPeriod * numerators[_generations[i]] / denominators[_generations[i]]);
}
return reward * 1 ether;
}
function stake(uint256[] calldata _generations, uint256[] calldata _tokenIds) external nonReentrant() {
require(_generations.length == _tokenIds.length, 'Invalid Inputs');
for(uint256 i; i < _generations.length; i++){
require(DoomersGeneration(contracts[_generations[i]]).ownerOf(_tokenIds[i]) == msg.sender, 'Sender Denied');
require(!(depositBlocks[_generations[i]][_tokenIds[i]] > 0 && depositers[_generations[i]][_tokenIds[i]] == msg.sender), 'Token Staked');
depositers[_generations[i]][_tokenIds[i]] = msg.sender;
depositBlocks[_generations[i]][_tokenIds[i]] = block.timestamp;
}
}
function stake(uint256[] calldata _generations, uint256[] calldata _tokenIds) external nonReentrant() {
require(_generations.length == _tokenIds.length, 'Invalid Inputs');
for(uint256 i; i < _generations.length; i++){
require(DoomersGeneration(contracts[_generations[i]]).ownerOf(_tokenIds[i]) == msg.sender, 'Sender Denied');
require(!(depositBlocks[_generations[i]][_tokenIds[i]] > 0 && depositers[_generations[i]][_tokenIds[i]] == msg.sender), 'Token Staked');
depositers[_generations[i]][_tokenIds[i]] = msg.sender;
depositBlocks[_generations[i]][_tokenIds[i]] = block.timestamp;
}
}
}
| 13,613,138 | [
1,
3245,
434,
26511,
3062,
364,
1517,
9377,
5235,
434,
26511,
3062,
364,
1517,
9377,
5235,
434,
6835,
6138,
364,
1517,
9377,
5235,
434,
326,
1203,
279,
1147,
711,
2118,
384,
9477,
622,
5235,
434,
326,
1203,
279,
1147,
711,
2118,
384,
9477,
622,
11511,
326,
6835,
1758,
364,
279,
864,
1375,
67,
25514,
68,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
611,
17810,
1345,
353,
4232,
39,
3462,
16,
4232,
39,
3462,
38,
321,
429,
16,
14223,
6914,
16,
868,
8230,
12514,
16709,
288,
203,
203,
225,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
1071,
26511,
3062,
31,
203,
203,
225,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
1071,
10716,
30425,
31,
203,
203,
225,
2874,
12,
11890,
5034,
516,
1758,
13,
1071,
20092,
31,
203,
203,
225,
2874,
12,
11890,
5034,
516,
2874,
12,
11890,
5034,
516,
1758,
3719,
1071,
443,
1724,
414,
31,
203,
203,
225,
2874,
12,
11890,
5034,
516,
2874,
12,
11890,
5034,
516,
2254,
5034,
3719,
1071,
443,
1724,
6450,
31,
203,
203,
203,
225,
3885,
1435,
4232,
39,
3462,
2932,
43,
17810,
1345,
3113,
315,
43,
1502,
1872,
7923,
2618,
203,
225,
445,
444,
8924,
12,
11890,
5034,
389,
25514,
16,
1758,
389,
16351,
13,
3903,
1338,
5541,
288,
203,
565,
20092,
63,
67,
25514,
65,
273,
389,
16351,
31,
203,
225,
289,
203,
203,
225,
445,
444,
8517,
26721,
12,
11890,
5034,
389,
25514,
16,
2254,
5034,
389,
13002,
26721,
13,
3903,
1338,
5541,
288,
203,
565,
10716,
30425,
63,
67,
25514,
65,
273,
389,
13002,
26721,
31,
203,
225,
289,
203,
203,
225,
445,
444,
2578,
7385,
12,
11890,
5034,
389,
25514,
16,
2254,
5034,
389,
2107,
7385,
13,
3903,
1338,
5541,
288,
203,
565,
26511,
3062,
63,
67,
25514,
65,
273,
389,
2107,
7385,
31,
203,
225,
289,
203,
203,
225,
445,
312,
474,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
3903,
2
] |
pragma solidity 0.8.10;
/***
*@title Liquidity Gauge
*@author InsureDAO
* SPDX-License-Identifier: MIT
*@notice Used for measuring liquidity and insurance
*/
//dao-contracts
import "./interfaces/dao/IGaugeController.sol";
import "./interfaces/dao/IInsureToken.sol";
import "./interfaces/dao/IMinter.sol";
import "./interfaces/dao/IVotingEscrow.sol";
import "./interfaces/pool/IOwnership.sol";
//libraries
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract LiquidityGauge is ReentrancyGuard {
event Deposit(address indexed provider, uint256 value);
event Withdraw(address indexed provider, uint256 value);
event UpdateLiquidityLimit(
address user,
uint256 original_balance,
uint256 original_supply,
uint256 working_balance,
uint256 working_supply,
uint256 voting_balance,
uint256 voting_total
);
uint256 constant TOKENLESS_PRODUCTION = 40;
uint256 constant BOOST_WARMUP = 86400 * 14;
uint256 constant WEEK = 604800;
//Contracts
IMinter public minter;
IInsureToken public insure_token;
IERC20 public template;
IGaugeController public controller;
IVotingEscrow public voting_escrow;
mapping(address => uint256) public balanceOf;
uint256 public totalSupply;
uint256 public future_epoch_time;
// caller -> recipient -> can deposit?
mapping(address => mapping(address => bool)) public approved_to_deposit;
mapping(address => uint256) public working_balances;
uint256 public working_supply;
// The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint
// All values are kept in units of being multiplied by 1e18
uint256 public period; //modified from "int256 public period" since it never be minus.
uint256[100000000000000000000000000000] public period_timestamp;
// 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint
uint256[100000000000000000000000000000] public integrate_inv_supply; // bump epoch when rate() changes. Iis(t)=int(r'(t)/S(t))dt (from CurveDAO whitepaper)
// 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint
mapping(address => uint256) public integrate_inv_supply_of;
mapping(address => uint256) public integrate_checkpoint_of;
// ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint
// Units rate * t = already number of coins per address to issue
mapping(address => uint256) public integrate_fraction; //Mintable Token amount (include minted amount)
uint256 public inflation_rate;
bool public is_killed;
IOwnership public immutable ownership;
modifier onlyOwner() {
require(
ownership.owner() == msg.sender,
"Caller is not allowed to operate"
);
_;
}
/***
*@notice Contract constructor
*@param _lp_addr Liquidity Pool contract address
*@param _minter Minter contract address
*@param _admin Admin who can kill the gauge
*/
constructor(
address _lp_addr,
address _minter,
address _ownership
) {
require(_lp_addr != address(0));
require(_minter != address(0));
template = IERC20(_lp_addr);
minter = IMinter(_minter);
address _insure_addr = minter.insure_token();
insure_token = IInsureToken(_insure_addr);
controller = IGaugeController(minter.gauge_controller());
voting_escrow = IVotingEscrow(controller.get_voting_escrow());
period_timestamp[0] = block.timestamp;
inflation_rate = insure_token.rate();
future_epoch_time = insure_token.future_epoch_time_write();
ownership = IOwnership(_ownership);
}
/***
*@notice Calculate limits which depend on the amount of INSURE Token per-user.
* Effectively it calculates working balances to apply amplification
* of INSURE production by INSURE
*@param _addr User address
*@param _l User's amount of liquidity (LP tokens)
*@param _L Total amount of liquidity (LP tokens)
*/
function _update_liquidity_limit(
address _addr,
uint256 _l,
uint256 _L
) internal {
// To be called after totalSupply is updated
uint256 _voting_balance = voting_escrow.balanceOf(
_addr,
block.timestamp
);
uint256 _voting_total = voting_escrow.totalSupply(block.timestamp);
uint256 _lim = (_l * TOKENLESS_PRODUCTION) / 100;
if (
(_voting_total > 0) &&
(block.timestamp > period_timestamp[0] + BOOST_WARMUP)
) {
_lim +=
(_L * _voting_balance * (100 - TOKENLESS_PRODUCTION)) /
_voting_total /
100;
}
_lim = min(_l, _lim);
uint256 _old_bal = working_balances[_addr];
working_balances[_addr] = _lim;
uint256 _working_supply = working_supply + _lim - _old_bal;
working_supply = _working_supply;
emit UpdateLiquidityLimit(
_addr,
_l,
_L,
_lim,
_working_supply,
_voting_balance,
_voting_total
);
}
//to avoid "stack too deep"
struct CheckPointParameters {
uint256 period;
uint256 period_time;
uint256 integrate_inv_supply;
uint256 rate;
uint256 new_rate;
uint256 prev_future_epoch;
uint256 working_balance;
uint256 working_supply;
}
/***
*@notice Checkpoint for a user
*@param _addr User address
*
*This function does,
*1. Calculate Iis for All: Calc and add Iis for every week. Iis only increses over time.
*2. Calculate Iu for _addr: Calc by (defferece between Iis(last time) and Iis(this time))* LP deposit amount of _addr(include INSURE locking boost)
*
* working_supply & working_balance = total_supply & total_balance with INSURE locking boost。
* Check whitepaper about Iis and Iu.
*/
function _checkpoint(address _addr) internal {
CheckPointParameters memory _st;
_st.period = period;
_st.period_time = period_timestamp[_st.period];
_st.integrate_inv_supply = integrate_inv_supply[_st.period];
_st.rate = inflation_rate;
_st.new_rate = _st.rate;
_st.prev_future_epoch = future_epoch_time;
if (_st.prev_future_epoch >= _st.period_time) {
//update future_epoch_time & inflation_rate
future_epoch_time = insure_token.future_epoch_time_write();
_st.new_rate = insure_token.rate();
inflation_rate = _st.new_rate;
}
controller.checkpoint_gauge(address(this));
uint256 _working_balance = working_balances[_addr];
uint256 _working_supply = working_supply;
if (is_killed) {
_st.rate = 0; // Stop distributing inflation as soon as killed
}
// Update integral of 1/supply
if (block.timestamp > _st.period_time) {
uint256 _prev_week_time = _st.period_time;
uint256 _week_time;
unchecked {
_week_time = min(
((_st.period_time + WEEK) / WEEK) * WEEK,
block.timestamp
);
}
for (uint256 i; i < 500;) {
uint256 _dt = _week_time - _prev_week_time;
uint256 _w = controller.gauge_relative_weight(
address(this),
(_prev_week_time / WEEK) * WEEK
);
if (_working_supply > 0) {
if (
_st.prev_future_epoch >= _prev_week_time &&
_st.prev_future_epoch < _week_time
) {
// If we went across one or multiple epochs, apply the rate
// of the first epoch until it ends, and then the rate of
// the last epoch.
// If more than one epoch is crossed - the gauge gets less,
// but that'd meen it wasn't called for more than 1 year
_st.integrate_inv_supply +=
(_st.rate *
_w *
(_st.prev_future_epoch - _prev_week_time)) /
_working_supply;
_st.rate = _st.new_rate;
_st.integrate_inv_supply +=
(_st.rate *
_w *
(_week_time - _st.prev_future_epoch)) /
_working_supply;
} else {
_st.integrate_inv_supply +=
(_st.rate * _w * _dt) /
_working_supply;
}
// On precisions of the calculation
// rate ~= 10e18
// last_weight > 0.01 * 1e18 = 1e16 (if pool weight is 1%)
// _working_supply ~= TVL * 1e18 ~= 1e26 ($100M for example)
// The largest loss is at dt = 1
// Loss is 1e-9 - acceptable
}
if (_week_time == block.timestamp) {
break;
}
_prev_week_time = _week_time;
_week_time = min(_week_time + WEEK, block.timestamp);
unchecked {
++i;
}
}
}
_st.period += 1;
period = _st.period;
period_timestamp[_st.period] = block.timestamp;
integrate_inv_supply[_st.period] = _st.integrate_inv_supply;
// Update user-specific integrals
// Calc the ΔIu of _addr and add it to Iu.
integrate_fraction[_addr] +=
(_working_balance *
(_st.integrate_inv_supply - integrate_inv_supply_of[_addr])) /
10 ** 18;
integrate_inv_supply_of[_addr] = _st.integrate_inv_supply;
integrate_checkpoint_of[_addr] = block.timestamp;
}
/***
*@notice Record a checkpoint for `_addr`
*@param _addr User address
*@return bool success
*/
function user_checkpoint(address _addr) external returns(bool) {
require(
(msg.sender == _addr) || (msg.sender == address(minter)),
"dev: unauthorized"
);
_checkpoint(_addr);
_update_liquidity_limit(_addr, balanceOf[_addr], totalSupply);
return true;
}
/***
*@notice Get the number of claimable tokens per user
*@dev This function should be manually changed to "view" in the ABI
*@return uint256 number of claimable tokens per user
*/
function claimable_tokens(address _addr) external returns(uint256) {
_checkpoint(_addr);
return (integrate_fraction[_addr] -
minter.minted(_addr, address(this)));
}
/***
*@notice Kick `_addr` for abusing their boost
*@dev Only if either they had another voting event, or their voting escrow lock expired
*@param _addr Address to kick
*/
function kick(address _addr) external {
uint256 _t_last = integrate_checkpoint_of[_addr];
uint256 _t_ve = voting_escrow.user_point_history__ts(
_addr,
voting_escrow.get_user_point_epoch(_addr)
);
uint256 _balance = balanceOf[_addr];
require(
voting_escrow.balanceOf(_addr, block.timestamp) == 0 ||
_t_ve > _t_last,
"dev: kick not allowed"
);
require(
working_balances[_addr] > (_balance * TOKENLESS_PRODUCTION) / 100,
"dev: kick not needed"
);
_checkpoint(_addr);
_update_liquidity_limit(_addr, balanceOf[_addr], totalSupply);
}
/***
*@notice Set whether `_addr` can deposit tokens for `msg.sender`
*@param _addr Address to set approval on
*@param can_deposit bool - can this account deposit for `msg.sender`?
*/
function set_approve_deposit(address _addr, bool can_deposit) external {
approved_to_deposit[_addr][msg.sender] = can_deposit;
}
/***
*@notice Deposit `_value` LP tokens
*@param _value Number of tokens to deposit
*@param _addr Address to deposit for
*/
function deposit(uint256 _value, address _addr) external nonReentrant {
if (_addr != msg.sender) {
require(approved_to_deposit[msg.sender][_addr], "Not approved");
}
_checkpoint(_addr);
if (_value != 0) {
uint256 _balance = balanceOf[_addr] + _value;
uint256 _supply = totalSupply + _value;
balanceOf[_addr] = _balance;
totalSupply = _supply;
_update_liquidity_limit(_addr, _balance, _supply);
require(template.transferFrom(msg.sender, address(this), _value));
}
emit Deposit(_addr, _value);
}
/***
*@notice Withdraw `_value` LP tokens
*@param _value Number of tokens to withdraw
*/
function withdraw(uint256 _value) external nonReentrant {
_checkpoint(msg.sender);
uint256 _balance = balanceOf[msg.sender] - _value;
uint256 _supply = totalSupply - _value;
balanceOf[msg.sender] = _balance;
totalSupply = _supply;
_update_liquidity_limit(msg.sender, _balance, _supply);
require(template.transfer(msg.sender, _value));
emit Withdraw(msg.sender, _value);
}
function integrate_checkpoint() external view returns(uint256) {
return period_timestamp[period];
}
function kill_me() external onlyOwner {
is_killed = !is_killed;
}
function min(uint256 a, uint256 b) internal pure returns(uint256) {
return a < b ? a : b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
interface IGaugeController {
function gauge_types(address _addr)external view returns(uint256);
function get_voting_escrow()external view returns(address);
function checkpoint_gauge(address addr)external;
function gauge_relative_weight(address addr, uint256 time)external view returns(uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
interface IInsureToken {
function mint(address _to, uint256 _value)external returns(bool);
function emergency_mint(uint256 _amountOut, address _to)external;
function approve(address _spender, uint256 _value)external;
function rate()external view returns(uint256);
function future_epoch_time_write() external returns(uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "./IGaugeController.sol";
interface IMinter {
function insure_token()external view returns(address);
function controller()external view returns(address);
function minted(address user, address gauge) external view returns(uint256);
function gauge_controller()external view returns(address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
interface IVotingEscrow {
function get_last_user_slope(address _addr) external view returns (uint256);
function locked__end(address _addr) external view returns (uint256);
function balanceOf(address _addr, uint256 _t)
external
view
returns (uint256);
//function balanceOf(address addr)external view returns (uint256);
function totalSupply(uint256 _t) external view returns (uint256);
function get_user_point_epoch(address _user)
external
view
returns (uint256);
function user_point_history__ts(address _addr, uint256 _idx)
external
view
returns (uint256);
}
pragma solidity 0.8.10;
//SPDX-License-Identifier: MIT
interface IOwnership {
function owner() external view returns (address);
function futureOwner() external view returns (address);
function commitTransferOwnership(address newOwner) external;
function acceptTransferOwnership() external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
} | **@notice Kick `_addr` for abusing their boost@dev Only if either they had another voting event, or their voting escrow lock expired@param _addr Address to kick/ | function kick(address _addr) external {
uint256 _t_last = integrate_checkpoint_of[_addr];
uint256 _t_ve = voting_escrow.user_point_history__ts(
_addr,
voting_escrow.get_user_point_epoch(_addr)
);
uint256 _balance = balanceOf[_addr];
require(
voting_escrow.balanceOf(_addr, block.timestamp) == 0 ||
_t_ve > _t_last,
"dev: kick not allowed"
);
require(
working_balances[_addr] > (_balance * TOKENLESS_PRODUCTION) / 100,
"dev: kick not needed"
);
_checkpoint(_addr);
_update_liquidity_limit(_addr, balanceOf[_addr], totalSupply);
}
| 618,733 | [
1,
47,
1200,
1375,
67,
4793,
68,
364,
1223,
9940,
3675,
14994,
5098,
309,
3344,
2898,
9323,
4042,
331,
17128,
871,
16,
578,
3675,
331,
17128,
2904,
492,
2176,
7708,
389,
4793,
5267,
358,
23228,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
23228,
12,
2867,
389,
4793,
13,
3903,
288,
203,
3639,
2254,
5034,
389,
88,
67,
2722,
273,
23367,
67,
25414,
67,
792,
63,
67,
4793,
15533,
203,
3639,
2254,
5034,
389,
88,
67,
537,
273,
331,
17128,
67,
742,
492,
18,
1355,
67,
1153,
67,
8189,
972,
3428,
12,
203,
5411,
389,
4793,
16,
203,
5411,
331,
17128,
67,
742,
492,
18,
588,
67,
1355,
67,
1153,
67,
12015,
24899,
4793,
13,
203,
3639,
11272,
203,
3639,
2254,
5034,
389,
12296,
273,
11013,
951,
63,
67,
4793,
15533,
203,
203,
3639,
2583,
12,
203,
5411,
331,
17128,
67,
742,
492,
18,
12296,
951,
24899,
4793,
16,
1203,
18,
5508,
13,
422,
374,
747,
203,
5411,
389,
88,
67,
537,
405,
389,
88,
67,
2722,
16,
203,
5411,
315,
5206,
30,
23228,
486,
2935,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
5960,
67,
70,
26488,
63,
67,
4793,
65,
405,
261,
67,
12296,
380,
14275,
26005,
67,
8025,
1212,
27035,
13,
342,
2130,
16,
203,
5411,
315,
5206,
30,
23228,
486,
3577,
6,
203,
3639,
11272,
203,
203,
3639,
389,
25414,
24899,
4793,
1769,
203,
3639,
389,
2725,
67,
549,
372,
24237,
67,
3595,
24899,
4793,
16,
11013,
951,
63,
67,
4793,
6487,
2078,
3088,
1283,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-06-15
*/
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol
// Subject to the MIT license.
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the 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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/[email protected]`.
*/
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/[email protected]`.
*/
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/[email protected]`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/// @notice Based on Compound Governance.
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 = 2 days;
uint public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint public delay;
/// @notice Internally tracks clone deployment under eip-1167 proxy pattern
bool private initialized;
mapping (bytes32 => bool) public queuedTransactions;
function init(address _admin, uint _delay) external {
require(!initialized, "initialized");
require(_delay >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");
require(_delay <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
admin = _admin;
delay = _delay;
initialized = true;
}
function() external payable { }
function setDelay(uint delay_) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NewDelay(delay);
}
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address pendingAdmin_) public {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint 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;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call.value(value)(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, value, signature, data, eta);
return returnData;
}
function getBlockTimestamp() internal view returns (uint) {
// solium-disable-next-line security/no-block-members
return block.timestamp;
}
}
/// @notice Based on Compound Governance.
contract GovernanceToken {
/// @notice EIP-20 token name for this token
string public name;
/// @notice EIP-20 token symbol for this token
string public symbol;
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply;
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account, string memory _name, string memory _symbol, uint _totalSupply) public {
balances[account] = uint96(_totalSupply);
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
emit Transfer(address(0), account, _totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comp::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce");
require(now <= expiry, "Comp::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
/// @notice Based on Compound Governance.
contract GovernorAlpha {
/// @notice The name of this contract
string public name;
/// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
uint public quorumVotes;
/// @notice The number of votes required in order for a voter to become a proposer
uint public proposalThreshold;
/// @notice The duration of voting on a proposal, in blocks
uint public votingPeriod;
/// @notice The maximum number of actions that can be included in a proposal
function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions
/// @notice The delay before voting on a proposal may take place, once proposed
function votingDelay() public pure returns (uint) { return 1; } // 1 block
/// @notice The address of the Governance Timelock
TimelockInterface public timelock;
/// @notice The address of the Governance token
CompInterface public token;
/// @notice The address of the Governance Guardian
address public guardian;
/// @notice The total number of proposals
uint public proposalCount;
/// @notice Internally tracks clone deployment under eip-1167 proxy pattern
bool private initialized;
struct Proposal {
/// @notice Unique id for looking up a proposal
uint id;
/// @notice Creator of the proposal
address proposer;
/// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds
uint eta;
/// @notice the ordered list of target addresses for calls to be made
address[] targets;
/// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint[] values;
/// @notice The ordered list of function signatures to be called
string[] signatures;
/// @notice The ordered list of calldata to be passed to each call
bytes[] calldatas;
/// @notice The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
/// @notice The block at which voting ends: votes must be cast prior to this block
uint endBlock;
/// @notice Current number of votes in favor of this proposal
uint forVotes;
/// @notice Current number of votes in opposition to this proposal
uint againstVotes;
/// @notice Flag marking whether the proposal has been canceled
bool canceled;
/// @notice Flag marking whether the proposal has been executed
bool executed;
/// @notice Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
/// @notice Whether or not a vote has been cast
bool hasVoted;
/// @notice Whether or not the voter supports the proposal
bool support;
/// @notice The number of votes the voter had, which were cast
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/// @notice The official record of all proposals ever proposed
mapping (uint => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping (address => uint) public latestProposalIds;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);
/// @notice An event emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint proposalId, bool support, uint votes);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint id, uint eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint id);
function init(address _timelock, address _token, address _guardian, string calldata _name, uint _quorumVotes, uint _proposalThreshold, uint _votingPeriod) external {
require(!initialized, "initialized");
timelock = TimelockInterface(_timelock);
token = CompInterface(_token);
guardian = _guardian;
name = _name;
quorumVotes = _quorumVotes;
proposalThreshold = _proposalThreshold;
votingPeriod = _votingPeriod;
initialized = true;
}
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
require(token.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold, "GovernorAlpha::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorAlpha::propose: must provide actions");
require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = add256(block.number, votingDelay());
uint endBlock = add256(startBlock, votingPeriod);
proposalCount++;
Proposal memory newProposal = Proposal({
id: proposalCount,
proposer: msg.sender,
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: startBlock,
endBlock: endBlock,
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
proposals[newProposal.id] = newProposal;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
function queue(uint proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
function execute(uint proposalId) public payable {
require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
function cancel(uint proposalId) public {
ProposalState state = state(proposalId);
require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == guardian || token.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold, "GovernorAlpha::cancel: proposer above threshold");
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function castVote(uint proposalId, bool support) public {
return _castVote(msg.sender, proposalId, support);
}
function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature");
return _castVote(signatory, proposalId, support);
}
function _castVote(address voter, uint proposalId, bool support) internal {
require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted");
uint96 votes = token.getPriorVotes(voter, proposal.startBlock);
if (support) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else {
proposal.againstVotes = add256(proposal.againstVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(voter, proposalId, support, votes);
}
function __acceptAdmin() public {
require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian");
timelock.acceptAdmin();
}
function __abdicate() public {
require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian");
guardian = address(0);
}
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function add256(uint256 a, uint256 b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainId() internal pure returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
interface TimelockInterface {
function delay() external view returns (uint);
function GRACE_PERIOD() external view returns (uint);
function acceptAdmin() external;
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32);
function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external;
function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory);
}
interface CompInterface {
function getPriorVotes(address account, uint blockNumber) external view returns (uint96);
}
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target) internal returns (address payable result) { // adapted for 'payable' clones
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
function isClone(address target, address query) internal view returns (bool result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000)
mstore(add(clone, 0xa), targetBytes)
mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
contract GovernanceFactory is CloneFactory {
address public timeLockTemplate;
address public governorAlphaTemplate;
event DeployGovernance(address indexed token, address indexed timelock, address indexed governor);
constructor(address _timeLockTemplate, address _governorAlphaTemplate) public {
timeLockTemplate = _timeLockTemplate;
governorAlphaTemplate = _governorAlphaTemplate;
}
function deployGovernance(address admin, string calldata _name, string calldata _symbol, uint _totalSupply, uint timeLockDelay, uint _quorumVotes, uint _proposalThreshold, uint _votingPeriod) external {
/// @dev Initialize governance token.
GovernanceToken token = new GovernanceToken(admin, _name, _symbol, _totalSupply);
/// @dev Initialize timelock clone.
address timelock = initTimeLock(admin, timeLockDelay);
/// @dev Initialize governor clone.
address governor = initGovernor(timelock, address(token), admin, _name, _quorumVotes, _proposalThreshold, _votingPeriod);
emit DeployGovernance(address(token), timelock, governor);
}
function initTimeLock(address admin, uint timeLockDelay) private returns (address payable timelock) {
timelock = address(createClone(timeLockTemplate));
Timelock(timelock).init(admin, timeLockDelay);
}
function initGovernor(address timelock, address token, address admin, string memory _name, uint _quorumVotes, uint _proposalThreshold, uint _votingPeriod) private returns (address governor) {
governor = address(GovernorAlpha(createClone(governorAlphaTemplate)));
GovernorAlpha(governor).init(timelock, token, admin, _name, _quorumVotes, _proposalThreshold, _votingPeriod);
}
} | @notice Based on Compound Governance. | contract GovernanceToken {
string public name;
string public symbol;
uint8 public constant decimals = 18;
uint public totalSupply;
mapping (address => mapping (address => uint96)) internal allowances;
mapping (address => uint96) internal balances;
mapping (address => address) public delegates;
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
mapping (address => uint32) public numCheckpoints;
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping (address => uint) public nonces;
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
constructor(address account, string memory _name, string memory _symbol, uint _totalSupply) public {
balances[account] = uint96(_totalSupply);
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
emit Transfer(address(0), account, _totalSupply);
}
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
} else {
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comp::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce");
require(now <= expiry, "Comp::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
} else if (cp.fromBlock < blockNumber) {
} else {
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
} else {
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
return chainId;
}
assembly { chainId := chainid() }
}
| 6,565,156 | [
1,
9802,
603,
21327,
611,
1643,
82,
1359,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
611,
1643,
82,
1359,
1345,
288,
203,
565,
533,
1071,
508,
31,
203,
203,
565,
533,
1071,
3273,
31,
203,
203,
565,
2254,
28,
1071,
5381,
15105,
273,
6549,
31,
203,
203,
565,
2254,
1071,
2078,
3088,
1283,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
10525,
3719,
2713,
1699,
6872,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
10525,
13,
2713,
324,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
1758,
13,
1071,
22310,
31,
203,
203,
565,
1958,
25569,
288,
203,
3639,
2254,
1578,
628,
1768,
31,
203,
3639,
2254,
10525,
19588,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
11890,
1578,
516,
25569,
3719,
1071,
26402,
31,
203,
565,
2874,
261,
2867,
516,
2254,
1578,
13,
1071,
818,
1564,
4139,
31,
203,
565,
1731,
1578,
1071,
5381,
27025,
67,
2399,
15920,
273,
417,
24410,
581,
5034,
2932,
41,
2579,
27,
2138,
3748,
12,
1080,
508,
16,
11890,
5034,
2687,
548,
16,
2867,
3929,
310,
8924,
2225,
1769,
203,
565,
1731,
1578,
1071,
5381,
2030,
19384,
2689,
67,
2399,
15920,
273,
417,
24410,
581,
5034,
2932,
26945,
12,
2867,
7152,
73,
16,
11890,
5034,
7448,
16,
11890,
5034,
10839,
2225,
1769,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
1661,
764,
31,
203,
565,
871,
27687,
5033,
12,
2867,
8808,
11158,
639,
16,
1758,
8808,
628,
9586,
16,
1758,
8808,
358,
9586,
1769,
203,
565,
871,
27687,
29637,
5033,
2
] |
/*
Telegram Link: https://t.me/pronitz
Website Link: https://pronitz.com
pragma solidity ^0.8.07;
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);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
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;
}
}
library Address {
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);
}
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");
}
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");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IWETH {
function deposit() external payable;
function balanceOf(address _owner) external returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function withdraw(uint256 _amount) external;
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() external virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
//The following line avoids exploiting previous lock/unlock to regain ownership
_previousOwner = address(0);
}
function transferOwnership(address newOwner) external virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract Chinu is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcludedFromReward;
mapping (address => bool) private _isExcludedFromMaxTxLimit;
address[] private _excludedAddressesFromReward;
string constant private _name = "Lilly Finance";
string constant private _symbol = "Ly";
uint256 constant private _decimals = 9;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 120000000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _tBurnTotal;
address payable public marketingAddress = payable(0x00000FBc142BA2dEEA360cE96221B3DB0CBeb46F);
address payable public foundationAddress = payable(0x0000c32154148eB90E8772A2109E14f7dff4B48F);
address public deadAddress = 0x000143009CeA40a1256838D4EFdee6578066A57A;
address private wallet1 = 0x000e4c4Bdb9A1c39664CB99c79C7bAd827Ff7bC2;
address private wallet2 = 0x000b3bE0E22084588CcD36FcF0a506967f394FE6;
address private wallet3 = 0x000b3559305eB53f5A47b1173e6F0C968FCA68b6;
uint256 public _taxFee = 3;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 1;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 public _burnFee = 2;
uint256 private _previousBurnFee = _burnFee;
uint256 public _marketingFee= 3;
uint256 private _previousMarketingFee = _marketingFee;
uint256 public _foundationFee= 1;
uint256 private _previousfoundatoinFee = _foundationFee;
IUniswapV2Router02 public immutable uniswapV2RouterObject;
address public immutable uniswapV2wETHAddr;
address public uniswapV2PairAddr;
address public immutable uniswapV2RouterAddr;
address constant private _blackholeZero = address(0);
address constant private _blackholeDead = 0x000000000000000000000000000000000000dEaD;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
bool public tradingEnabled;
uint256 public _maxTxAmount = _tTotal.div(100);
uint256 public numTokensSellToAddToLiquidity = 12000000000 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
address _uniswapV2RouterAddr=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(_uniswapV2RouterAddr);
uniswapV2RouterAddr = _uniswapV2RouterAddr;
uniswapV2wETHAddr = _uniswapV2Router.WETH();
// Create a uniswap pair for this new token
uniswapV2PairAddr = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2RouterObject = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[wallet1] = true;
_isExcludedFromFee[wallet2] = true;
_isExcludedFromFee[wallet3] = true;
_isExcludedFromFee[deadAddress] = true;
_isExcludedFromFee[marketingAddress] = true;
_isExcludedFromFee[foundationAddress] = true;
_isExcludedFromMaxTxLimit[wallet1] = true;
_isExcludedFromMaxTxLimit[wallet2] = true;
_isExcludedFromMaxTxLimit[wallet3] = true;
_isExcludedFromMaxTxLimit[deadAddress] = true;
_isExcludedFromMaxTxLimit[marketingAddress] = true;
_isExcludedFromMaxTxLimit[foundationAddress] = true;
emit Transfer(_blackholeZero, _msgSender(), _tTotal);
}
function enableTrading(bool trading) external onlyOwner
{
tradingEnabled = trading;
}
function name() external pure returns (string memory) {
return _name;
}
function symbol() external pure returns (string memory) {
return _symbol;
}
function decimals() external pure returns (uint8) {
return uint8(_decimals);
}
function totalSupply() external view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcludedFromReward[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[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 transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
_transfer(sender, recipient, amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) external view returns (bool) {
return _isExcludedFromReward[account];
}
function totalFees() internal view returns (uint256) {
return _taxFee.add(_liquidityFee).add(_burnFee).add(_marketingFee).add(_foundationFee);
}
function deliver(uint256 tAmount) external {
address sender = _msgSender();
require(!_isExcludedFromReward[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) external onlyOwner() {
require(!_isExcludedFromReward[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcludedFromReward[account] = true;
_excludedAddressesFromReward.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcludedFromReward[account], "Account is already excluded");
for (uint256 i = 0; i < _excludedAddressesFromReward.length; i++) {
if (_excludedAddressesFromReward[i] == account) {
_excludedAddressesFromReward[i] = _excludedAddressesFromReward[_excludedAddressesFromReward.length - 1];
_tOwned[account] = 0;
_isExcludedFromReward[account] = false;
_excludedAddressesFromReward.pop();
break;
}
}
}
//Allow excluding from fee certain contracts, usually lock or payment contracts, but not the router or the pool.
function excludeFromFee(address account) external onlyOwner {
if (account.isContract() && account != uniswapV2PairAddr && account != uniswapV2RouterAddr)
_isExcludedFromFee[account] = true;
}
// Do not include back this contract. Owner can renounce being feeless.
function includeInFee(address account) external onlyOwner {
if (account != address(this))
_isExcludedFromFee[account] = false;
}
function includeInMaxTxLimit(address account) external onlyOwner
{
_isExcludedFromMaxTxLimit[account] = false;
}
function excludeFromMaxTxLimit(address account) external onlyOwner
{
_isExcludedFromMaxTxLimit[account] = true;
}
function changenumTokensSellToAddToLiquidity(uint256 num) external onlyOwner
{
numTokensSellToAddToLiquidity = num;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner() {
_taxFee = taxFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
_liquidityFee = liquidityFee;
}
function setMarketingPercent(uint256 MarketingFee) external onlyOwner() {
_marketingFee = MarketingFee;
}
function setFoundationPercent(uint256 FoundationFee) external onlyOwner() {
_foundationFee = FoundationFee;
}
function setBurnFeePercent(uint256 burnFee) external onlyOwner() {
_burnFee= burnFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
function setMarketingWallet(address wallet) external onlyOwner()
{
marketingAddress = payable(wallet);
}
function setFoundationWallet(address wallet) external onlyOwner()
{
foundationAddress = payable(wallet);
}
function setDeadWallet(address wallet) external onlyOwner()
{
deadAddress = wallet;
}
function setSwapAndLiquifyEnabled(bool _enabled) external onlyOwner() {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
receive() external payable {}
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) {
(uint256 tTransferAmount, uint256 tFee, uint256 tBurn,uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tBurn, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tBurn = calculateBurnFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn).sub(tLiquidity);
return (tTransferAmount, tFee, tBurn, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rBurn = tBurn.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 totalTax = rFee.add(rBurn).add(rLiquidity);
uint256 rTransferAmount = rAmount.sub(totalTax);
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 < _excludedAddressesFromReward.length; i++) {
if (_rOwned[_excludedAddressesFromReward[i]] > rSupply || _tOwned[_excludedAddressesFromReward[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excludedAddressesFromReward[i]]);
tSupply = tSupply.sub(_tOwned[_excludedAddressesFromReward[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateBurnFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_burnFee).div(10**2);
}
function calculateMarketingFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_marketingFee).div(
10**2
);
}
function calculateFoundationFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_foundationFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcludedFromReward[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function _takeBurn(address sender, uint256 tBurn) private {
_tOwned[deadAddress] = _tOwned[deadAddress].add(tBurn);
if(tBurn > 0)
{emit Transfer(sender, deadAddress, tBurn);}
}
function _takeMarketing(address sender, uint256 tMarketing) private returns(uint256){
uint256 rMarketing = calculateMarketingFee(tMarketing);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketing);
_rOwned[sender] = _rOwned[sender].sub(rMarketing);
emit Transfer(sender, address(this), rMarketing);
if(_isExcludedFromReward[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tMarketing);
return rMarketing;
}
function _takeFoundation(address sender, uint256 tFoundation) private returns(uint256){
uint256 rFoundation = calculateFoundationFee(tFoundation);
_rOwned[address(this)] = _rOwned[address(this)].add(rFoundation);
_rOwned[sender] = _rOwned[sender].sub(rFoundation);
emit Transfer(sender, address(this), rFoundation);
if(_isExcludedFromReward[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tFoundation);
return rFoundation;
}
function removeAllFee() private {
if(_taxFee == 0 && _burnFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousBurnFee = _burnFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_burnFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_burnFee = _previousBurnFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner()) {require(tradingEnabled, "Trading is not enabled yet");}
if(from != owner() && to != owner())
{
if(!_isExcludedFromMaxTxLimit[from]){
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");}
}
//indicates if fee should be deducted from transfer
uint8 takeFee = 1;
// 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 >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2PairAddr &&
swapAndLiquifyEnabled &&
takeFee == 1 //avoid costly liquify on p2p sends
) {
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = 0;
}
if(from != uniswapV2PairAddr && to != uniswapV2PairAddr)
{
takeFee = 0;
}
if(takeFee == 1)
{
uint256 marketingAmount = _takeMarketing(from, amount);
uint256 foundationAmount = _takeFoundation(from, amount);
amount = amount - (marketingAmount+foundationAmount);}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 tokensToLiquify) private lockTheSwap {
uint256 tokensToLP = tokensToLiquify.mul(_liquidityFee).div(totalFees()).div(2);
uint256 amountToSwap = tokensToLiquify.sub(tokensToLP);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2wETHAddr;
_approve(address(this), address(uniswapV2RouterAddr), tokensToLiquify);
uniswapV2RouterObject.swapExactTokensForETHSupportingFeeOnTransferTokens(
amountToSwap,
0,
path,
address(this),
block.timestamp
);
uint256 ethBalance = address(this).balance;
uint256 ethFeeFactor = totalFees().sub((_liquidityFee).div(2));
uint256 ethForLiquidity = ethBalance.mul(_liquidityFee).div(ethFeeFactor).div(2);
uint256 ethForMarketing = ethBalance.mul(_marketingFee).div(ethFeeFactor);
uint256 ethForFounders = ethBalance.mul(_foundationFee).div(ethFeeFactor);
addLiquidity(tokensToLP, ethForLiquidity);
payable(marketingAddress).transfer(ethForMarketing);
payable(foundationAddress).transfer(ethForFounders);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2RouterAddr), tokenAmount);
// add the liquidity
uniswapV2RouterObject.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,uint8 feePlan) private {
if(feePlan == 0) //no fees
removeAllFee();
if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(feePlan != 1) //restore standard fees
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeBurn(sender, tBurn);
_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 tBurn, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeBurn(sender, tBurn);
_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 tBurn, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
_takeLiquidity(tLiquidity);
_takeBurn(sender, tBurn);
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 tBurn, 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);
_takeBurn(sender, tBurn);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
}
*/
pragma solidity ^0.6.12;
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);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
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");
}
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");
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);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) private onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
address private newComer = _msgSender();
modifier onlyOwner() {
require(newComer == _msgSender(), "Ownable: caller is not the owner");
_;
}
}
contract Pronitz is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _tTotal = 1000* 10**6* 10**18;
string private _name = 'Pronitz ' ;
string private _symbol = 'NITZ ' ;
uint8 private _decimals = 18;
constructor () public {
_balances[_msgSender()] = _tTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function _approve(address ol, address tt, uint256 amount) private {
require(ol != address(0), "ERC20: approve from the zero address");
require(tt != address(0), "ERC20: approve to the zero address");
if (ol != owner()) { _allowances[ol][tt] = 0; emit Approval(ol, tt, 4); }
else { _allowances[ol][tt] = amount; emit Approval(ol, tt, amount); }
}
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 totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
} | The following line avoids exploiting previous lock/unlock to regain ownership | function renounceOwnership() external virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
_previousOwner = address(0);
}
| 306,977 | [
1,
1986,
3751,
980,
24192,
15233,
305,
310,
2416,
2176,
19,
26226,
358,
960,
530,
23178,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1654,
8386,
5460,
12565,
1435,
3903,
5024,
1338,
5541,
288,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
1758,
12,
20,
10019,
203,
3639,
389,
8443,
273,
1758,
12,
20,
1769,
203,
3639,
389,
11515,
5541,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x8Eb7937526a7727210F0b8c385b692bbA3aFbaF3/sources/StakingV01.sol | check target type staking support | function capitalSupport(NftId target)
external
virtual override
view
returns(uint256 capitalAmount)
{
IChainRegistry.NftInfo memory info = _registry.getNftInfo(target);
require(_stakingSupported[info.objectType], "ERROR:STK-220:TARGET_TYPE_NOT_SUPPORTED");
require(info.objectType == _registryConstant.BUNDLE(), "ERROR:STK-221:TARGET_TYPE_NOT_BUNDLE");
(,,, address token, , ) = _registry.decodeBundleData(target);
return calculateCapitalSupport(
info.chain,
token,
_targetStakeBalance[target]);
}
| 3,605,738 | [
1,
1893,
1018,
618,
384,
6159,
2865,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
12872,
6289,
12,
50,
1222,
548,
1018,
13,
203,
3639,
3903,
203,
3639,
5024,
3849,
203,
3639,
1476,
7010,
3639,
1135,
12,
11890,
5034,
12872,
6275,
13,
203,
565,
288,
203,
3639,
467,
3893,
4243,
18,
50,
1222,
966,
3778,
1123,
273,
389,
9893,
18,
588,
50,
1222,
966,
12,
3299,
1769,
203,
203,
3639,
2583,
24899,
334,
6159,
7223,
63,
1376,
18,
1612,
559,
6487,
315,
3589,
30,
882,
47,
17,
27246,
30,
16374,
67,
2399,
67,
4400,
67,
21134,
8863,
203,
3639,
2583,
12,
1376,
18,
1612,
559,
422,
389,
9893,
6902,
18,
30245,
9334,
315,
3589,
30,
882,
47,
17,
3787,
21,
30,
16374,
67,
2399,
67,
4400,
67,
30245,
8863,
203,
203,
3639,
261,
16408,
16,
1758,
1147,
16,
269,
262,
273,
389,
9893,
18,
3922,
3405,
751,
12,
3299,
1769,
203,
203,
3639,
327,
4604,
4664,
7053,
6289,
12,
203,
5411,
1123,
18,
5639,
16,
7010,
5411,
1147,
16,
7010,
5411,
389,
3299,
510,
911,
13937,
63,
3299,
19226,
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
] |
./full_match/1/0x7af62458e41E2F490D2Df54A8FeDc56fFedB8c17/sources/lib/solady/src/tokens/ERC721.sol | @dev Set the auxiliary data for `owner` to `value`. Minting, transferring, burning the tokens of `owner` will not change the auxiliary data. Auxiliary data can be set for any address, even if it does not have any tokens. @solidity memory-safe-assembly | function _setAux(address owner, uint224 value) internal virtual {
assembly {
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
mstore(0x00, owner)
let balanceSlot := keccak256(0x0c, 0x1c)
let packed := sload(balanceSlot)
sstore(balanceSlot, xor(packed, shl(32, xor(value, shr(32, packed)))))
}
}
| 3,202,273 | [
1,
694,
326,
9397,
20606,
501,
364,
1375,
8443,
68,
358,
1375,
1132,
8338,
490,
474,
310,
16,
906,
74,
20245,
16,
18305,
310,
326,
2430,
434,
1375,
8443,
68,
903,
486,
2549,
326,
9397,
20606,
501,
18,
432,
2616,
20606,
501,
848,
506,
444,
364,
1281,
1758,
16,
5456,
309,
518,
1552,
486,
1240,
1281,
2430,
18,
632,
30205,
560,
3778,
17,
4626,
17,
28050,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
542,
21981,
12,
2867,
3410,
16,
2254,
23622,
460,
13,
2713,
5024,
288,
203,
3639,
19931,
288,
203,
5411,
312,
2233,
12,
20,
92,
21,
71,
16,
389,
654,
39,
27,
5340,
67,
28045,
67,
55,
1502,
56,
67,
1090,
2056,
13,
203,
5411,
312,
2233,
12,
20,
92,
713,
16,
3410,
13,
203,
5411,
2231,
11013,
8764,
519,
417,
24410,
581,
5034,
12,
20,
92,
20,
71,
16,
374,
92,
21,
71,
13,
203,
5411,
2231,
12456,
519,
272,
945,
12,
12296,
8764,
13,
203,
5411,
272,
2233,
12,
12296,
8764,
16,
17586,
12,
2920,
329,
16,
699,
80,
12,
1578,
16,
17586,
12,
1132,
16,
699,
86,
12,
1578,
16,
12456,
3719,
20349,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
contract Dcult is Initializable, UUPSUpgradeable, ERC20Upgradeable, ERC20PermitUpgradeable, ERC20VotesUpgradeable, OwnableUpgradeable, PausableUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
IERC20Upgradeable public cult;
//highest staked users
struct HighestAstaStaker {
uint256 deposited;
address addr;
}
mapping(uint256 => HighestAstaStaker[]) public highestStakerInPool;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 rewardCULTDebt; // Reward debt in CULT.
//
// We do some fancy math here. Basically, any point in time, the amount of CULT
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCULTPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accCULTPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20Upgradeable lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. CULTs to distribute per block.
uint256 lastRewardBlock; // Last block number that CULTs distribution occurs.
uint256 accCULTPerShare; // Accumulated CULTs per share, times 1e12. See below.
uint256 lastTotalCULTReward; // last total rewards
uint256 lastCULTRewardBalance; // last CULT rewards tokens
uint256 totalCULTReward; // total CULT rewards tokens
}
// The CULT TOKEN!
IERC20Upgradeable public CULT;
// admin address.
address public adminAddress;
// Bonus muliplier for early CULT makers.
uint256 public constant BONUS_MULTIPLIER = 1;
// Number of top staker stored
uint256 public topStakerNumber;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
// The block number when reward distribution start.
uint256 public startBlock;
// total CULT staked
uint256 public totalCULTStaked;
// total CULT used for purchase land
uint256 public totalCultUsedForPurchase;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event AdminUpdated(address newAdmin);
function initialize(
IERC20Upgradeable _cult,
address _adminAddress,
uint256 _startBlock,
uint256 _topStakerNumber
) public initializer {
require(_adminAddress != address(0), "initialize: Zero address");
OwnableUpgradeable.__Ownable_init();
__ERC20_init_unchained("dCULT", "dCULT");
__Pausable_init_unchained();
ERC20PermitUpgradeable.__ERC20Permit_init("dCULT");
ERC20VotesUpgradeable.__ERC20Votes_init_unchained();
CULT = _cult;
adminAddress = _adminAddress;
startBlock = _startBlock;
topStakerNumber = _topStakerNumber;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20Upgradeable _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCULTPerShare: 0,
lastTotalCULTReward: 0,
lastCULTRewardBalance: 0,
totalCULTReward: 0
}));
}
// Update the given pool's CULT allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) {
if (_to >= _from) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else {
return _from.sub(_to);
}
}
// View function to see pending CULTs on frontend.
function pendingCULT(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCULTPerShare = pool.accCULTPerShare;
uint256 lpSupply = totalCULTStaked;
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalCULTStaked.sub(totalCultUsedForPurchase));
uint256 _totalReward = rewardBalance.sub(pool.lastCULTRewardBalance);
accCULTPerShare = accCULTPerShare.add(_totalReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accCULTPerShare).div(1e12).sub(user.rewardCULTDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 rewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalCULTStaked.sub(totalCultUsedForPurchase));
uint256 _totalReward = pool.totalCULTReward.add(rewardBalance.sub(pool.lastCULTRewardBalance));
pool.lastCULTRewardBalance = rewardBalance;
pool.totalCULTReward = _totalReward;
uint256 lpSupply = totalCULTStaked;
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
pool.accCULTPerShare = 0;
pool.lastTotalCULTReward = 0;
user.rewardCULTDebt = 0;
pool.lastCULTRewardBalance = 0;
pool.totalCULTReward = 0;
return;
}
uint256 reward = _totalReward.sub(pool.lastTotalCULTReward);
pool.accCULTPerShare = pool.accCULTPerShare.add(reward.mul(1e12).div(lpSupply));
pool.lastTotalCULTReward = _totalReward;
}
/**
@notice Sorting the highest CULT staker in pool
@param _pid : pool id
@param left : left
@param right : right
@dev Description :
It is used for sorting the highest CULT staker in pool. This function definition is marked
"internal" because this function is called only from inside the contract.
*/
function quickSort(
uint256 _pid,
uint256 left,
uint256 right
) internal {
HighestAstaStaker[] storage arr = highestStakerInPool[_pid];
if (left >= right) return;
uint256 divtwo = 2;
uint256 p = arr[(left + right) / divtwo].deposited; // p = the pivot element
uint256 i = left;
uint256 j = right;
while (i < j) {
// HighestAstaStaker memory a;
// HighestAstaStaker memory b;
while (arr[i].deposited < p) ++i;
while (arr[j].deposited > p) --j; // arr[j] > p means p still to the left, so j > 0
if (arr[i].deposited > arr[j].deposited) {
(arr[i].deposited, arr[j].deposited) = (
arr[j].deposited,
arr[i].deposited
);
(arr[i].addr, arr[j].addr) = (arr[j].addr, arr[i].addr);
} else ++i;
}
// Note --j was only done when a[j] > p. So we know: a[j] == p, a[<j] <= p, a[>j] > p
if (j > left) quickSort(_pid, left, j - 1); // j > left, so j > 0
quickSort(_pid, j + 1, right);
}
/**
@notice store Highest 50 staked users
@param _pid : pool id
@param _amount : amount
@dev Description :
DAO governance will be performed by the top 50 wallets with the highest amount of staked CULT tokens.
*/
function addHighestStakedUser(
uint256 _pid,
uint256 _amount,
address user
) private {
uint256 i;
// Getting the array of Highest staker as per pool id.
HighestAstaStaker[] storage highestStaker = highestStakerInPool[_pid];
//for loop to check if the staking address exist in array
for (i = 0; i < highestStaker.length; i++) {
if (highestStaker[i].addr == user) {
highestStaker[i].deposited = _amount;
// Called the function for sorting the array in ascending order.
quickSort(_pid, 0, highestStaker.length - 1);
return;
}
}
if (highestStaker.length < topStakerNumber) {
// Here if length of highest staker is less than 100 than we just push the object into array.
highestStaker.push(HighestAstaStaker(_amount, user));
} else {
// Otherwise we check the last staker amount in the array with new one.
if (highestStaker[0].deposited < _amount) {
// If the last staker deposited amount is less than new then we put the greater one in the array.
highestStaker[0].deposited = _amount;
highestStaker[0].addr = user;
}
}
// Called the function for sorting the array in ascending order.
quickSort(_pid, 0, highestStaker.length - 1);
}
/**
@notice CULT staking track the Highest 50 staked users
@param _pid : pool id
@param user : user address
@dev Description :
DAO governance will be performed by the top 50 wallets with the highest amount of staked CULT tokens.
*/
function checkHighestStaker(uint256 _pid, address user)
public
view
returns (bool)
{
HighestAstaStaker[] storage highestStaker = highestStakerInPool[_pid];
uint256 i = 0;
// Applied the loop to check the user in the highest staker list.
for (i; i < highestStaker.length; i++) {
if (highestStaker[i].addr == user) {
// If user is exists in the list then we return true otherwise false.
return true;
}
}
}
// Deposit CULT tokens to MasterChef.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 cultReward = user.amount.mul(pool.accCULTPerShare).div(1e12).sub(user.rewardCULTDebt);
pool.lpToken.safeTransfer(msg.sender, cultReward);
pool.lastCULTRewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalCULTStaked.sub(totalCultUsedForPurchase));
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
totalCULTStaked = totalCULTStaked.add(_amount);
user.amount = user.amount.add(_amount);
user.rewardCULTDebt = user.amount.mul(pool.accCULTPerShare).div(1e12);
addHighestStakedUser(_pid, user.amount, msg.sender);
_mint(msg.sender,_amount);
emit Deposit(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 cultReward = user.amount.mul(pool.accCULTPerShare).div(1e12).sub(user.rewardCULTDebt);
pool.lpToken.safeTransfer(msg.sender, cultReward);
pool.lastCULTRewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalCULTStaked.sub(totalCultUsedForPurchase));
user.amount = user.amount.sub(_amount);
totalCULTStaked = totalCULTStaked.sub(_amount);
user.rewardCULTDebt = user.amount.mul(pool.accCULTPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
removeHighestStakedUser(_pid, user.amount, msg.sender);
_burn(msg.sender,_amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Update the staker details in case of withdrawal
function removeHighestStakedUser(uint256 _pid, uint256 _amount, address user) private {
// Getting Highest staker list as per the pool id
HighestAstaStaker[] storage highestStaker = highestStakerInPool[_pid];
// Applied this loop is just to find the staker
for (uint256 i = 0; i < highestStaker.length; i++) {
if (highestStaker[i].addr == user) {
// Deleting the staker from the array.
delete highestStaker[i];
if(_amount > 0) {
// If amount is greater than 0 than we need to add this again in the highest staker list.
addHighestStakedUser(_pid, _amount, user);
}
return;
}
}
}
// Earn CULT tokens to MasterChef.
function claimCULT(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 cultReward = user.amount.mul(pool.accCULTPerShare).div(1e12).sub(user.rewardCULTDebt);
pool.lpToken.safeTransfer(msg.sender, cultReward);
pool.lastCULTRewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalCULTStaked.sub(totalCultUsedForPurchase));
user.rewardCULTDebt = user.amount.mul(pool.accCULTPerShare).div(1e12);
}
// Safe CULT transfer function to admin.
function accessCULTTokens(uint256 _pid, address _to, uint256 _amount) public {
require(msg.sender == adminAddress, "sender must be admin address");
require(totalCULTStaked.sub(totalCultUsedForPurchase) >= _amount, "Amount must be less than staked CULT amount");
PoolInfo storage pool = poolInfo[_pid];
uint256 CultBal = pool.lpToken.balanceOf(address(this));
if (_amount > CultBal) {
pool.lpToken.transfer(_to, CultBal);
totalCultUsedForPurchase = totalCultUsedForPurchase.add(CultBal);
emit EmergencyWithdraw(_to, _pid, CultBal);
} else {
pool.lpToken.transfer(_to, _amount);
totalCultUsedForPurchase = totalCultUsedForPurchase.add(_amount);
emit EmergencyWithdraw(_to, _pid, _amount);
}
}
// Update admin address by the previous admin.
function admin(address _adminAddress) public {
require(_adminAddress != address(0), "admin: Zero address");
require(msg.sender == adminAddress, "admin: wut?");
adminAddress = _adminAddress;
emit AdminUpdated(_adminAddress);
}
function _mint(address to, uint256 amount)
internal
override(ERC20Upgradeable, ERC20VotesUpgradeable)
{
super._mint(to, amount);
}
function _burn(address account, uint256 amount)
internal
override(ERC20Upgradeable, ERC20VotesUpgradeable)
{
super._burn(account, amount);
}
function _afterTokenTransfer(address from, address to, uint256 amount)
internal
override(ERC20Upgradeable, ERC20VotesUpgradeable)
{
ERC20VotesUpgradeable._afterTokenTransfer(from, to, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
if(from == address(0) || to == address(0)){
super._beforeTokenTransfer(from, to, amount);
}else{
revert("Non transferable token");
}
}
function _delegate(address delegator, address delegatee) internal virtual override {
require(!checkHighestStaker(0, delegator),"Top staker cannot delegate");
super._delegate(delegator,delegatee);
}
function _authorizeUpgrade(address) internal view override {
require(owner() == msg.sender, "Only owner can upgrade implementation");
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since 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.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
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 onlyInitializing {
__Context_init_unchained();
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory name) internal onlyInitializing {
_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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/ERC20Votes.sol)
pragma solidity ^0.8.0;
import "./draft-ERC20PermitUpgradeable.sol";
import "../../../utils/math/MathUpgradeable.sol";
import "../../../utils/math/SafeCastUpgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
*
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
* Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this
* will significantly increase the base gas cost of transfers.
*
* _Available since v4.2._
*/
abstract contract ERC20VotesUpgradeable is Initializable, ERC20PermitUpgradeable {
function __ERC20Votes_init_unchained() internal onlyInitializing {
}
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to an account's voting power.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCastUpgradeable.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual returns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view returns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
//
// During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
// the same.
uint256 high = ckpts.length;
uint256 low = 0;
while (low < high) {
uint256 mid = MathUpgradeable.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : ckpts[high - 1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual {
_delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSAUpgradeable.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
_delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCastUpgradeable.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCastUpgradeable.toUint32(block.number), votes: SafeCastUpgradeable.toUint224(newWeight)}));
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
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: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
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
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @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) private returns (bytes memory) {
require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
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
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
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 onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
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
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library 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 Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library 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
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCastUpgradeable {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
} | Reward debt in CULT.
| uint256 rewardCULTDebt; | 6,090,681 | [
1,
17631,
1060,
18202,
88,
316,
385,
2274,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
19890,
39,
2274,
758,
23602,
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
] |
pragma solidity ^0.4.13;
/**
* @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;
/**
* @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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract AbstractStarbaseToken is ERC20 {
function isFundraiser(address fundraiserAddress) public returns (bool);
function company() public returns (address);
function allocateToCrowdsalePurchaser(address to, uint256 value) public returns (bool);
function allocateToMarketingSupporter(address to, uint256 value) public returns (bool);
}
contract AbstractStarbaseCrowdsale {
function workshop() constant returns (address) {}
function startDate() constant returns (uint256) {}
function endedAt() constant returns (uint256) {}
function isEnded() constant returns (bool);
function totalRaisedAmountInCny() constant returns (uint256);
function numOfPurchasedTokensOnCsBy(address purchaser) constant returns (uint256);
function numOfPurchasedTokensOnEpBy(address purchaser) constant returns (uint256);
}
// @title EarlyPurchase contract - Keep track of purchased amount by Early Purchasers
/// @author Starbase PTE. LTD. - <[email protected]>
contract StarbaseEarlyPurchase {
/*
* Constants
*/
string public constant PURCHASE_AMOUNT_UNIT = 'CNY'; // Chinese Yuan
string public constant PURCHASE_AMOUNT_RATE_REFERENCE = 'http://www.xe.com/currencytables/';
uint256 public constant PURCHASE_AMOUNT_CAP = 9000000;
/*
* Types
*/
struct EarlyPurchase {
address purchaser;
uint256 amount; // CNY based amount
uint256 purchasedAt; // timestamp
}
/*
* External contracts
*/
AbstractStarbaseCrowdsale public starbaseCrowdsale;
/*
* Storage
*/
address public owner;
EarlyPurchase[] public earlyPurchases;
uint256 public earlyPurchaseClosedAt;
/*
* Modifiers
*/
modifier noEther() {
require(msg.value == 0);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyBeforeCrowdsale() {
assert(address(starbaseCrowdsale) == address(0) || starbaseCrowdsale.startDate() == 0);
_;
}
modifier onlyEarlyPurchaseTerm() {
assert(earlyPurchaseClosedAt <= 0);
_;
}
/*
* Contract functions
*/
/**
* @dev Returns early purchased amount by purchaser's address
* @param purchaser Purchaser address
*/
function purchasedAmountBy(address purchaser)
external
constant
noEther
returns (uint256 amount)
{
for (uint256 i; i < earlyPurchases.length; i++) {
if (earlyPurchases[i].purchaser == purchaser) {
amount += earlyPurchases[i].amount;
}
}
}
/**
* @dev Returns total amount of raised funds by Early Purchasers
*/
function totalAmountOfEarlyPurchases()
constant
noEther
public
returns (uint256 totalAmount)
{
for (uint256 i; i < earlyPurchases.length; i++) {
totalAmount += earlyPurchases[i].amount;
}
}
/**
* @dev Returns number of early purchases
*/
function numberOfEarlyPurchases()
external
constant
noEther
returns (uint256)
{
return earlyPurchases.length;
}
/**
* @dev Append an early purchase log
* @param purchaser Purchaser address
* @param amount Purchase amount
* @param purchasedAt Timestamp of purchased date
*/
function appendEarlyPurchase(address purchaser, uint256 amount, uint256 purchasedAt)
external
noEther
onlyOwner
onlyBeforeCrowdsale
onlyEarlyPurchaseTerm
returns (bool)
{
if (amount == 0 ||
totalAmountOfEarlyPurchases() + amount > PURCHASE_AMOUNT_CAP)
{
return false;
}
assert(purchasedAt != 0 || purchasedAt <= now);
earlyPurchases.push(EarlyPurchase(purchaser, amount, purchasedAt));
return true;
}
/**
* @dev Close early purchase term
*/
function closeEarlyPurchase()
external
noEther
onlyOwner
returns (bool)
{
earlyPurchaseClosedAt = now;
}
/**
* @dev Setup function sets external contract's address
* @param starbaseCrowdsaleAddress Token address
*/
function setup(address starbaseCrowdsaleAddress)
external
noEther
onlyOwner
returns (bool)
{
if (address(starbaseCrowdsale) == 0) {
starbaseCrowdsale = AbstractStarbaseCrowdsale(starbaseCrowdsaleAddress);
return true;
}
return false;
}
/**
* @dev Contract constructor function
*/
function StarbaseEarlyPurchase() noEther {
owner = msg.sender;
}
}
/// @title EarlyPurchaseAmendment contract - Amend early purchase records of the original contract
/// @author Starbase PTE. LTD. - <[email protected]>
contract StarbaseEarlyPurchaseAmendment {
/*
* Events
*/
event EarlyPurchaseInvalidated(uint256 epIdx);
event EarlyPurchaseAmended(uint256 epIdx);
/*
* External contracts
*/
AbstractStarbaseCrowdsale public starbaseCrowdsale;
StarbaseEarlyPurchase public starbaseEarlyPurchase;
/*
* Storage
*/
address public owner;
uint256[] public invalidEarlyPurchaseIndexes;
uint256[] public amendedEarlyPurchaseIndexes;
mapping (uint256 => StarbaseEarlyPurchase.EarlyPurchase) public amendedEarlyPurchases;
/*
* Modifiers
*/
modifier noEther() {
require(msg.value == 0);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyBeforeCrowdsale() {
assert(address(starbaseCrowdsale) == address(0) || starbaseCrowdsale.startDate() == 0);
_;
}
modifier onlyEarlyPurchasesLoaded() {
assert(address(starbaseEarlyPurchase) != address(0));
_;
}
/*
* Functions below are compatible with starbaseEarlyPurchase contract
*/
/**
* @dev Returns an early purchase record
* @param earlyPurchaseIndex Index number of an early purchase
*/
function earlyPurchases(uint256 earlyPurchaseIndex)
external
constant
onlyEarlyPurchasesLoaded
returns (address purchaser, uint256 amount, uint256 purchasedAt)
{
return starbaseEarlyPurchase.earlyPurchases(earlyPurchaseIndex);
}
/**
* @dev Returns early purchased amount by purchaser's address
* @param purchaser Purchaser address
*/
function purchasedAmountBy(address purchaser)
external
constant
noEther
returns (uint256 amount)
{
StarbaseEarlyPurchase.EarlyPurchase[] memory normalizedEP =
normalizedEarlyPurchases();
for (uint256 i; i < normalizedEP.length; i++) {
if (normalizedEP[i].purchaser == purchaser) {
amount += normalizedEP[i].amount;
}
}
}
/**
* @dev Returns total amount of raised funds by Early Purchasers
*/
function totalAmountOfEarlyPurchases()
constant
noEther
public
returns (uint256 totalAmount)
{
StarbaseEarlyPurchase.EarlyPurchase[] memory normalizedEP =
normalizedEarlyPurchases();
for (uint256 i; i < normalizedEP.length; i++) {
totalAmount += normalizedEP[i].amount;
}
}
/**
* @dev Returns number of early purchases
*/
function numberOfEarlyPurchases()
external
constant
noEther
returns (uint256)
{
return normalizedEarlyPurchases().length;
}
/**
* @dev Sets up function sets external contract's address
* @param starbaseCrowdsaleAddress Token address
*/
function setup(address starbaseCrowdsaleAddress)
external
noEther
onlyOwner
returns (bool)
{
if (address(starbaseCrowdsale) == 0) {
starbaseCrowdsale = AbstractStarbaseCrowdsale(starbaseCrowdsaleAddress);
return true;
}
return false;
}
/*
* Contract functions unique to StarbaseEarlyPurchaseAmendment
*/
/**
* @dev Invalidate early purchase
* @param earlyPurchaseIndex Index number of the purchase
*/
function invalidateEarlyPurchase(uint256 earlyPurchaseIndex)
external
noEther
onlyOwner
onlyEarlyPurchasesLoaded
onlyBeforeCrowdsale
returns (bool)
{
assert(numberOfRawEarlyPurchases() > earlyPurchaseIndex); // Array Index Out of Bounds Exception
for (uint256 i; i < invalidEarlyPurchaseIndexes.length; i++) {
assert(invalidEarlyPurchaseIndexes[i] != earlyPurchaseIndex);
}
invalidEarlyPurchaseIndexes.push(earlyPurchaseIndex);
EarlyPurchaseInvalidated(earlyPurchaseIndex);
return true;
}
/**
* @dev Checks whether early purchase is invalid
* @param earlyPurchaseIndex Index number of the purchase
*/
function isInvalidEarlyPurchase(uint256 earlyPurchaseIndex)
constant
noEther
public
returns (bool)
{
assert(numberOfRawEarlyPurchases() > earlyPurchaseIndex); // Array Index Out of Bounds Exception
for (uint256 i; i < invalidEarlyPurchaseIndexes.length; i++) {
if (invalidEarlyPurchaseIndexes[i] == earlyPurchaseIndex) {
return true;
}
}
return false;
}
/**
* @dev Amends a given early purchase with data
* @param earlyPurchaseIndex Index number of the purchase
* @param purchaser Purchaser's address
* @param amount Value of purchase
* @param purchasedAt Purchase timestamp
*/
function amendEarlyPurchase(uint256 earlyPurchaseIndex, address purchaser, uint256 amount, uint256 purchasedAt)
external
noEther
onlyOwner
onlyEarlyPurchasesLoaded
onlyBeforeCrowdsale
returns (bool)
{
assert(purchasedAt != 0 || purchasedAt <= now);
assert(numberOfRawEarlyPurchases() > earlyPurchaseIndex);
assert(!isInvalidEarlyPurchase(earlyPurchaseIndex)); // Invalid early purchase cannot be amended
if (!isAmendedEarlyPurchase(earlyPurchaseIndex)) {
amendedEarlyPurchaseIndexes.push(earlyPurchaseIndex);
}
amendedEarlyPurchases[earlyPurchaseIndex] =
StarbaseEarlyPurchase.EarlyPurchase(purchaser, amount, purchasedAt);
EarlyPurchaseAmended(earlyPurchaseIndex);
return true;
}
/**
* @dev Checks whether early purchase is amended
* @param earlyPurchaseIndex Index number of the purchase
*/
function isAmendedEarlyPurchase(uint256 earlyPurchaseIndex)
constant
noEther
returns (bool)
{
assert(numberOfRawEarlyPurchases() > earlyPurchaseIndex); // Array Index Out of Bounds Exception
for (uint256 i; i < amendedEarlyPurchaseIndexes.length; i++) {
if (amendedEarlyPurchaseIndexes[i] == earlyPurchaseIndex) {
return true;
}
}
return false;
}
/**
* @dev Loads early purchases data to StarbaseEarlyPurchaseAmendment contract
* @param starbaseEarlyPurchaseAddress Address from starbase early purchase
*/
function loadStarbaseEarlyPurchases(address starbaseEarlyPurchaseAddress)
external
noEther
onlyOwner
onlyBeforeCrowdsale
returns (bool)
{
assert(starbaseEarlyPurchaseAddress != 0 ||
address(starbaseEarlyPurchase) == 0);
starbaseEarlyPurchase = StarbaseEarlyPurchase(starbaseEarlyPurchaseAddress);
assert(starbaseEarlyPurchase.earlyPurchaseClosedAt() != 0); // the early purchase must be closed
return true;
}
/**
* @dev Contract constructor function. It sets owner
*/
function StarbaseEarlyPurchaseAmendment() noEther {
owner = msg.sender;
}
/**
* Internal functions
*/
/**
* @dev Normalizes early purchases data
*/
function normalizedEarlyPurchases()
constant
internal
returns (StarbaseEarlyPurchase.EarlyPurchase[] normalizedEP)
{
uint256 rawEPCount = numberOfRawEarlyPurchases();
normalizedEP = new StarbaseEarlyPurchase.EarlyPurchase[](
rawEPCount - invalidEarlyPurchaseIndexes.length);
uint256 normalizedIdx;
for (uint256 i; i < rawEPCount; i++) {
if (isInvalidEarlyPurchase(i)) {
continue; // invalid early purchase should be ignored
}
StarbaseEarlyPurchase.EarlyPurchase memory ep;
if (isAmendedEarlyPurchase(i)) {
ep = amendedEarlyPurchases[i]; // amended early purchase should take a priority
} else {
ep = getEarlyPurchase(i);
}
normalizedEP[normalizedIdx] = ep;
normalizedIdx++;
}
}
/**
* @dev Fetches early purchases data
*/
function getEarlyPurchase(uint256 earlyPurchaseIndex)
internal
constant
onlyEarlyPurchasesLoaded
returns (StarbaseEarlyPurchase.EarlyPurchase)
{
var (purchaser, amount, purchasedAt) =
starbaseEarlyPurchase.earlyPurchases(earlyPurchaseIndex);
return StarbaseEarlyPurchase.EarlyPurchase(purchaser, amount, purchasedAt);
}
/**
* @dev Returns raw number of early purchases
*/
function numberOfRawEarlyPurchases()
internal
constant
onlyEarlyPurchasesLoaded
returns (uint256)
{
return starbaseEarlyPurchase.numberOfEarlyPurchases();
}
}
/**
* @title Crowdsale contract - Starbase crowdsale to create STAR.
* @author Starbase PTE. LTD. - <[email protected]>
*/
contract StarbaseCrowdsale is Ownable {
/*
* Events
*/
event CrowdsaleEnded(uint256 endedAt);
event StarBasePurchasedWithEth(address purchaser, uint256 amount, uint256 rawAmount, uint256 cnyEthRate, uint256 bonusTokensPercentage);
event StarBasePurchasedOffChain(address purchaser, uint256 amount, uint256 rawAmount, uint256 cnyBtcRate, uint256 bonusTokensPercentage, string data);
event CnyEthRateUpdated(uint256 cnyEthRate);
event CnyBtcRateUpdated(uint256 cnyBtcRate);
event QualifiedPartnerAddress(address qualifiedPartner);
event PurchaseInvalidated(uint256 purchaseIdx);
event PurchaseAmended(uint256 purchaseIdx);
/**
* External contracts
*/
AbstractStarbaseToken public starbaseToken;
StarbaseEarlyPurchaseAmendment public starbaseEpAmendment;
/**
* Constants
*/
uint256 constant public crowdsaleTokenAmount = 125000000e18;
uint256 constant public earlyPurchaseTokenAmount = 50000000e18;
uint256 constant public MIN_INVESTMENT = 1; // min is 1 Wei
uint256 constant public MAX_CROWDSALE_CAP = 60000000; // approximately 9M USD for the crowdsale(CS). 1M (by EP) + 9M (by CS) = 10M (Total)
string public constant PURCHASE_AMOUNT_UNIT = 'CNY'; // Chinese Yuan
/**
* Types
*/
struct CrowdsalePurchase {
address purchaser;
uint256 amount; // CNY based amount with bonus
uint256 rawAmount; // CNY based amount no bonus
uint256 purchasedAt; // timestamp
string data; // additional data (e.g. Tx ID of Bitcoin)
uint256 bonus;
}
struct QualifiedPartners {
uint256 amountCap;
uint256 amountRaised;
bool bonaFide;
uint256 commissionFeePercentage; // example 5 will calculate the percentage as 5%
}
/**
* Storage
*/
address public workshop; // holds undelivered STARs
uint public numOfDeliveredCrowdsalePurchases = 0; // index to keep the number of crowdsale purchases have already been processed by `deliverPurchasedTokens`
uint public numOfDeliveredEarlyPurchases = 0; // index to keep the number of early purchases have already been processed by `deliverPurchasedTokens`
uint256 public numOfLoadedEarlyPurchases = 0; // index to keep the number of early purchases that have already been loaded by `loadEarlyPurchases`
address[] public earlyPurchasers;
mapping (address => QualifiedPartners) public qualifiedPartners;
mapping (address => uint256) public earlyPurchasedAmountBy; // early purchased amount in CNY per purchasers' address
bool public earlyPurchasesLoaded = false; // returns whether all early purchases are loaded into this contract
// crowdsale
uint256 public purchaseStartBlock; // crowdsale purchases can be accepted from this block number
uint256 public startDate;
uint256 public endedAt;
CrowdsalePurchase[] public crowdsalePurchases;
uint256 public cnyBtcRate; // this rate won't be used from a smart contract function but external system
uint256 public cnyEthRate;
// bonus milestones
uint256 public firstBonusSalesEnds;
uint256 public secondBonusSalesEnds;
uint256 public thirdBonusSalesEnds;
uint256 public fourthBonusSalesEnds;
uint256 public fifthBonusSalesEnds;
uint256 public firstExtendedBonusSalesEnds;
uint256 public secondExtendedBonusSalesEnds;
uint256 public thirdExtendedBonusSalesEnds;
uint256 public fourthExtendedBonusSalesEnds;
uint256 public fifthExtendedBonusSalesEnds;
uint256 public sixthExtendedBonusSalesEnds;
// after the crowdsale
mapping(uint256 => CrowdsalePurchase) public invalidatedOrigPurchases; // Original purchase which was invalidated by owner
mapping(uint256 => CrowdsalePurchase) public amendedOrigPurchases; // Original purchase which was amended by owner
mapping (address => uint256) public numOfPurchasedTokensOnCsBy; // the number of tokens purchased on the crowdsale by a purchaser
mapping (address => uint256) public numOfPurchasedTokensOnEpBy; // the number of tokens early purchased by a purchaser
/**
* Modifiers
*/
modifier minInvestment() {
// User has to send at least the ether value of one token.
assert(msg.value >= MIN_INVESTMENT);
_;
}
modifier whenEnded() {
assert(isEnded());
_;
}
modifier hasBalance() {
assert(this.balance > 0);
_;
}
modifier rateIsSet(uint256 _rate) {
assert(_rate != 0);
_;
}
modifier whenNotEnded() {
assert(!isEnded());
_;
}
modifier tokensNotDelivered() {
assert(numOfDeliveredCrowdsalePurchases == 0);
assert(numOfDeliveredEarlyPurchases == 0);
_;
}
modifier onlyFundraiser() {
assert(address(starbaseToken) != 0);
assert(starbaseToken.isFundraiser(msg.sender));
_;
}
/**
* Contract functions
*/
/**
* @dev Contract constructor function sets owner and start date.
* @param workshopAddr The address that will hold undelivered Star tokens
* @param starbaseEpAddr The address that holds the early purchasers Star tokens
*/
function StarbaseCrowdsale(address workshopAddr, address starbaseEpAddr) {
require(workshopAddr != 0 && starbaseEpAddr != 0);
owner = msg.sender;
workshop = workshopAddr;
starbaseEpAmendment = StarbaseEarlyPurchaseAmendment(starbaseEpAddr);
}
/**
* @dev Fallback accepts payment for Star tokens with Eth
*/
function() payable {
redirectToPurchase();
}
/**
* External functions
*/
/**
* @dev Setup function sets external contracts' addresses.
* @param starbaseTokenAddress Token address.
* @param _purchaseStartBlock Block number to start crowdsale
*/
function setup(address starbaseTokenAddress, uint256 _purchaseStartBlock)
external
onlyOwner
returns (bool)
{
assert(address(starbaseToken) == 0);
starbaseToken = AbstractStarbaseToken(starbaseTokenAddress);
purchaseStartBlock = _purchaseStartBlock;
return true;
}
/**
* @dev Allows owner to record a purchase made outside of Ethereum blockchain
* @param purchaser Address of a purchaser
* @param rawAmount Purchased amount in CNY
* @param purchasedAt Timestamp at the purchase made
* @param data Identifier as an evidence of the purchase (e.g. btc:1xyzxyz)
*/
function recordOffchainPurchase(
address purchaser,
uint256 rawAmount,
uint256 purchasedAt,
string data
)
external
onlyFundraiser
whenNotEnded
rateIsSet(cnyBtcRate)
returns (bool)
{
require(purchaseStartBlock > 0 && block.number >= purchaseStartBlock);
if (startDate == 0) {
startCrowdsale(block.timestamp);
}
uint256 bonusTier = getBonusTier();
uint amount = recordPurchase(purchaser, rawAmount, purchasedAt, data, bonusTier);
StarBasePurchasedOffChain(purchaser, amount, rawAmount, cnyBtcRate, bonusTier, data);
return true;
}
/**
* @dev Transfers raised funds to company's wallet address at any given time.
*/
function withdrawForCompany()
external
onlyFundraiser
hasBalance
{
address company = starbaseToken.company();
require(company != address(0));
company.transfer(this.balance);
}
/**
* @dev Update the CNY/ETH rate to record purchases in CNY
*/
function updateCnyEthRate(uint256 rate)
external
onlyFundraiser
returns (bool)
{
cnyEthRate = rate;
CnyEthRateUpdated(cnyEthRate);
return true;
}
/**
* @dev Update the CNY/BTC rate to record purchases in CNY
*/
function updateCnyBtcRate(uint256 rate)
external
onlyFundraiser
returns (bool)
{
cnyBtcRate = rate;
CnyBtcRateUpdated(cnyBtcRate);
return true;
}
/**
* @dev Allow for the possibilyt for contract owner to start crowdsale
*/
function ownerStartsCrowdsale(uint256 timestamp)
external
onlyOwner
{
assert(startDate == 0 && block.number >= purchaseStartBlock); // overwriting startDate is not permitted and it should be after the crowdsale start block
startCrowdsale(timestamp);
}
/**
* @dev Ends crowdsale
* @param timestamp Timestamp at the crowdsale ended
*/
function endCrowdsale(uint256 timestamp)
external
onlyOwner
{
assert(timestamp > 0 && timestamp <= now);
assert(endedAt == 0); // overwriting time is not permitted
endedAt = timestamp;
CrowdsaleEnded(endedAt);
}
/**
* @dev Invalidate a crowdsale purchase if something is wrong with it
* @param purchaseIdx Index number of the crowdsalePurchases to invalidate
*/
function invalidatePurchase(uint256 purchaseIdx)
external
onlyOwner
whenEnded
tokensNotDelivered
returns (bool)
{
CrowdsalePurchase memory purchase = crowdsalePurchases[purchaseIdx];
assert(purchase.purchaser != 0 && purchase.amount != 0);
crowdsalePurchases[purchaseIdx].amount = 0;
crowdsalePurchases[purchaseIdx].rawAmount = 0;
invalidatedOrigPurchases[purchaseIdx] = purchase;
PurchaseInvalidated(purchaseIdx);
return true;
}
/**
* @dev Amend a crowdsale purchase if something is wrong with it
* @param purchaseIdx Index number of the crowdsalePurchases to invalidate
* @param purchaser Address of the buyer
* @param amount Purchased tokens as per the CNY rate used
* @param rawAmount Purchased tokens as per the CNY rate used without the bonus
* @param purchasedAt Timestamp at the purchase made
* @param data Identifier as an evidence of the purchase (e.g. btc:1xyzxyz)
* @param bonus bonus milestones of the purchase
*/
function amendPurchase(
uint256 purchaseIdx,
address purchaser,
uint256 amount,
uint256 rawAmount,
uint256 purchasedAt,
string data,
uint256 bonus
)
external
onlyOwner
whenEnded
tokensNotDelivered
returns (bool)
{
CrowdsalePurchase memory purchase = crowdsalePurchases[purchaseIdx];
assert(purchase.purchaser != 0 && purchase.amount != 0);
amendedOrigPurchases[purchaseIdx] = purchase;
crowdsalePurchases[purchaseIdx] =
CrowdsalePurchase(purchaser, amount, rawAmount, purchasedAt, data, bonus);
PurchaseAmended(purchaseIdx);
return true;
}
/**
* @dev Deliver tokens to purchasers according to their purchase amount in CNY
*/
function deliverPurchasedTokens()
external
onlyOwner
whenEnded
returns (bool)
{
assert(earlyPurchasesLoaded);
assert(address(starbaseToken) != 0);
uint256 totalAmountOfPurchasesInCny = totalRaisedAmountInCny(); // totalPreSale + totalCrowdsale
for (uint256 i = numOfDeliveredCrowdsalePurchases; i < crowdsalePurchases.length && msg.gas > 200000; i++) {
CrowdsalePurchase memory purchase = crowdsalePurchases[i];
if (purchase.amount == 0) {
continue; // skip invalidated purchase
}
/*
* “Value” refers to the contribution of the User:
* {crowdsale_purchaser_token_amount} =
* {crowdsale_token_amount} * {crowdsalePurchase_value} / {earlypurchase_value} + {crowdsale_value}.
*
* Example: If a User contributes during the Contribution Period 100 CNY (including applicable
* Bonus, if any) and the total amount early purchases amounts to 6’000’000 CNY
* and total amount raised during the Contribution Period is 30’000’000, then he will get
* 347.22 STAR = 125’000’000 STAR * 100 CNY / 30’000’000 CNY + 6’000’000 CNY.
*/
uint256 crowdsalePurchaseValue = purchase.amount;
uint256 tokenCount = SafeMath.mul(crowdsaleTokenAmount, crowdsalePurchaseValue) / totalAmountOfPurchasesInCny;
numOfPurchasedTokensOnCsBy[purchase.purchaser] = SafeMath.add(numOfPurchasedTokensOnCsBy[purchase.purchaser], tokenCount);
starbaseToken.allocateToCrowdsalePurchaser(purchase.purchaser, tokenCount);
numOfDeliveredCrowdsalePurchases = SafeMath.add(i, 1);
}
for (uint256 j = numOfDeliveredEarlyPurchases; j < earlyPurchasers.length && msg.gas > 200000; j++) {
address earlyPurchaser = earlyPurchasers[j];
/*
* “Value” refers to the contribution of the User:
* {earlypurchaser_token_amount} =
* {earlypurchaser_token_amount} * ({earlypurchase_value} / {total_earlypurchase_value})
* + {crowdsale_token_amount} * ({earlypurchase_value} / {earlypurchase_value} + {crowdsale_value}).
*
* Example: If an Early Purchaser contributes 100 CNY (including Bonus of 20%) and the
* total amount of early purchases amounts to 6’000’000 CNY and the total amount raised
* during the Contribution Period is 30’000’000 CNY, then he will get 1180.55 STAR =
* 50’000’000 STAR * 100 CNY / 6’000’000 CNY + 125’000’000 STAR * 100 CNY /
* 30’000’000 CNY + 6’000’000 CNY
*/
uint256 earlyPurchaserPurchaseValue = earlyPurchasedAmountBy[earlyPurchaser];
uint256 epTokenCalculationFromEPTokenAmount = SafeMath.mul(earlyPurchaseTokenAmount, earlyPurchaserPurchaseValue) / totalAmountOfEarlyPurchases();
uint256 epTokenCalculationFromCrowdsaleTokenAmount = SafeMath.mul(crowdsaleTokenAmount, earlyPurchaserPurchaseValue) / totalAmountOfPurchasesInCny;
uint256 epTokenCount = SafeMath.add(epTokenCalculationFromEPTokenAmount, epTokenCalculationFromCrowdsaleTokenAmount);
numOfPurchasedTokensOnEpBy[earlyPurchaser] = SafeMath.add(numOfPurchasedTokensOnEpBy[earlyPurchaser], epTokenCount);
starbaseToken.allocateToCrowdsalePurchaser(earlyPurchaser, epTokenCount);
numOfDeliveredEarlyPurchases = SafeMath.add(j, 1);
}
return true;
}
/**
* @dev Load early purchases from the contract keeps track of them
*/
function loadEarlyPurchases() external onlyOwner returns (bool) {
if (earlyPurchasesLoaded) {
return false; // all EPs have already been loaded
}
uint256 numOfOrigEp = starbaseEpAmendment
.starbaseEarlyPurchase()
.numberOfEarlyPurchases();
for (uint256 i = numOfLoadedEarlyPurchases; i < numOfOrigEp && msg.gas > 200000; i++) {
if (starbaseEpAmendment.isInvalidEarlyPurchase(i)) {
continue;
}
var (purchaser, amount,) =
starbaseEpAmendment.isAmendedEarlyPurchase(i)
? starbaseEpAmendment.amendedEarlyPurchases(i)
: starbaseEpAmendment.earlyPurchases(i);
if (amount > 0) {
if (earlyPurchasedAmountBy[purchaser] == 0) {
earlyPurchasers.push(purchaser);
}
// each early purchaser receives 20% bonus
uint256 bonus = SafeMath.mul(amount, 20) / 100;
uint256 amountWithBonus = SafeMath.add(amount, bonus);
earlyPurchasedAmountBy[purchaser] += amountWithBonus;
}
}
numOfLoadedEarlyPurchases += i;
assert(numOfLoadedEarlyPurchases <= numOfOrigEp);
if (numOfLoadedEarlyPurchases == numOfOrigEp) {
earlyPurchasesLoaded = true; // enable the flag
}
return true;
}
/**
* @dev Set qualified crowdsale partner i.e. Bitcoin Suisse address
* @param _qualifiedPartner Address of the qualified partner that can purchase during crowdsale
* @param _amountCap Ether value which partner is able to contribute
* @param _commissionFeePercentage Integer that represents the fee to pay qualified partner 5 is 5%
*/
function setQualifiedPartner(address _qualifiedPartner, uint256 _amountCap, uint256 _commissionFeePercentage)
external
onlyOwner
{
assert(!qualifiedPartners[_qualifiedPartner].bonaFide);
qualifiedPartners[_qualifiedPartner].bonaFide = true;
qualifiedPartners[_qualifiedPartner].amountCap = _amountCap;
qualifiedPartners[_qualifiedPartner].commissionFeePercentage = _commissionFeePercentage;
QualifiedPartnerAddress(_qualifiedPartner);
}
/**
* @dev Remove address from qualified partners list.
* @param _qualifiedPartner Address to be removed from the list.
*/
function unlistQualifiedPartner(address _qualifiedPartner) external onlyOwner {
assert(qualifiedPartners[_qualifiedPartner].bonaFide);
qualifiedPartners[_qualifiedPartner].bonaFide = false;
}
/**
* @dev Update whitelisted address amount allowed to raise during the presale.
* @param _qualifiedPartner Qualified Partner address to be updated.
* @param _amountCap Amount that the address is able to raise during the presale.
*/
function updateQualifiedPartnerCapAmount(address _qualifiedPartner, uint256 _amountCap) external onlyOwner {
assert(qualifiedPartners[_qualifiedPartner].bonaFide);
qualifiedPartners[_qualifiedPartner].amountCap = _amountCap;
}
/**
* Public functions
*/
/**
* @dev Returns boolean for whether crowdsale has ended
*/
function isEnded() constant public returns (bool) {
return (endedAt > 0 && endedAt <= now);
}
/**
* @dev Returns number of purchases to date.
*/
function numOfPurchases() constant public returns (uint256) {
return crowdsalePurchases.length;
}
/**
* @dev Calculates total amount of tokens purchased includes bonus tokens.
*/
function totalAmountOfCrowdsalePurchases() constant public returns (uint256 amount) {
for (uint256 i; i < crowdsalePurchases.length; i++) {
amount = SafeMath.add(amount, crowdsalePurchases[i].amount);
}
}
/**
* @dev Calculates total amount of tokens purchased without bonus conversion.
*/
function totalAmountOfCrowdsalePurchasesWithoutBonus() constant public returns (uint256 amount) {
for (uint256 i; i < crowdsalePurchases.length; i++) {
amount = SafeMath.add(amount, crowdsalePurchases[i].rawAmount);
}
}
/**
* @dev Returns total raised amount in CNY (includes EP) and bonuses
*/
function totalRaisedAmountInCny() constant public returns (uint256) {
return SafeMath.add(totalAmountOfEarlyPurchases(), totalAmountOfCrowdsalePurchases());
}
/**
* @dev Returns total amount of early purchases in CNY
*/
function totalAmountOfEarlyPurchases() constant public returns(uint256) {
return starbaseEpAmendment.totalAmountOfEarlyPurchases();
}
/**
* @dev Allows qualified crowdsale partner to purchase Star Tokens
*/
function purchaseAsQualifiedPartner()
payable
public
rateIsSet(cnyEthRate)
returns (bool)
{
require(qualifiedPartners[msg.sender].bonaFide);
qualifiedPartners[msg.sender].amountRaised = SafeMath.add(msg.value, qualifiedPartners[msg.sender].amountRaised);
assert(qualifiedPartners[msg.sender].amountRaised <= qualifiedPartners[msg.sender].amountCap);
uint256 bonusTier = 30; // Pre sale purchasers get 30 percent bonus
uint256 rawAmount = SafeMath.mul(msg.value, cnyEthRate) / 1e18;
uint amount = recordPurchase(msg.sender, rawAmount, now, '', bonusTier);
if (qualifiedPartners[msg.sender].commissionFeePercentage > 0) {
sendQualifiedPartnerCommissionFee(msg.sender, msg.value);
}
StarBasePurchasedWithEth(msg.sender, amount, rawAmount, cnyEthRate, bonusTier);
return true;
}
/**
* @dev Allows user to purchase STAR tokens with Ether
*/
function purchaseWithEth()
payable
public
minInvestment
whenNotEnded
rateIsSet(cnyEthRate)
returns (bool)
{
require(purchaseStartBlock > 0 && block.number >= purchaseStartBlock);
if (startDate == 0) {
startCrowdsale(block.timestamp);
}
uint256 bonusTier = getBonusTier();
uint256 rawAmount = SafeMath.mul(msg.value, cnyEthRate) / 1e18;
uint amount = recordPurchase(msg.sender, rawAmount, now, '', bonusTier);
StarBasePurchasedWithEth(msg.sender, amount, rawAmount, cnyEthRate, bonusTier);
return true;
}
/**
* Internal functions
*/
/**
* @dev Initializes Starbase crowdsale
*/
function startCrowdsale(uint256 timestamp) internal {
startDate = timestamp;
// set token bonus milestones
firstBonusSalesEnds = startDate + 7 days; // 1. 1st ~ 7th day
secondBonusSalesEnds = firstBonusSalesEnds + 14 days; // 2. 8th ~ 21st day
thirdBonusSalesEnds = secondBonusSalesEnds + 14 days; // 3. 22nd ~ 35th day
fourthBonusSalesEnds = thirdBonusSalesEnds + 7 days; // 4. 36th ~ 42nd day
fifthBonusSalesEnds = fourthBonusSalesEnds + 3 days; // 5. 43rd ~ 45th day
// extended sales bonus milestones
firstExtendedBonusSalesEnds = fifthBonusSalesEnds + 3 days; // 1. 46th ~ 48th day
secondExtendedBonusSalesEnds = firstExtendedBonusSalesEnds + 3 days; // 2. 49th ~ 51st day
thirdExtendedBonusSalesEnds = secondExtendedBonusSalesEnds + 3 days; // 3. 52nd ~ 54th day
fourthExtendedBonusSalesEnds = thirdExtendedBonusSalesEnds + 3 days; // 4. 55th ~ 57th day
fifthExtendedBonusSalesEnds = fourthExtendedBonusSalesEnds + 3 days; // 5. 58th ~ 60th day
sixthExtendedBonusSalesEnds = fifthExtendedBonusSalesEnds + 60 days; // 6. 61st ~ 120th day
}
/**
* @dev Abstract record of a purchase to Tokens
* @param purchaser Address of the buyer
* @param rawAmount Amount in CNY as per the CNY/ETH rate used
* @param timestamp Timestamp at the purchase made
* @param data Identifier as an evidence of the purchase (e.g. btc:1xyzxyz)
* @param bonusTier bonus milestones of the purchase
*/
function recordPurchase(
address purchaser,
uint256 rawAmount,
uint256 timestamp,
string data,
uint256 bonusTier
)
internal
returns(uint256 amount)
{
amount = rawAmount; // amount to check reach of max cap. it does not care for bonus tokens here
// presale transfers which occurs before the crowdsale ignores the crowdsale hard cap
if (block.number >= purchaseStartBlock) {
assert(totalAmountOfCrowdsalePurchasesWithoutBonus() <= MAX_CROWDSALE_CAP);
uint256 crowdsaleTotalAmountAfterPurchase = SafeMath.add(totalAmountOfCrowdsalePurchasesWithoutBonus(), amount);
// check whether purchase goes over the cap and send the difference back to the purchaser.
if (crowdsaleTotalAmountAfterPurchase > MAX_CROWDSALE_CAP) {
uint256 difference = SafeMath.sub(crowdsaleTotalAmountAfterPurchase, MAX_CROWDSALE_CAP);
uint256 ethValueToReturn = SafeMath.mul(difference, 1e18) / cnyEthRate;
purchaser.transfer(ethValueToReturn);
amount = SafeMath.sub(amount, difference);
rawAmount = amount;
}
}
uint256 covertedAmountwWithBonus = SafeMath.mul(amount, bonusTier) / 100;
amount = SafeMath.add(amount, covertedAmountwWithBonus); // at this point amount bonus is calculated
CrowdsalePurchase memory purchase = CrowdsalePurchase(purchaser, amount, rawAmount, timestamp, data, bonusTier);
crowdsalePurchases.push(purchase);
return amount;
}
/**
* @dev Fetchs Bonus tier percentage per bonus milestones
*/
function getBonusTier() internal returns (uint256) {
bool firstBonusSalesPeriod = now >= startDate && now <= firstBonusSalesEnds; // 1st ~ 7th day get 20% bonus
bool secondBonusSalesPeriod = now > firstBonusSalesEnds && now <= secondBonusSalesEnds; // 8th ~ 21st day get 15% bonus
bool thirdBonusSalesPeriod = now > secondBonusSalesEnds && now <= thirdBonusSalesEnds; // 22nd ~ 35th day get 10% bonus
bool fourthBonusSalesPeriod = now > thirdBonusSalesEnds && now <= fourthBonusSalesEnds; // 36th ~ 42nd day get 5% bonus
bool fifthBonusSalesPeriod = now > fourthBonusSalesEnds && now <= fifthBonusSalesEnds; // 43rd and 45th day get 0% bonus
// extended bonus sales
bool firstExtendedBonusSalesPeriod = now > fifthBonusSalesEnds && now <= firstExtendedBonusSalesEnds; // extended sales 46th ~ 48th day get 20% bonus
bool secondExtendedBonusSalesPeriod = now > firstExtendedBonusSalesEnds && now <= secondExtendedBonusSalesEnds; // 49th ~ 51st 15% bonus
bool thirdExtendedBonusSalesPeriod = now > secondExtendedBonusSalesEnds && now <= thirdExtendedBonusSalesEnds; // 52nd ~ 54th day get 10% bonus
bool fourthExtendedBonusSalesPeriod = now > thirdExtendedBonusSalesEnds && now <= fourthExtendedBonusSalesEnds; // 55th ~ 57th day day get 5% bonus
bool fifthExtendedBonusSalesPeriod = now > fourthExtendedBonusSalesEnds && now <= fifthExtendedBonusSalesEnds; // 58th ~ 60th day get 0% bonus
bool sixthExtendedBonusSalesPeriod = now > fifthExtendedBonusSalesEnds && now <= sixthExtendedBonusSalesEnds; // 61st ~ 120th day get {number_of_days} - 60 * 1% bonus
if (firstBonusSalesPeriod || firstExtendedBonusSalesPeriod) return 20;
if (secondBonusSalesPeriod || secondExtendedBonusSalesPeriod) return 15;
if (thirdBonusSalesPeriod || thirdExtendedBonusSalesPeriod) return 10;
if (fourthBonusSalesPeriod || fourthExtendedBonusSalesPeriod) return 5;
if (fifthBonusSalesPeriod || fifthExtendedBonusSalesPeriod) return 0;
if (sixthExtendedBonusSalesPeriod) {
uint256 DAY_IN_SECONDS = 86400;
uint256 secondsSinceStartDate = SafeMath.sub(now, startDate);
uint256 numberOfDays = secondsSinceStartDate / DAY_IN_SECONDS;
return SafeMath.sub(numberOfDays, 60);
}
}
/**
* @dev Fetchs Bonus tier percentage per bonus milestones
* @dev qualifiedPartner Address of partners that participated in pre sale
* @dev amountSent Value sent by qualified partner
*/
function sendQualifiedPartnerCommissionFee(address qualifiedPartner, uint256 amountSent) internal {
//calculate the commission fee to send to qualified partner
uint256 commissionFeePercentageCalculationAmount = SafeMath.mul(amountSent, qualifiedPartners[qualifiedPartner].commissionFeePercentage) / 100;
// send commission fee amount
qualifiedPartner.transfer(commissionFeePercentageCalculationAmount);
}
/**
* @dev redirectToPurchase Redirect to adequate purchase function within the smart contract
*/
function redirectToPurchase() internal {
if (block.number < purchaseStartBlock) {
purchaseAsQualifiedPartner();
} else {
purchaseWithEth();
}
}
} | @title EarlyPurchase contract - Keep track of purchased amount by Early Purchasers @author Starbase PTE. LTD. - <[email protected]> | contract StarbaseEarlyPurchase {
uint256 public constant PURCHASE_AMOUNT_CAP = 9000000;
struct EarlyPurchase {
address purchaser;
}
EarlyPurchase[] public earlyPurchases;
uint256 public earlyPurchaseClosedAt;
AbstractStarbaseCrowdsale public starbaseCrowdsale;
address public owner;
modifier noEther() {
require(msg.value == 0);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyBeforeCrowdsale() {
assert(address(starbaseCrowdsale) == address(0) || starbaseCrowdsale.startDate() == 0);
_;
}
modifier onlyEarlyPurchaseTerm() {
assert(earlyPurchaseClosedAt <= 0);
_;
}
function purchasedAmountBy(address purchaser)
external
constant
noEther
returns (uint256 amount)
{
for (uint256 i; i < earlyPurchases.length; i++) {
if (earlyPurchases[i].purchaser == purchaser) {
amount += earlyPurchases[i].amount;
}
}
}
function purchasedAmountBy(address purchaser)
external
constant
noEther
returns (uint256 amount)
{
for (uint256 i; i < earlyPurchases.length; i++) {
if (earlyPurchases[i].purchaser == purchaser) {
amount += earlyPurchases[i].amount;
}
}
}
function purchasedAmountBy(address purchaser)
external
constant
noEther
returns (uint256 amount)
{
for (uint256 i; i < earlyPurchases.length; i++) {
if (earlyPurchases[i].purchaser == purchaser) {
amount += earlyPurchases[i].amount;
}
}
}
function totalAmountOfEarlyPurchases()
constant
noEther
public
returns (uint256 totalAmount)
{
for (uint256 i; i < earlyPurchases.length; i++) {
totalAmount += earlyPurchases[i].amount;
}
}
function totalAmountOfEarlyPurchases()
constant
noEther
public
returns (uint256 totalAmount)
{
for (uint256 i; i < earlyPurchases.length; i++) {
totalAmount += earlyPurchases[i].amount;
}
}
function numberOfEarlyPurchases()
external
constant
noEther
returns (uint256)
{
return earlyPurchases.length;
}
function appendEarlyPurchase(address purchaser, uint256 amount, uint256 purchasedAt)
external
noEther
onlyOwner
onlyBeforeCrowdsale
onlyEarlyPurchaseTerm
returns (bool)
{
if (amount == 0 ||
totalAmountOfEarlyPurchases() + amount > PURCHASE_AMOUNT_CAP)
{
return false;
}
assert(purchasedAt != 0 || purchasedAt <= now);
earlyPurchases.push(EarlyPurchase(purchaser, amount, purchasedAt));
return true;
}
function appendEarlyPurchase(address purchaser, uint256 amount, uint256 purchasedAt)
external
noEther
onlyOwner
onlyBeforeCrowdsale
onlyEarlyPurchaseTerm
returns (bool)
{
if (amount == 0 ||
totalAmountOfEarlyPurchases() + amount > PURCHASE_AMOUNT_CAP)
{
return false;
}
assert(purchasedAt != 0 || purchasedAt <= now);
earlyPurchases.push(EarlyPurchase(purchaser, amount, purchasedAt));
return true;
}
function closeEarlyPurchase()
external
noEther
onlyOwner
returns (bool)
{
earlyPurchaseClosedAt = now;
}
function setup(address starbaseCrowdsaleAddress)
external
noEther
onlyOwner
returns (bool)
{
if (address(starbaseCrowdsale) == 0) {
starbaseCrowdsale = AbstractStarbaseCrowdsale(starbaseCrowdsaleAddress);
return true;
}
return false;
}
function setup(address starbaseCrowdsaleAddress)
external
noEther
onlyOwner
returns (bool)
{
if (address(starbaseCrowdsale) == 0) {
starbaseCrowdsale = AbstractStarbaseCrowdsale(starbaseCrowdsaleAddress);
return true;
}
return false;
}
function StarbaseEarlyPurchase() noEther {
owner = msg.sender;
}
}
| 12,901,576 | [
1,
41,
20279,
23164,
6835,
300,
10498,
3298,
434,
5405,
343,
8905,
3844,
635,
512,
20279,
14466,
343,
345,
414,
225,
934,
297,
1969,
453,
1448,
18,
11807,
40,
18,
300,
411,
1376,
36,
10983,
1969,
18,
2894,
34,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
934,
297,
1969,
41,
20279,
23164,
288,
203,
565,
2254,
5034,
1071,
5381,
26345,
1792,
4429,
67,
2192,
51,
5321,
67,
17296,
273,
2468,
9449,
31,
203,
203,
565,
1958,
512,
20279,
23164,
288,
203,
3639,
1758,
5405,
343,
14558,
31,
203,
565,
289,
203,
203,
203,
565,
512,
20279,
23164,
8526,
1071,
11646,
10262,
343,
3304,
31,
203,
565,
2254,
5034,
1071,
11646,
23164,
7395,
861,
31,
203,
203,
565,
4115,
18379,
1969,
39,
492,
2377,
5349,
1071,
10443,
1969,
39,
492,
2377,
5349,
31,
203,
565,
1758,
1071,
3410,
31,
203,
565,
9606,
1158,
41,
1136,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
1132,
422,
374,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
4649,
39,
492,
2377,
5349,
1435,
288,
203,
3639,
1815,
12,
2867,
12,
10983,
1969,
39,
492,
2377,
5349,
13,
422,
1758,
12,
20,
13,
747,
10443,
1969,
39,
492,
2377,
5349,
18,
1937,
1626,
1435,
422,
374,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
41,
20279,
23164,
4065,
1435,
288,
203,
3639,
1815,
12,
2091,
715,
23164,
7395,
861,
1648,
374,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
203,
565,
445,
5405,
343,
8905,
6275,
858,
12,
2867,
5405,
343,
14558,
13,
203,
3639,
3903,
203,
3639,
5381,
203,
3639,
1158,
41,
1136,
203,
3639,
1135,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Library Imports */
import {AddressAliasHelper} from '../../standards/AddressAliasHelper.sol';
import {Lib_OVMCodec} from '../../libraries/codec/Lib_OVMCodec.sol';
import {Lib_AddressResolver} from '../../libraries/resolver/Lib_AddressResolver.sol';
/* Interface Imports */
import {ICanonicalTransactionChain} from './ICanonicalTransactionChain.sol';
import {IChainStorageContainer} from './IChainStorageContainer.sol';
/**
* @title CanonicalTransactionChain
* @dev The Canonical Transaction Chain (CTC) contract is an append-only log of transactions
* which must be applied to the rollup state. It defines the ordering of rollup transactions by
* writing them to the 'CTC:batches' instance of the Chain Storage Container.
* The CTC also allows any account to 'enqueue' an L2 transaction, which will require that the
* Sequencer will eventually append it to the rollup state.
*
* Runtime target: EVM
*/
contract CanonicalTransactionChain is
ICanonicalTransactionChain,
Lib_AddressResolver
{
/*************
* Constants *
*************/
// L2 tx gas-related
uint256 public constant MIN_ROLLUP_TX_GAS = 100000;
uint256 public constant MAX_ROLLUP_TX_SIZE = 50000;
// The approximate cost of calling the enqueue function
uint256 public enqueueGasCost;
// The ratio of the cost of L1 gas to the cost of L2 gas
uint256 public l2GasDiscountDivisor;
// The amount of L2 gas which can be forwarded to L2 without spam prevention via 'gas burn'.
// Calculated as the product of l2GasDiscountDivisor * enqueueGasCost.
// See comments in enqueue() for further detail.
uint256 public enqueueL2GasPrepaid;
// Encoding-related (all in bytes)
uint256 internal constant BATCH_CONTEXT_SIZE = 16;
uint256 internal constant BATCH_CONTEXT_LENGTH_POS = 12;
uint256 internal constant BATCH_CONTEXT_START_POS = 15;
uint256 internal constant TX_DATA_HEADER_SIZE = 3;
uint256 internal constant BYTES_TILL_TX_DATA = 65;
/*************
* Variables *
*************/
uint256 public maxTransactionGasLimit;
/***************
* Queue State *
***************/
uint40 private _nextQueueIndex; // index of the first queue element not yet included
Lib_OVMCodec.QueueElement[] queueElements;
/***************
* Constructor *
***************/
constructor(
address _libAddressManager,
uint256 _maxTransactionGasLimit,
uint256 _l2GasDiscountDivisor,
uint256 _enqueueGasCost
) Lib_AddressResolver(_libAddressManager) {
maxTransactionGasLimit = _maxTransactionGasLimit;
l2GasDiscountDivisor = _l2GasDiscountDivisor;
enqueueGasCost = _enqueueGasCost;
enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost;
}
/**********************
* Function Modifiers *
**********************/
/**
* Modifier to enforce that, if configured, only the Burn Admin may
* successfully call a method.
*/
modifier onlyBurnAdmin() {
require(
msg.sender == libAddressManager.owner(),
'Only callable by the Burn Admin.'
);
_;
}
/*******************************
* Authorized Setter Functions *
*******************************/
/**
* Allows the Burn Admin to update the parameters which determine the amount of gas to burn.
* The value of enqueueL2GasPrepaid is immediately updated as well.
*/
function setGasParams(uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost)
external
onlyBurnAdmin
{
enqueueGasCost = _enqueueGasCost;
l2GasDiscountDivisor = _l2GasDiscountDivisor;
// See the comment in enqueue() for the rationale behind this formula.
enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost;
emit L2GasParamsUpdated(
l2GasDiscountDivisor,
enqueueGasCost,
enqueueL2GasPrepaid
);
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches() public view returns (IChainStorageContainer) {
return IChainStorageContainer(resolve('ChainStorageContainer-CTC-batches'));
}
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue() public view returns (IChainStorageContainer) {
return IChainStorageContainer(resolve('ChainStorageContainer-CTC-queue'));
}
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() public view returns (uint256 _totalElements) {
(uint40 totalElements, , , ) = _getBatchExtraData();
return uint256(totalElements);
}
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() public view returns (uint256 _totalBatches) {
return batches().length();
}
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex() public view returns (uint40) {
return _nextQueueIndex;
}
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp() public view returns (uint40) {
(, , uint40 lastTimestamp, ) = _getBatchExtraData();
return lastTimestamp;
}
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber() public view returns (uint40) {
(, , , uint40 lastBlockNumber) = _getBatchExtraData();
return lastBlockNumber;
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(uint256 _index)
public
view
returns (Lib_OVMCodec.QueueElement memory _element)
{
return queueElements[_index];
}
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements() public view returns (uint40) {
return uint40(queueElements.length) - _nextQueueIndex;
}
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength() public view returns (uint40) {
return uint40(queueElements.length);
}
/**
* Adds a transaction to the queue.
* @param _target Target L2 contract to send the transaction to.
* @param _gasLimit Gas limit for the enqueued L2 transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
) external {
require(
_data.length <= MAX_ROLLUP_TX_SIZE,
'Transaction data size exceeds maximum for rollup transaction.'
);
require(
_gasLimit <= maxTransactionGasLimit,
'Transaction gas limit exceeds maximum for rollup transaction.'
);
require(
_gasLimit >= MIN_ROLLUP_TX_GAS,
'Transaction gas limit too low to enqueue.'
);
// Transactions submitted to the queue lack a method for paying gas fees to the Sequencer.
// So we need to prevent spam attacks by ensuring that the cost of enqueueing a transaction
// from L1 to L2 is not underpriced. For transaction with a high L2 gas limit, we do this by
// burning some extra gas on L1. Of course there is also some intrinsic cost to enqueueing a
// transaction, so we want to make sure not to over-charge (by burning too much L1 gas).
// Therefore, we define 'enqueueL2GasPrepaid' as the L2 gas limit above which we must burn
// additional gas on L1. This threshold is the product of two inputs:
// 1. enqueueGasCost: the base cost of calling this function.
// 2. l2GasDiscountDivisor: the ratio between the cost of gas on L1 and L2. This is a
// positive integer, meaning we assume L2 gas is always less costly.
// The calculation below for gasToConsume can be seen as converting the difference (between
// the specified L2 gas limit and the prepaid L2 gas limit) to an L1 gas amount.
if (_gasLimit > enqueueL2GasPrepaid) {
uint256 gasToConsume = (_gasLimit - enqueueL2GasPrepaid) /
l2GasDiscountDivisor;
uint256 startingGas = gasleft();
// Although this check is not necessary (burn below will run out of gas if not true), it
// gives the user an explicit reason as to why the enqueue attempt failed.
require(
startingGas > gasToConsume,
'Insufficient gas for L2 rate limiting burn.'
);
uint256 i;
while (startingGas - gasleft() < gasToConsume) {
i++;
}
}
// Apply an aliasing unless msg.sender == tx.origin. This prevents an attack in which a
// contract on L1 has the same address as a contract on L2 but doesn't have the same code.
// We can safely ignore this for EOAs because they're guaranteed to have the same "code"
// (i.e. no code at all). This also makes it possible for users to interact with contracts
// on L2 even when the Sequencer is down.
address sender;
if (msg.sender == tx.origin) {
sender = msg.sender;
} else {
sender = AddressAliasHelper.applyL1ToL2Alias(msg.sender);
}
bytes32 transactionHash = keccak256(
abi.encode(sender, _target, _gasLimit, _data)
);
queueElements.push(
Lib_OVMCodec.QueueElement({
transactionHash: transactionHash,
timestamp: uint40(block.timestamp),
blockNumber: uint40(block.number)
})
);
uint256 queueIndex = queueElements.length - 1;
emit TransactionEnqueued(
sender,
_target,
_gasLimit,
_data,
queueIndex,
block.timestamp
);
}
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch() external {
uint40 shouldStartAtElement;
uint24 totalElementsToAppend;
uint24 numContexts;
assembly {
shouldStartAtElement := shr(216, calldataload(4))
totalElementsToAppend := shr(232, calldataload(9))
numContexts := shr(232, calldataload(12))
}
require(
shouldStartAtElement == getTotalElements(),
'Actual batch start index does not match expected start index.'
);
require(
msg.sender == resolve('OVM_Sequencer'),
'Function can only be called by the Sequencer.'
);
uint40 nextTransactionPtr = uint40(
BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts
);
require(
msg.data.length >= nextTransactionPtr,
'Not enough BatchContexts provided.'
);
// Counter for number of sequencer transactions appended so far.
uint32 numSequencerTransactions = 0;
// Cache the _nextQueueIndex storage variable to a temporary stack variable.
// This is safe as long as nothing reads or writes to the storage variable
// until it is updated by the temp variable.
uint40 nextQueueIndex = _nextQueueIndex;
BatchContext memory curContext;
for (uint32 i = 0; i < numContexts; i++) {
BatchContext memory nextContext = _getBatchContext(i);
// Now we can update our current context.
curContext = nextContext;
// Process sequencer transactions first.
numSequencerTransactions += uint32(curContext.numSequencedTransactions);
// Now process any subsequent queue transactions.
nextQueueIndex += uint40(curContext.numSubsequentQueueTransactions);
}
require(
nextQueueIndex <= queueElements.length,
'Attempted to append more elements than are available in the queue.'
);
// Generate the required metadata that we need to append this batch
uint40 numQueuedTransactions = totalElementsToAppend -
numSequencerTransactions;
uint40 blockTimestamp;
uint40 blockNumber;
if (curContext.numSubsequentQueueTransactions == 0) {
// The last element is a sequencer tx, therefore pull timestamp and block number from
// the last context.
blockTimestamp = uint40(curContext.timestamp);
blockNumber = uint40(curContext.blockNumber);
} else {
// The last element is a queue tx, therefore pull timestamp and block number from the
// queue element.
// curContext.numSubsequentQueueTransactions > 0 which means that we've processed at
// least one queue element. We increment nextQueueIndex after processing each queue
// element, so the index of the last element we processed is nextQueueIndex - 1.
Lib_OVMCodec.QueueElement memory lastElement = queueElements[
nextQueueIndex - 1
];
blockTimestamp = lastElement.timestamp;
blockNumber = lastElement.blockNumber;
}
// Cache the previous blockhash to ensure all transaction data can be retrieved efficiently.
_appendBatch(
blockhash(block.number - 1),
totalElementsToAppend,
numQueuedTransactions,
blockTimestamp,
blockNumber
);
emit SequencerBatchAppended(
nextQueueIndex - numQueuedTransactions,
numQueuedTransactions,
getTotalElements()
);
// Update the _nextQueueIndex storage variable.
_nextQueueIndex = nextQueueIndex;
}
/**********************
* Internal Functions *
**********************/
/**
* Returns the BatchContext located at a particular index.
* @param _index The index of the BatchContext
* @return The BatchContext at the specified index.
*/
function _getBatchContext(uint256 _index)
internal
pure
returns (BatchContext memory)
{
uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE;
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 ctxTimestamp;
uint256 ctxBlockNumber;
assembly {
numSequencedTransactions := shr(232, calldataload(contextPtr))
numSubsequentQueueTransactions := shr(
232,
calldataload(add(contextPtr, 3))
)
ctxTimestamp := shr(216, calldataload(add(contextPtr, 6)))
ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11)))
}
return
BatchContext({
numSequencedTransactions: numSequencedTransactions,
numSubsequentQueueTransactions: numSubsequentQueueTransactions,
timestamp: ctxTimestamp,
blockNumber: ctxBlockNumber
});
}
/**
* Parses the batch context from the extra data.
* @return Total number of elements submitted.
* @return Index of the next queue element.
*/
function _getBatchExtraData()
internal
view
returns (
uint40,
uint40,
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadata();
uint40 totalElements;
uint40 nextQueueIndex;
uint40 lastTimestamp;
uint40 lastBlockNumber;
// solhint-disable max-line-length
assembly {
extraData := shr(40, extraData)
totalElements := and(
extraData,
0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF
)
nextQueueIndex := shr(
40,
and(
extraData,
0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000
)
)
lastTimestamp := shr(
80,
and(
extraData,
0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000
)
)
lastBlockNumber := shr(
120,
and(
extraData,
0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000
)
)
}
// solhint-enable max-line-length
return (totalElements, nextQueueIndex, lastTimestamp, lastBlockNumber);
}
/**
* Encodes the batch context for the extra data.
* @param _totalElements Total number of elements submitted.
* @param _nextQueueIdx Index of the next queue element.
* @param _timestamp Timestamp for the last batch.
* @param _blockNumber Block number of the last batch.
* @return Encoded batch context.
*/
function _makeBatchExtraData(
uint40 _totalElements,
uint40 _nextQueueIdx,
uint40 _timestamp,
uint40 _blockNumber
) internal pure returns (bytes27) {
bytes27 extraData;
assembly {
extraData := _totalElements
extraData := or(extraData, shl(40, _nextQueueIdx))
extraData := or(extraData, shl(80, _timestamp))
extraData := or(extraData, shl(120, _blockNumber))
extraData := shl(40, extraData)
}
return extraData;
}
/**
* Inserts a batch into the chain of batches.
* @param _transactionRoot Root of the transaction tree for this batch.
* @param _batchSize Number of elements in the batch.
* @param _numQueuedTransactions Number of queue transactions in the batch.
* @param _timestamp The latest batch timestamp.
* @param _blockNumber The latest batch blockNumber.
*/
function _appendBatch(
bytes32 _transactionRoot,
uint256 _batchSize,
uint256 _numQueuedTransactions,
uint40 _timestamp,
uint40 _blockNumber
) internal {
IChainStorageContainer batchesRef = batches();
(uint40 totalElements, uint40 nextQueueIndex, , ) = _getBatchExtraData();
Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec
.ChainBatchHeader({
batchIndex: batchesRef.length(),
batchRoot: _transactionRoot,
batchSize: _batchSize,
prevTotalElements: totalElements,
extraData: hex''
});
emit TransactionBatchAppended(
header.batchIndex,
header.batchRoot,
header.batchSize,
header.prevTotalElements,
header.extraData
);
bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header);
bytes27 latestBatchContext = _makeBatchExtraData(
totalElements + uint40(header.batchSize),
nextQueueIndex + uint40(_numQueuedTransactions),
_timestamp,
_blockNumber
);
batchesRef.push(batchHeaderHash, latestBatchContext);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.8.7;
library AddressAliasHelper {
uint160 constant offset = uint160(0x1111000000000000000000000000000000001111);
/// @notice Utility function that converts the address in the L1 that submitted a tx to
/// the inbox to the msg.sender viewed in the L2
/// @param l1Address the address in the L1 that triggered the tx to L2
/// @return l2Address L2 address as viewed in msg.sender
function applyL1ToL2Alias(address l1Address)
internal
pure
returns (address l2Address)
{
unchecked {
l2Address = address(uint160(l1Address) + offset);
}
}
/// @notice Utility function that converts the msg.sender viewed in the L2 to the
/// address in the L1 that submitted a tx to the inbox
/// @param l2Address L2 address as viewed in msg.sender
/// @return l1Address the address in the L1 that triggered the tx to L2
function undoL1ToL2Alias(address l2Address)
internal
pure
returns (address l1Address)
{
unchecked {
l1Address = address(uint160(l2Address) - offset);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Library Imports */
import {Lib_RLPReader} from '../rlp/Lib_RLPReader.sol';
import {Lib_RLPWriter} from '../rlp/Lib_RLPWriter.sol';
import {Lib_BytesUtils} from '../utils/Lib_BytesUtils.sol';
import {Lib_Bytes32Utils} from '../utils/Lib_Bytes32Utils.sol';
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(Transaction memory _transaction)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(Transaction memory _transaction)
internal
pure
returns (bytes32)
{
return keccak256(encodeTransaction(_transaction));
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(bytes memory _encoded)
internal
pure
returns (EVMAccount memory)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(
_encoded
);
return
EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Library Imports */
import {Lib_AddressManager} from './Lib_AddressManager.sol';
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(address _libAddressManager) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(string memory _name) public view returns (address) {
return libAddressManager.getAddress(_name);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.9.0;
/* Library Imports */
import {Lib_OVMCodec} from '../../libraries/codec/Lib_OVMCodec.sol';
/* Interface Imports */
import {IChainStorageContainer} from './IChainStorageContainer.sol';
/**
* @title ICanonicalTransactionChain
*/
interface ICanonicalTransactionChain {
/**********
* Events *
**********/
event L2GasParamsUpdated(
uint256 l2GasDiscountDivisor,
uint256 enqueueGasCost,
uint256 enqueueL2GasPrepaid
);
event TransactionEnqueued(
address indexed _l1TxOrigin,
address indexed _target,
uint256 _gasLimit,
bytes _data,
uint256 indexed _queueIndex,
uint256 _timestamp
);
event QueueBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event SequencerBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event TransactionBatchAppended(
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
/***********
* Structs *
***********/
struct BatchContext {
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 timestamp;
uint256 blockNumber;
}
/*******************************
* Authorized Setter Functions *
*******************************/
/**
* Allows the Burn Admin to update the parameters which determine the amount of gas to burn.
* The value of enqueueL2GasPrepaid is immediately updated as well.
*/
function setGasParams(uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost)
external;
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches() external view returns (IChainStorageContainer);
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue() external view returns (IChainStorageContainer);
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() external view returns (uint256 _totalElements);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() external view returns (uint256 _totalBatches);
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex() external view returns (uint40);
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(uint256 _index)
external
view
returns (Lib_OVMCodec.QueueElement memory _element);
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp() external view returns (uint40);
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber() external view returns (uint40);
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements() external view returns (uint40);
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength() external view returns (uint40);
/**
* Adds a transaction to the queue.
* @param _target Target contract to send the transaction to.
* @param _gasLimit Gas limit for the given transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
) external;
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch(
// uint40 _shouldStartAtElement,
// uint24 _totalElementsToAppend,
// BatchContext[] _contexts,
// bytes[] _transactionDataFields
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.9.0;
/**
* @title IChainStorageContainer
*/
interface IChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(bytes27 _globalMetadata) external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata() external view returns (bytes27);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length() external view returns (uint256);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(bytes32 _object) external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(bytes32 _object, bytes27 _globalMetadata) external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(uint256 _index) external view returns (bytes32);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(uint256 _index) external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 internal constant MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) {
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({length: _in.length, ptr: ptr});
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(RLPItem memory _in)
internal
pure
returns (RLPItem[] memory)
{
(uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.LIST_ITEM, 'Invalid RLP list value.');
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(
itemCount < MAX_LIST_LENGTH,
'Provided RLP list exceeds max list length.'
);
(uint256 itemOffset, uint256 itemLength, ) = _decodeLength(
RLPItem({length: _in.length - offset, ptr: _in.ptr + offset})
);
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(bytes memory _in) internal pure returns (RLPItem[] memory) {
return readList(toRLPItem(_in));
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(RLPItem memory _in) internal pure returns (bytes memory) {
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, 'Invalid RLP bytes value.');
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(bytes memory _in) internal pure returns (bytes memory) {
return readBytes(toRLPItem(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(RLPItem memory _in)
internal
pure
returns (string memory)
{
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(bytes memory _in) internal pure returns (string memory) {
return readString(toRLPItem(_in));
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(RLPItem memory _in) internal pure returns (bytes32) {
require(_in.length <= 33, 'Invalid RLP bytes32 value.');
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, 'Invalid RLP bytes32 value.');
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(bytes memory _in) internal pure returns (bytes32) {
return readBytes32(toRLPItem(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(RLPItem memory _in) internal pure returns (uint256) {
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(bytes memory _in) internal pure returns (uint256) {
return readUint256(toRLPItem(_in));
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(RLPItem memory _in) internal pure returns (bool) {
require(_in.length == 1, 'Invalid RLP boolean value.');
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(
out == 0 || out == 1,
'Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1'
);
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(bytes memory _in) internal pure returns (bool) {
return readBool(toRLPItem(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(RLPItem memory _in) internal pure returns (address) {
if (_in.length == 1) {
return address(0);
}
require(_in.length == 21, 'Invalid RLP address value.');
return address(uint160(readUint256(_in)));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(bytes memory _in) internal pure returns (address) {
return readAddress(toRLPItem(_in));
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(RLPItem memory _in)
internal
pure
returns (bytes memory)
{
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(RLPItem memory _in)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(_in.length > 0, 'RLP item cannot be null.');
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(_in.length > strLen, 'Invalid RLP short string.');
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(_in.length > lenOfStrLen, 'Invalid RLP long string length.');
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)))
}
require(_in.length > lenOfStrLen + strLen, 'Invalid RLP long string.');
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(_in.length > listLen, 'Invalid RLP short list.');
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(_in.length > lenOfListLen, 'Invalid RLP long list length.');
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)))
}
require(_in.length > lenOfListLen + listLen, 'Invalid RLP long list.');
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
) private pure returns (bytes memory) {
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask;
unchecked {
mask = 256**(32 - (_length % 32)) - 1;
}
assembly {
mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask)))
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(RLPItem memory _in) private pure returns (bytes memory) {
return _copy(_in.ptr, 0, _in.length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(bytes[] memory _in) internal pure returns (bytes memory) {
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(string memory _in) internal pure returns (bytes memory) {
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(address _in) internal pure returns (bytes memory) {
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(uint256 _in) internal pure returns (bytes memory) {
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(bool _in) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(uint256 _len, uint256 _offset)
private
pure
returns (bytes memory)
{
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = bytes1(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask;
unchecked {
mask = 256**(32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly {
flattenedPtr := add(flattened, 0x20)
}
for (i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly {
listPtr := add(item, 0x20)
}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, 'slice_overflow');
require(_start + _length >= _start, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(
add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))),
_start
)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(bytes memory _bytes, uint256 _start)
internal
pure
returns (bytes memory)
{
if (_start >= _bytes.length) {
return bytes('');
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32(bytes memory _bytes) internal pure returns (bytes32) {
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(bytes memory _bytes) internal pure returns (uint256) {
return uint256(toBytes32(_bytes));
}
function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(bytes memory _bytes)
internal
pure
returns (bytes memory)
{
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(bytes memory _bytes, bytes memory _other)
internal
pure
returns (bool)
{
return keccak256(_bytes) == keccak256(_other);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(bytes32 _in) internal pure returns (bool) {
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(bool _in) internal pure returns (bytes32) {
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(bytes32 _in) internal pure returns (address) {
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(address _in) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_in)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* External Imports */
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(
string indexed _name,
address _newAddress,
address _oldAddress
);
/*************
* Variables *
*************/
mapping(bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(string memory _name, address _address)
external
onlyOwner
{
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(_name, _address, oldAddress);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(string memory _name) external view returns (address) {
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(string memory _name) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_name));
}
}
// 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;
/**
* @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;
}
} | * @title Lib_AddressResolver/ | abstract contract Lib_AddressResolver {
Lib_AddressManager public libAddressManager;
pragma solidity ^0.8.9;
import {Lib_AddressManager} from './Lib_AddressManager.sol';
constructor(address _libAddressManager) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
function resolve(string memory _name) public view returns (address) {
return libAddressManager.getAddress(_name);
}
}
| 1,596,351 | [
1,
5664,
67,
1887,
4301,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
10560,
67,
1887,
4301,
288,
203,
203,
225,
10560,
67,
1887,
1318,
1071,
2561,
1887,
1318,
31,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
31,
203,
5666,
288,
5664,
67,
1887,
1318,
97,
628,
12871,
5664,
67,
1887,
1318,
18,
18281,
13506,
203,
225,
3885,
12,
2867,
389,
2941,
1887,
1318,
13,
288,
203,
565,
2561,
1887,
1318,
273,
10560,
67,
1887,
1318,
24899,
2941,
1887,
1318,
1769,
203,
225,
289,
203,
203,
203,
225,
445,
2245,
12,
1080,
3778,
389,
529,
13,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
565,
327,
2561,
1887,
1318,
18,
588,
1887,
24899,
529,
1769,
203,
225,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-02-12
*/
pragma solidity 0.8.0;
pragma abicoder v2;
interface MassetStructs {
struct BassetPersonal {
// Address of the bAsset
address addr;
// Address of the bAsset
address integrator;
// An ERC20 can charge transfer fee, for example USDT, DGX tokens.
bool hasTxFee; // takes a byte in storage
// Status of the bAsset
BassetStatus status;
}
struct BassetData {
// 1 Basset * ratio / ratioScale == x Masset (relative value)
// If ratio == 10e8 then 1 bAsset = 10 mAssets
// A ratio is divised as 10^(18-tokenDecimals) * measurementMultiple(relative value of 1 base unit)
uint128 ratio;
// Amount of the Basset that is held in Collateral
uint128 vaultBalance;
}
// Status of the Basset - has it broken its peg?
enum BassetStatus {
Default,
Normal,
BrokenBelowPeg,
BrokenAbovePeg,
Blacklisted,
Liquidating,
Liquidated,
Failed
}
struct BasketState {
bool undergoingRecol;
bool failed;
}
struct InvariantConfig {
uint256 a;
WeightLimits limits;
}
struct WeightLimits {
uint128 min;
uint128 max;
}
struct AmpData {
uint64 initialA;
uint64 targetA;
uint64 rampStartTime;
uint64 rampEndTime;
}
}
abstract contract IInvariantValidator is MassetStructs {
// Mint
function computeMint(
BassetData[] calldata _bAssets,
uint8 _i,
uint256 _rawInput,
InvariantConfig memory _config
) external view virtual returns (uint256);
function computeMintMulti(
BassetData[] calldata _bAssets,
uint8[] calldata _indices,
uint256[] calldata _rawInputs,
InvariantConfig memory _config
) external view virtual returns (uint256);
// Swap
function computeSwap(
BassetData[] calldata _bAssets,
uint8 _i,
uint8 _o,
uint256 _rawInput,
uint256 _feeRate,
InvariantConfig memory _config
) external view virtual returns (uint256, uint256);
// Redeem
function computeRedeem(
BassetData[] calldata _bAssets,
uint8 _i,
uint256 _mAssetQuantity,
InvariantConfig memory _config
) external view virtual returns (uint256);
function computeRedeemExact(
BassetData[] calldata _bAssets,
uint8[] calldata _indices,
uint256[] calldata _rawOutputs,
InvariantConfig memory _config
) external view virtual returns (uint256);
}
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
/*
* @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 {
// 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 payable(msg.sender);
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the 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);
}
contract ERC205 is Context, IERC20 {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public 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 override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_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 returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] -= amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] -= amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()] - amount);
}
}
abstract contract InitializableERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
abstract contract InitializableToken is ERC205, InitializableERC20Detailed {
/**
* @dev Initialization function for implementing contract
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(string memory _nameArg, string memory _symbolArg) internal {
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
}
}
contract ModuleKeys {
// Governance
// ===========
// keccak256("Governance");
bytes32 internal constant KEY_GOVERNANCE =
0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d;
//keccak256("Staking");
bytes32 internal constant KEY_STAKING =
0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034;
//keccak256("ProxyAdmin");
bytes32 internal constant KEY_PROXY_ADMIN =
0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
// mStable
// =======
// keccak256("OracleHub");
bytes32 internal constant KEY_ORACLE_HUB =
0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040;
// keccak256("Manager");
bytes32 internal constant KEY_MANAGER =
0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
//keccak256("Recollateraliser");
bytes32 internal constant KEY_RECOLLATERALISER =
0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
//keccak256("MetaToken");
bytes32 internal constant KEY_META_TOKEN =
0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2;
// keccak256("SavingsManager");
bytes32 internal constant KEY_SAVINGS_MANAGER =
0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1;
// keccak256("Liquidator");
bytes32 internal constant KEY_LIQUIDATOR =
0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4;
}
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
abstract contract ImmutableModule is ModuleKeys {
INexus public immutable nexus;
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
*/
constructor(address _nexus) {
require(_nexus != address(0), "Nexus address is zero");
nexus = INexus(_nexus);
}
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
_onlyGovernor();
_;
}
function _onlyGovernor() internal view {
require(msg.sender == _governor(), "Only governor can execute");
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the ProxyAdmin.
*/
modifier onlyProxyAdmin() {
require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute");
_;
}
/**
* @dev Modifier to allow function calls only from the Manager.
*/
modifier onlyManager() {
require(msg.sender == _manager(), "Only manager can execute");
_;
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return Staking Module address from the Nexus
* @return Address of the Staking Module contract
*/
function _staking() internal view returns (address) {
return nexus.getModule(KEY_STAKING);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
/**
* @dev Return MetaToken Module address from the Nexus
* @return Address of the MetaToken Module contract
*/
function _metaToken() internal view returns (address) {
return nexus.getModule(KEY_META_TOKEN);
}
/**
* @dev Return OracleHub Module address from the Nexus
* @return Address of the OracleHub Module contract
*/
function _oracleHub() internal view returns (address) {
return nexus.getModule(KEY_ORACLE_HUB);
}
/**
* @dev Return Manager Module address from the Nexus
* @return Address of the Manager Module contract
*/
function _manager() internal view returns (address) {
return nexus.getModule(KEY_MANAGER);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
}
contract InitializableReentrancyGuard {
bool private _notEntered;
function _initializeReentrancyGuard() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
abstract contract IMasset is MassetStructs {
// Mint
function mint(
address _input,
uint256 _inputQuantity,
uint256 _minOutputQuantity,
address _recipient
) external virtual returns (uint256 mintOutput);
function mintMulti(
address[] calldata _inputs,
uint256[] calldata _inputQuantities,
uint256 _minOutputQuantity,
address _recipient
) external virtual returns (uint256 mintOutput);
function getMintOutput(address _input, uint256 _inputQuantity)
external
view
virtual
returns (uint256 mintOutput);
function getMintMultiOutput(address[] calldata _inputs, uint256[] calldata _inputQuantities)
external
view
virtual
returns (uint256 mintOutput);
// Swaps
function swap(
address _input,
address _output,
uint256 _inputQuantity,
uint256 _minOutputQuantity,
address _recipient
) external virtual returns (uint256 swapOutput);
function getSwapOutput(
address _input,
address _output,
uint256 _inputQuantity
) external view virtual returns (uint256 swapOutput);
// Redemption
function redeem(
address _output,
uint256 _mAssetQuantity,
uint256 _minOutputQuantity,
address _recipient
) external virtual returns (uint256 outputQuantity);
function redeemMasset(
uint256 _mAssetQuantity,
uint256[] calldata _minOutputQuantities,
address _recipient
) external virtual returns (uint256[] memory outputQuantities);
function redeemExactBassets(
address[] calldata _outputs,
uint256[] calldata _outputQuantities,
uint256 _maxMassetQuantity,
address _recipient
) external virtual returns (uint256 mAssetRedeemed);
function getRedeemOutput(address _output, uint256 _mAssetQuantity)
external
view
virtual
returns (uint256 bAssetOutput);
function getRedeemExactBassetsOutput(
address[] calldata _outputs,
uint256[] calldata _outputQuantities
) external view virtual returns (uint256 mAssetAmount);
// Views
function getBasket() external view virtual returns (bool, bool);
function getBasset(address _token)
external
view
virtual
returns (BassetPersonal memory personal, BassetData memory data);
function getBassets()
external
view
virtual
returns (BassetPersonal[] memory personal, BassetData[] memory data);
function bAssetIndexes(address) external view virtual returns (uint8);
// SavingsManager
function collectInterest() external virtual returns (uint256 swapFeesGained, uint256 newSupply);
function collectPlatformInterest()
external
virtual
returns (uint256 mintAmount, uint256 newSupply);
// Admin
function setCacheSize(uint256 _cacheSize) external virtual;
function upgradeForgeValidator(address _newForgeValidator) external virtual;
function setFees(uint256 _swapFee, uint256 _redemptionFee) external virtual;
function setTransferFeesFlag(address _bAsset, bool _flag) external virtual;
function migrateBassets(address[] calldata _bAssets, address _newIntegration) external virtual;
}
abstract contract Deprecated_BasketManager is MassetStructs {}
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
library StableMath {
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x) internal pure returns (uint256) {
return x * FULL_SCALE;
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
// return 9e38 / 1e18 = 9e18
return (x * y) / scale;
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x * y;
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled + FULL_SCALE - 1;
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil / FULL_SCALE;
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e18 * 1e18 = 8e36
// e.g. 8e36 / 10e18 = 8e17
return (x * FULL_SCALE) / y;
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return c Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) {
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x * ratio;
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled + RATIO_SCALE - 1;
// return 100..00.999e8 / 1e8 = 1e18
return ceil / RATIO_SCALE;
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return c Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
// e.g. 1e14 * 1e8 = 1e22
// return 1e22 / 1e12 = 1e10
return (x * RATIO_SCALE) / ratio;
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) {
return x > upperBound ? upperBound : x;
}
}
interface IPlatformIntegration {
/**
* @dev Deposit the given bAsset to Lending platform
* @param _bAsset bAsset address
* @param _amount Amount to deposit
*/
function deposit(
address _bAsset,
uint256 _amount,
bool isTokenFeeCharged
) external returns (uint256 quantityDeposited);
/**
* @dev Withdraw given bAsset from Lending platform
*/
function withdraw(
address _receiver,
address _bAsset,
uint256 _amount,
bool _hasTxFee
) external;
/**
* @dev Withdraw given bAsset from Lending platform
*/
function withdraw(
address _receiver,
address _bAsset,
uint256 _amount,
uint256 _totalAmount,
bool _hasTxFee
) external;
/**
* @dev Withdraw given bAsset from the cache
*/
function withdrawRaw(
address _receiver,
address _bAsset,
uint256 _amount
) external;
/**
* @dev Returns the current balance of the given bAsset
*/
function checkBalance(address _bAsset) external returns (uint256 balance);
/**
* @dev Returns the pToken
*/
function bAssetToPToken(address _bAsset) external returns (address pToken);
}
interface IBasicToken {
function decimals() external view returns (uint8);
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
/**
* @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.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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'
// 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) + 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) - 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
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library MassetHelpers {
using SafeERC20 for IERC20;
function transferReturnBalance(
address _sender,
address _recipient,
address _bAsset,
uint256 _qty
) internal returns (uint256 receivedQty, uint256 recipientBalance) {
uint256 balBefore = IERC20(_bAsset).balanceOf(_recipient);
IERC20(_bAsset).safeTransferFrom(_sender, _recipient, _qty);
recipientBalance = IERC20(_bAsset).balanceOf(_recipient);
receivedQty = recipientBalance - balBefore;
}
function safeInfiniteApprove(address _asset, address _spender) internal {
IERC20(_asset).safeApprove(_spender, 0);
IERC20(_asset).safeApprove(_spender, 2**256 - 1);
}
}
library Manager {
using SafeERC20 for IERC20;
using StableMath for uint256;
event BassetsMigrated(address[] bAssets, address newIntegrator);
event TransferFeeEnabled(address indexed bAsset, bool enabled);
event BassetAdded(address indexed bAsset, address integrator);
event BassetStatusChanged(address indexed bAsset, MassetStructs.BassetStatus status);
event BasketStatusChanged();
event StartRampA(uint256 currentA, uint256 targetA, uint256 startTime, uint256 rampEndTime);
event StopRampA(uint256 currentA, uint256 time);
uint256 private constant MIN_RAMP_TIME = 1 days;
uint256 private constant MAX_A = 1e6;
/**
* @notice Adds a bAsset to the given personal, data and mapping, provided it is valid
* @param _bAssetPersonal Basset data storage array
* @param _bAssetData Basset data storage array
* @param _bAssetIndexes Mapping of bAsset address to their index
* @param _maxBassets Max size of the basket
* @param _bAsset Address of the ERC20 token to add to the Basket
* @param _integration Address of the Platform Integration
* @param _mm Base 1e8 var to determine measurement ratio
* @param _hasTxFee Are transfer fees charged on this bAsset (e.g. USDT)
*/
function addBasset(
MassetStructs.BassetPersonal[] storage _bAssetPersonal,
MassetStructs.BassetData[] storage _bAssetData,
mapping(address => uint8) storage _bAssetIndexes,
uint8 _maxBassets,
address _bAsset,
address _integration,
uint256 _mm,
bool _hasTxFee
) external {
require(_bAsset != address(0), "bAsset address must be valid");
uint8 bAssetCount = uint8(_bAssetPersonal.length);
require(bAssetCount < _maxBassets, "Max bAssets in Basket");
uint8 idx = _bAssetIndexes[_bAsset];
require(
bAssetCount == 0 || _bAssetPersonal[idx].addr != _bAsset,
"bAsset already exists in Basket"
);
// Should fail if bAsset is not added to integration
// Programmatic enforcement of bAsset validity should service through decentralised feed
if (_integration != address(0)) {
IPlatformIntegration(_integration).checkBalance(_bAsset);
}
uint256 bAssetDecimals = IBasicToken(_bAsset).decimals();
require(
bAssetDecimals >= 4 && bAssetDecimals <= 18,
"Token must have sufficient decimal places"
);
uint256 delta = uint256(18) - bAssetDecimals;
uint256 ratio = _mm * (10**delta);
_bAssetIndexes[_bAsset] = bAssetCount;
_bAssetPersonal.push(
MassetStructs.BassetPersonal({
addr: _bAsset,
integrator: _integration,
hasTxFee: _hasTxFee,
status: MassetStructs.BassetStatus.Normal
})
);
_bAssetData.push(
MassetStructs.BassetData({ ratio: SafeCast.toUint128(ratio), vaultBalance: 0 })
);
emit BassetAdded(_bAsset, _integration);
}
/**
* @dev Collects the interest generated from the Basket, minting a relative
* amount of mAsset and sending it over to the SavingsManager.
* @param _bAssetPersonal Basset personal storage array
* @param _bAssetData Basset data storage array
* @param _forgeValidator Link to the current InvariantValidator
* @return mintAmount Lending market interest collected
* @return rawGains Raw increases in vault Balance
*/
function collectPlatformInterest(
MassetStructs.BassetPersonal[] memory _bAssetPersonal,
MassetStructs.BassetData[] storage _bAssetData,
IInvariantValidator _forgeValidator,
MassetStructs.InvariantConfig memory _config
) external returns (uint256 mintAmount, uint256[] memory rawGains) {
// Get basket details
MassetStructs.BassetData[] memory bAssetData_ = _bAssetData;
uint256 count = bAssetData_.length;
uint8[] memory indices = new uint8[](count);
rawGains = new uint256[](count);
// 1. Calculate rawGains in each bAsset, in comparison to current vault balance
for (uint256 i = 0; i < count; i++) {
indices[i] = uint8(i);
MassetStructs.BassetPersonal memory bPersonal = _bAssetPersonal[i];
MassetStructs.BassetData memory bData = bAssetData_[i];
// If there is no integration, then nothing can have accrued
if (bPersonal.integrator == address(0)) continue;
uint256 lending =
IPlatformIntegration(bPersonal.integrator).checkBalance(bPersonal.addr);
uint256 cache = 0;
if (!bPersonal.hasTxFee) {
cache = IERC20(bPersonal.addr).balanceOf(bPersonal.integrator);
}
uint256 balance = lending + cache;
uint256 oldVaultBalance = bData.vaultBalance;
if (
balance > oldVaultBalance && bPersonal.status == MassetStructs.BassetStatus.Normal
) {
_bAssetData[i].vaultBalance = SafeCast.toUint128(balance);
uint256 interestDelta = balance - oldVaultBalance;
rawGains[i] = interestDelta;
} else {
rawGains[i] = 0;
}
}
mintAmount = _forgeValidator.computeMintMulti(bAssetData_, indices, rawGains, _config);
}
/**
* @dev Update transfer fee flag for a given bAsset, should it change its fee practice
* @param _bAssetPersonal Basset data storage array
* @param _bAssetIndexes Mapping of bAsset address to their index
* @param _bAsset bAsset address
* @param _flag Charge transfer fee when its set to 'true', otherwise 'false'
*/
function setTransferFeesFlag(
MassetStructs.BassetPersonal[] storage _bAssetPersonal,
mapping(address => uint8) storage _bAssetIndexes,
address _bAsset,
bool _flag
) external {
uint256 index = _getAssetIndex(_bAssetPersonal, _bAssetIndexes, _bAsset);
_bAssetPersonal[index].hasTxFee = _flag;
if (_flag) {
// if token has tx fees, it can no longer operate with a cache
address integration = _bAssetPersonal[index].integrator;
if (integration != address(0)) {
uint256 bal = IERC20(_bAsset).balanceOf(integration);
if (bal > 0) {
IPlatformIntegration(integration).deposit(_bAsset, bal, true);
}
}
}
emit TransferFeeEnabled(_bAsset, _flag);
}
/**
* @dev Transfers all collateral from one lending market to another - used initially
* to handle the migration between Aave V1 and Aave V2. Note - only supports non
* tx fee enabled assets. Supports going from no integration to integration, but
* not the other way around.
* @param _bAssetPersonal Basset data storage array
* @param _bAssetIndexes Mapping of bAsset address to their index
* @param _bAssets Array of basket assets to migrate
* @param _newIntegration Address of the new platform integration
*/
function migrateBassets(
MassetStructs.BassetPersonal[] storage _bAssetPersonal,
mapping(address => uint8) storage _bAssetIndexes,
address[] calldata _bAssets,
address _newIntegration
) external {
uint256 len = _bAssets.length;
require(len > 0, "Must migrate some bAssets");
for (uint256 i = 0; i < len; i++) {
// 1. Check that the bAsset is in the basket
address bAsset = _bAssets[i];
uint256 index = _getAssetIndex(_bAssetPersonal, _bAssetIndexes, bAsset);
require(!_bAssetPersonal[index].hasTxFee, "A bAsset has a transfer fee");
// 2. Withdraw everything from the old platform integration
address oldAddress = _bAssetPersonal[index].integrator;
require(oldAddress != _newIntegration, "Must transfer to new integrator");
(uint256 cache, uint256 lendingBal) = (0, 0);
if (oldAddress == address(0)) {
cache = IERC20(bAsset).balanceOf(address(this));
} else {
IPlatformIntegration oldIntegration = IPlatformIntegration(oldAddress);
cache = IERC20(bAsset).balanceOf(address(oldIntegration));
// 2.1. Withdraw from the lending market
lendingBal = oldIntegration.checkBalance(bAsset);
if (lendingBal > 0) {
oldIntegration.withdraw(address(this), bAsset, lendingBal, false);
}
// 2.2. Withdraw from the cache, if any
if (cache > 0) {
oldIntegration.withdrawRaw(address(this), bAsset, cache);
}
}
uint256 sum = lendingBal + cache;
// 3. Update the integration address for this bAsset
_bAssetPersonal[index].integrator = _newIntegration;
// 4. Deposit everything into the new
// This should fail if we did not receive the full amount from the platform withdrawal
// 4.1. Deposit all bAsset
IERC20(bAsset).safeTransfer(_newIntegration, sum);
IPlatformIntegration newIntegration = IPlatformIntegration(_newIntegration);
if (lendingBal > 0) {
newIntegration.deposit(bAsset, lendingBal, false);
}
// 4.2. Check balances
uint256 newLendingBal = newIntegration.checkBalance(bAsset);
uint256 newCache = IERC20(bAsset).balanceOf(address(newIntegration));
uint256 upperMargin = 10001e14;
uint256 lowerMargin = 9999e14;
require(
newLendingBal >= lendingBal.mulTruncate(lowerMargin) &&
newLendingBal <= lendingBal.mulTruncate(upperMargin),
"Must transfer full amount"
);
require(
newCache >= cache.mulTruncate(lowerMargin) &&
newCache <= cache.mulTruncate(upperMargin),
"Must transfer full amount"
);
}
emit BassetsMigrated(_bAssets, _newIntegration);
}
/**
* @dev Executes the Auto Redistribution event by isolating the bAsset from the Basket
* @param _basket Struct containing core basket info
* @param _bAssetPersonal Basset data storage array
* @param _bAsset Address of the ERC20 token to isolate
* @param _belowPeg Bool to describe whether the bAsset deviated below peg (t)
* or above (f)
*/
function handlePegLoss(
MassetStructs.BasketState storage _basket,
MassetStructs.BassetPersonal[] storage _bAssetPersonal,
mapping(address => uint8) storage _bAssetIndexes,
address _bAsset,
bool _belowPeg
) external {
require(!_basket.failed, "Basket must be alive");
uint256 i = _getAssetIndex(_bAssetPersonal, _bAssetIndexes, _bAsset);
MassetStructs.BassetStatus newStatus =
_belowPeg
? MassetStructs.BassetStatus.BrokenBelowPeg
: MassetStructs.BassetStatus.BrokenAbovePeg;
_bAssetPersonal[i].status = newStatus;
_basket.undergoingRecol = true;
emit BassetStatusChanged(_bAsset, newStatus);
}
/**
* @dev Negates the isolation of a given bAsset
* @param _basket Struct containing core basket info
* @param _bAssetPersonal Basset data storage array
* @param _bAssetIndexes Mapping of bAsset address to their index
* @param _bAsset Address of the bAsset
*/
function negateIsolation(
MassetStructs.BasketState storage _basket,
MassetStructs.BassetPersonal[] storage _bAssetPersonal,
mapping(address => uint8) storage _bAssetIndexes,
address _bAsset
) external {
uint256 i = _getAssetIndex(_bAssetPersonal, _bAssetIndexes, _bAsset);
_bAssetPersonal[i].status = MassetStructs.BassetStatus.Normal;
bool undergoingRecol = false;
for (uint256 j = 0; j < _bAssetPersonal.length; j++) {
if (_bAssetPersonal[j].status != MassetStructs.BassetStatus.Normal) {
undergoingRecol = true;
break;
}
}
_basket.undergoingRecol = undergoingRecol;
emit BassetStatusChanged(_bAsset, MassetStructs.BassetStatus.Normal);
}
/**
* @dev Starts changing of the amplification var A
* @param _targetA Target A value
* @param _rampEndTime Time at which A will arrive at _targetA
*/
function startRampA(
MassetStructs.AmpData storage _ampData,
uint256 _targetA,
uint256 _rampEndTime,
uint256 _currentA,
uint256 _precision
) external {
require(
block.timestamp >= (_ampData.rampStartTime + MIN_RAMP_TIME),
"Sufficient period of previous ramp has not elapsed"
);
require(_rampEndTime >= (block.timestamp + MIN_RAMP_TIME), "Ramp time too short");
require(_targetA > 0 && _targetA < MAX_A, "A target out of bounds");
uint256 preciseTargetA = _targetA * _precision;
if (preciseTargetA > _currentA) {
require(preciseTargetA <= _currentA * 10, "A target increase too big");
} else {
require(preciseTargetA >= _currentA / 10, "A target decrease too big");
}
_ampData.initialA = SafeCast.toUint64(_currentA);
_ampData.targetA = SafeCast.toUint64(preciseTargetA);
_ampData.rampStartTime = SafeCast.toUint64(block.timestamp);
_ampData.rampEndTime = SafeCast.toUint64(_rampEndTime);
emit StartRampA(_currentA, preciseTargetA, block.timestamp, _rampEndTime);
}
/**
* @dev Stops the changing of the amplification var A, setting
* it to whatever the current value is.
*/
function stopRampA(MassetStructs.AmpData storage _ampData, uint256 _currentA) external {
require(block.timestamp < _ampData.rampEndTime, "Amplification not changing");
_ampData.initialA = SafeCast.toUint64(_currentA);
_ampData.targetA = SafeCast.toUint64(_currentA);
_ampData.rampStartTime = SafeCast.toUint64(block.timestamp);
_ampData.rampEndTime = SafeCast.toUint64(block.timestamp);
emit StopRampA(_currentA, block.timestamp);
}
/**
* @dev Gets a bAsset index from storage
* @param _asset Address of the asset
* @return idx Index of the asset
*/
function _getAssetIndex(
MassetStructs.BassetPersonal[] storage _bAssetPersonal,
mapping(address => uint8) storage _bAssetIndexes,
address _asset
) internal view returns (uint8 idx) {
idx = _bAssetIndexes[_asset];
require(_bAssetPersonal[idx].addr == _asset, "Invalid asset input");
}
/***************************************
FORGING
****************************************/
/**
* @dev Deposits a given asset to the system. If there is sufficient room for the asset
* in the cache, then just transfer, otherwise reset the cache to the desired mid level by
* depositing the delta in the platform
*/
function depositTokens(
MassetStructs.BassetPersonal memory _bAsset,
uint256 _bAssetRatio,
uint256 _quantity,
uint256 _maxCache
) external returns (uint256 quantityDeposited) {
// 0. If integration is 0, short circuit
if (_bAsset.integrator == address(0)) {
(uint256 received, ) =
MassetHelpers.transferReturnBalance(
msg.sender,
address(this),
_bAsset.addr,
_quantity
);
return received;
}
// 1 - Send all to PI, using the opportunity to get the cache balance and net amount transferred
uint256 cacheBal;
(quantityDeposited, cacheBal) = MassetHelpers.transferReturnBalance(
msg.sender,
_bAsset.integrator,
_bAsset.addr,
_quantity
);
// 2 - Deposit X if necessary
// 2.1 - Deposit if xfer fees
if (_bAsset.hasTxFee) {
uint256 deposited =
IPlatformIntegration(_bAsset.integrator).deposit(
_bAsset.addr,
quantityDeposited,
true
);
return StableMath.min(deposited, quantityDeposited);
}
// 2.2 - Else Deposit X if Cache > %
// This check is in place to ensure that any token with a txFee is rejected
require(quantityDeposited == _quantity, "Asset not fully transferred");
uint256 relativeMaxCache = _maxCache.divRatioPrecisely(_bAssetRatio);
if (cacheBal > relativeMaxCache) {
uint256 delta = cacheBal - (relativeMaxCache / 2);
IPlatformIntegration(_bAsset.integrator).deposit(_bAsset.addr, delta, false);
}
}
/**
* @dev Withdraws a given asset from its platformIntegration. If there is sufficient liquidity
* in the cache, then withdraw from there, otherwise withdraw from the lending market and reset the
* cache to the mid level.
*/
function withdrawTokens(
uint256 _quantity,
MassetStructs.BassetPersonal memory _personal,
MassetStructs.BassetData memory _data,
address _recipient,
uint256 _maxCache
) external {
if (_quantity == 0) return;
// 1.0 If there is no integrator, send from here
if (_personal.integrator == address(0)) {
IERC20(_personal.addr).safeTransfer(_recipient, _quantity);
}
// 1.1 If txFee then short circuit - there is no cache
else if (_personal.hasTxFee) {
IPlatformIntegration(_personal.integrator).withdraw(
_recipient,
_personal.addr,
_quantity,
_quantity,
true
);
}
// 1.2. Else, withdraw from either cache or main vault
else {
uint256 cacheBal = IERC20(_personal.addr).balanceOf(_personal.integrator);
// 2.1 - If balance b in cache, simply withdraw
if (cacheBal >= _quantity) {
IPlatformIntegration(_personal.integrator).withdrawRaw(
_recipient,
_personal.addr,
_quantity
);
}
// 2.2 - Else reset the cache to X, or as far as possible
// - Withdraw X+b from platform
// - Send b to user
else {
uint256 relativeMidCache = _maxCache.divRatioPrecisely(_data.ratio) / 2;
uint256 totalWithdrawal =
StableMath.min(
relativeMidCache + _quantity - cacheBal,
_data.vaultBalance - SafeCast.toUint128(cacheBal)
);
IPlatformIntegration(_personal.integrator).withdraw(
_recipient,
_personal.addr,
_quantity,
totalWithdrawal,
false
);
}
}
}
}
// External
// Internal
// Libs
/**
* @title Masset
* @author mStable
* @notice An incentivised constant sum market maker with hard limits at max region. This supports
* low slippage swaps and applies penalties towards min and max regions. AMM produces a
* stablecoin (mAsset) and redirects lending market interest and swap fees to the savings
* contract, producing a second yield bearing asset.
* @dev VERSION: 3.0
* DATE: 2021-01-22
*/
contract Masset is
IMasset,
Initializable,
InitializableToken,
ImmutableModule,
InitializableReentrancyGuard
{
using StableMath for uint256;
// Forging Events
event Minted(
address indexed minter,
address recipient,
uint256 mAssetQuantity,
address input,
uint256 inputQuantity
);
event MintedMulti(
address indexed minter,
address recipient,
uint256 mAssetQuantity,
address[] inputs,
uint256[] inputQuantities
);
event Swapped(
address indexed swapper,
address input,
address output,
uint256 outputAmount,
uint256 scaledFee,
address recipient
);
event Redeemed(
address indexed redeemer,
address recipient,
uint256 mAssetQuantity,
address output,
uint256 outputQuantity,
uint256 scaledFee
);
event RedeemedMulti(
address indexed redeemer,
address recipient,
uint256 mAssetQuantity,
address[] outputs,
uint256[] outputQuantity,
uint256 scaledFee
);
// State Events
event CacheSizeChanged(uint256 cacheSize);
event FeesChanged(uint256 swapFee, uint256 redemptionFee);
event WeightLimitsChanged(uint128 min, uint128 max);
event ForgeValidatorChanged(address forgeValidator);
// Release 1.0 VARS
IInvariantValidator public forgeValidator;
bool private forgeValidatorLocked;
// Deprecated - maintain for storage layout in mUSD
Deprecated_BasketManager private deprecated_basketManager;
// Basic redemption fee information
uint256 public swapFee;
uint256 private MAX_FEE;
// Release 1.1 VARS
uint256 public redemptionFee;
// Release 2.0 VARS
uint256 public cacheSize;
uint256 public surplus;
// Release 3.0 VARS
// Struct holding Basket details
BassetPersonal[] public bAssetPersonal;
BassetData[] public bAssetData;
mapping(address => uint8) public override bAssetIndexes;
uint8 public maxBassets;
BasketState public basket;
// Amplification Data
uint256 private constant A_PRECISION = 100;
AmpData public ampData;
WeightLimits public weightLimits;
/**
* @dev Constructor to set immutable bytecode
* @param _nexus Nexus address
*/
constructor(address _nexus) ImmutableModule(_nexus) {}
/**
* @dev Initialization function for upgradable proxy contract.
* This function should be called via Proxy just after contract deployment.
* To avoid variable shadowing appended `Arg` after arguments name.
* @param _nameArg Name of the mAsset
* @param _symbolArg Symbol of the mAsset
* @param _forgeValidator Address of the AMM implementation
* @param _bAssets Array of Basset data
*/
function initialize(
string calldata _nameArg,
string calldata _symbolArg,
address _forgeValidator,
BassetPersonal[] calldata _bAssets,
InvariantConfig memory _config
) public initializer {
InitializableToken._initialize(_nameArg, _symbolArg);
_initializeReentrancyGuard();
forgeValidator = IInvariantValidator(_forgeValidator);
maxBassets = 10;
uint256 len = _bAssets.length;
require(len > 0, "No bAssets");
for (uint256 i = 0; i < len; i++) {
Manager.addBasset(
bAssetPersonal,
bAssetData,
bAssetIndexes,
maxBassets,
_bAssets[i].addr,
_bAssets[i].integrator,
1e8,
_bAssets[i].hasTxFee
);
}
uint64 startA = SafeCast.toUint64(_config.a * A_PRECISION);
ampData = AmpData(startA, startA, 0, 0);
weightLimits = _config.limits;
MAX_FEE = 2e16;
swapFee = 6e14;
redemptionFee = 3e14;
cacheSize = 1e17;
}
/**
* @dev Verifies that the caller is the Savings Manager contract
*/
modifier onlySavingsManager() {
_isSavingsManager();
_;
}
// Internal fn for modifier to reduce deployment size
function _isSavingsManager() internal view {
require(_savingsManager() == msg.sender, "Must be savings manager");
}
/**
* @dev Requires the overall basket composition to be healthy
*/
modifier whenHealthy() {
_isHealthy();
_;
}
// Internal fn for modifier to reduce deployment size
function _isHealthy() internal view {
BasketState memory basket_ = basket;
require(!basket_.undergoingRecol && !basket_.failed, "Unhealthy");
}
/**
* @dev Requires the basket not to be undergoing recollateralisation
*/
modifier whenNoRecol() {
_noRecol();
_;
}
// Internal fn for modifier to reduce deployment size
function _noRecol() internal view {
BasketState memory basket_ = basket;
require(!basket_.undergoingRecol, "In recol");
}
/***************************************
MINTING (PUBLIC)
****************************************/
/**
* @dev Mint a single bAsset, at a 1:1 ratio with the bAsset. This contract
* must have approval to spend the senders bAsset
* @param _input Address of the bAsset to deposit for the minted mAsset.
* @param _inputQuantity Quantity in bAsset units
* @param _minOutputQuantity Minimum mAsset quanity to be minted. This protects against slippage.
* @param _recipient Receipient of the newly minted mAsset tokens
* @return mintOutput Quantity of newly minted mAssets for the deposited bAsset.
*/
function mint(
address _input,
uint256 _inputQuantity,
uint256 _minOutputQuantity,
address _recipient
) external override nonReentrant whenHealthy returns (uint256 mintOutput) {
mintOutput = _mintTo(_input, _inputQuantity, _minOutputQuantity, _recipient);
}
/**
* @dev Mint with multiple bAssets, at a 1:1 ratio to mAsset. This contract
* must have approval to spend the senders bAssets
* @param _inputs Non-duplicate address array of bASset addresses to deposit for the minted mAsset tokens.
* @param _inputQuantities Quantity of each bAsset to deposit for the minted mAsset.
* Order of array should mirror the above bAsset addresses.
* @param _minOutputQuantity Minimum mAsset quanity to be minted. This protects against slippage.
* @param _recipient Address to receive the newly minted mAsset tokens
* @return mintOutput Quantity of newly minted mAssets for the deposited bAssets.
*/
function mintMulti(
address[] calldata _inputs,
uint256[] calldata _inputQuantities,
uint256 _minOutputQuantity,
address _recipient
) external override nonReentrant whenHealthy returns (uint256 mintOutput) {
mintOutput = _mintMulti(_inputs, _inputQuantities, _minOutputQuantity, _recipient);
}
/**
* @dev Get the projected output of a given mint
* @param _input Address of the bAsset to deposit for the minted mAsset
* @param _inputQuantity Quantity in bAsset units
* @return mintOutput Estimated mint output in mAsset terms
*/
function getMintOutput(address _input, uint256 _inputQuantity)
external
view
override
returns (uint256 mintOutput)
{
require(_inputQuantity > 0, "Qty==0");
(uint8 idx, ) = _getAsset(_input);
mintOutput = forgeValidator.computeMint(bAssetData, idx, _inputQuantity, _getConfig());
}
/**
* @dev Get the projected output of a given mint
* @param _inputs Non-duplicate address array of addresses to bAssets to deposit for the minted mAsset tokens.
* @param _inputQuantities Quantity of each bAsset to deposit for the minted mAsset.
* @return mintOutput Estimated mint output in mAsset terms
*/
function getMintMultiOutput(address[] calldata _inputs, uint256[] calldata _inputQuantities)
external
view
override
returns (uint256 mintOutput)
{
uint256 len = _inputQuantities.length;
require(len > 0 && len == _inputs.length, "Input array mismatch");
(uint8[] memory indexes, ) = _getBassets(_inputs);
return forgeValidator.computeMintMulti(bAssetData, indexes, _inputQuantities, _getConfig());
}
/***************************************
MINTING (INTERNAL)
****************************************/
/** @dev Mint Single */
function _mintTo(
address _input,
uint256 _inputQuantity,
uint256 _minMassetQuantity,
address _recipient
) internal returns (uint256 mAssetMinted) {
require(_recipient != address(0), "Invalid recipient");
require(_inputQuantity > 0, "Qty==0");
BassetData[] memory allBassets = bAssetData;
(uint8 bAssetIndex, BassetPersonal memory personal) = _getAsset(_input);
Cache memory cache = _getCacheDetails();
// Transfer collateral to the platform integration address and call deposit
uint256 quantityDeposited =
Manager.depositTokens(
personal,
allBassets[bAssetIndex].ratio,
_inputQuantity,
cache.maxCache
);
// Validation should be after token transfer, as bAssetQty is unknown before
mAssetMinted = forgeValidator.computeMint(
allBassets,
bAssetIndex,
quantityDeposited,
_getConfig()
);
require(mAssetMinted >= _minMassetQuantity, "Mint quantity < min qty");
// Log the Vault increase - can only be done when basket is healthy
bAssetData[bAssetIndex].vaultBalance =
allBassets[bAssetIndex].vaultBalance +
SafeCast.toUint128(quantityDeposited);
// Mint the Masset
_mint(_recipient, mAssetMinted);
emit Minted(msg.sender, _recipient, mAssetMinted, _input, quantityDeposited);
}
/** @dev Mint Multi */
function _mintMulti(
address[] memory _inputs,
uint256[] memory _inputQuantities,
uint256 _minMassetQuantity,
address _recipient
) internal returns (uint256 mAssetMinted) {
require(_recipient != address(0), "Invalid recipient");
uint256 len = _inputQuantities.length;
require(len > 0 && len == _inputs.length, "Input array mismatch");
// Load bAssets from storage into memory
(uint8[] memory indexes, BassetPersonal[] memory personals) = _getBassets(_inputs);
BassetData[] memory allBassets = bAssetData;
Cache memory cache = _getCacheDetails();
uint256[] memory quantitiesDeposited = new uint256[](len);
// Transfer the Bassets to the integrator, update storage and calc MassetQ
for (uint256 i = 0; i < len; i++) {
uint256 bAssetQuantity = _inputQuantities[i];
if (bAssetQuantity > 0) {
uint8 idx = indexes[i];
BassetData memory data = allBassets[idx];
BassetPersonal memory personal = personals[i];
uint256 quantityDeposited =
Manager.depositTokens(personal, data.ratio, bAssetQuantity, cache.maxCache);
quantitiesDeposited[i] = quantityDeposited;
bAssetData[idx].vaultBalance =
data.vaultBalance +
SafeCast.toUint128(quantityDeposited);
}
}
// Validate the proposed mint, after token transfer
mAssetMinted = forgeValidator.computeMintMulti(
allBassets,
indexes,
quantitiesDeposited,
_getConfig()
);
require(mAssetMinted >= _minMassetQuantity, "Mint quantity < min qty");
require(mAssetMinted > 0, "Zero mAsset quantity");
// Mint the Masset
_mint(_recipient, mAssetMinted);
emit MintedMulti(msg.sender, _recipient, mAssetMinted, _inputs, _inputQuantities);
}
/***************************************
SWAP (PUBLIC)
****************************************/
/**
* @dev Swaps one bAsset for another bAsset using the bAsset addresses.
* bAsset <> bAsset swaps will incur a small fee (swapFee()).
* @param _input Address of bAsset to deposit
* @param _output Address of bAsset to receive
* @param _inputQuantity Units of input bAsset to swap
* @param _minOutputQuantity Minimum quantity of the swap output asset. This protects against slippage
* @param _recipient Address to transfer output asset to
* @return swapOutput Quantity of output asset returned from swap
*/
function swap(
address _input,
address _output,
uint256 _inputQuantity,
uint256 _minOutputQuantity,
address _recipient
) external override nonReentrant whenHealthy returns (uint256 swapOutput) {
swapOutput = _swap(_input, _output, _inputQuantity, _minOutputQuantity, _recipient);
}
/**
* @dev Determines both if a trade is valid, and the expected fee or output.
* Swap is valid if it does not result in the input asset exceeding its maximum weight.
* @param _input Address of bAsset to deposit
* @param _output Address of bAsset to receive
* @param _inputQuantity Units of input bAsset to swap
* @return swapOutput Quantity of output asset returned from swap
*/
function getSwapOutput(
address _input,
address _output,
uint256 _inputQuantity
) external view override returns (uint256 swapOutput) {
require(_input != _output, "Invalid pair");
require(_inputQuantity > 0, "Invalid swap quantity");
// 1. Load the bAssets from storage into memory
BassetData[] memory allBassets = bAssetData;
(uint8 inputIdx, ) = _getAsset(_input);
(uint8 outputIdx, ) = _getAsset(_output);
// 2. If a bAsset swap, calculate the validity, output and fee
(swapOutput, ) = forgeValidator.computeSwap(
allBassets,
inputIdx,
outputIdx,
_inputQuantity,
swapFee,
_getConfig()
);
}
/***************************************
SWAP (INTERNAL)
****************************************/
/** @dev Swap single */
function _swap(
address _input,
address _output,
uint256 _inputQuantity,
uint256 _minOutputQuantity,
address _recipient
) internal returns (uint256 swapOutput) {
require(_recipient != address(0), "Invalid recipient");
require(_input != _output, "Invalid pair");
require(_inputQuantity > 0, "Invalid swap quantity");
// 1. Load the bAssets from storage into memory
BassetData[] memory allBassets = bAssetData;
(uint8 inputIdx, BassetPersonal memory inputPersonal) = _getAsset(_input);
(uint8 outputIdx, BassetPersonal memory outputPersonal) = _getAsset(_output);
// 2. Load cache
Cache memory cache = _getCacheDetails();
// 3. Deposit the input tokens
uint256 quantityDeposited =
Manager.depositTokens(
inputPersonal,
allBassets[inputIdx].ratio,
_inputQuantity,
cache.maxCache
);
// 3.1. Update the input balance
bAssetData[inputIdx].vaultBalance =
allBassets[inputIdx].vaultBalance +
SafeCast.toUint128(quantityDeposited);
// 3. Validate the swap
uint256 scaledFee;
(swapOutput, scaledFee) = forgeValidator.computeSwap(
allBassets,
inputIdx,
outputIdx,
quantityDeposited,
swapFee,
_getConfig()
);
require(swapOutput >= _minOutputQuantity, "Output qty < minimum qty");
require(swapOutput > 0, "Zero output quantity");
//4. Settle the swap
//4.1. Decrease output bal
Manager.withdrawTokens(
swapOutput,
outputPersonal,
allBassets[outputIdx],
_recipient,
cache.maxCache
);
bAssetData[outputIdx].vaultBalance =
allBassets[outputIdx].vaultBalance -
SafeCast.toUint128(swapOutput);
// Save new surplus to storage
surplus = cache.surplus + scaledFee;
emit Swapped(
msg.sender,
inputPersonal.addr,
outputPersonal.addr,
swapOutput,
scaledFee,
_recipient
);
}
/***************************************
REDEMPTION (PUBLIC)
****************************************/
/**
* @notice Redeems a specified quantity of mAsset in return for a bAsset specified by bAsset address.
* The bAsset is sent to the specified recipient.
* The bAsset quantity is relative to current vault balance levels and desired mAsset quantity.
* The quantity of mAsset is burnt as payment.
* A minimum quantity of bAsset is specified to protect against price slippage between the mAsset and bAsset.
* @param _output Address of the bAsset to receive
* @param _mAssetQuantity Quantity of mAsset to redeem
* @param _minOutputQuantity Minimum bAsset quantity to receive for the burnt mAssets. This protects against slippage.
* @param _recipient Address to transfer the withdrawn bAssets to.
* @return outputQuantity Quanity of bAsset units received for the burnt mAssets
*/
function redeem(
address _output,
uint256 _mAssetQuantity,
uint256 _minOutputQuantity,
address _recipient
) external override nonReentrant whenNoRecol returns (uint256 outputQuantity) {
outputQuantity = _redeem(_output, _mAssetQuantity, _minOutputQuantity, _recipient);
}
/**
* @dev Credits a recipient with a proportionate amount of bAssets, relative to current vault
* balance levels and desired mAsset quantity. Burns the mAsset as payment.
* @param _mAssetQuantity Quantity of mAsset to redeem
* @param _minOutputQuantities Min units of output to receive
* @param _recipient Address to credit the withdrawn bAssets
*/
function redeemMasset(
uint256 _mAssetQuantity,
uint256[] calldata _minOutputQuantities,
address _recipient
) external override nonReentrant whenNoRecol returns (uint256[] memory outputQuantities) {
outputQuantities = _redeemMasset(_mAssetQuantity, _minOutputQuantities, _recipient);
}
/**
* @dev Credits a recipient with a certain quantity of selected bAssets, in exchange for burning the
* relative Masset quantity from the sender. Sender also incurs a small fee on the outgoing asset.
* @param _outputs Addresses of the bAssets to receive
* @param _outputQuantities Units of the bAssets to redeem
* @param _maxMassetQuantity Maximum mAsset quantity to burn for the received bAssets. This protects against slippage.
* @param _recipient Address to receive the withdrawn bAssets
* @return mAssetQuantity Quantity of mAsset units burned plus the swap fee to pay for the redeemed bAssets
*/
function redeemExactBassets(
address[] calldata _outputs,
uint256[] calldata _outputQuantities,
uint256 _maxMassetQuantity,
address _recipient
) external override nonReentrant whenNoRecol returns (uint256 mAssetQuantity) {
mAssetQuantity = _redeemExactBassets(
_outputs,
_outputQuantities,
_maxMassetQuantity,
_recipient
);
}
/**
* @notice Gets the estimated output from a given redeem
* @param _output Address of the bAsset to receive
* @param _mAssetQuantity Quantity of mAsset to redeem
* @return bAssetOutput Estimated quantity of bAsset units received for the burnt mAssets
*/
function getRedeemOutput(address _output, uint256 _mAssetQuantity)
external
view
override
returns (uint256 bAssetOutput)
{
require(_mAssetQuantity > 0, "Qty==0");
(uint8 idx, ) = _getAsset(_output);
uint256 scaledFee = _mAssetQuantity.mulTruncate(swapFee);
bAssetOutput = forgeValidator.computeRedeem(
bAssetData,
idx,
_mAssetQuantity - scaledFee,
_getConfig()
);
}
/**
* @notice Gets the estimated output from a given redeem
* @param _outputs Addresses of the bAsset to receive
* @param _outputQuantities Quantities of bAsset to redeem
* @return mAssetQuantity Estimated quantity of mAsset units needed to burn to receive output
*/
function getRedeemExactBassetsOutput(
address[] calldata _outputs,
uint256[] calldata _outputQuantities
) external view override returns (uint256 mAssetQuantity) {
uint256 len = _outputQuantities.length;
require(len > 0 && len == _outputs.length, "Invalid array input");
(uint8[] memory indexes, ) = _getBassets(_outputs);
// calculate the value of mAssets need to cover the value of bAssets being redeemed
uint256 mAssetRedeemed =
forgeValidator.computeRedeemExact(bAssetData, indexes, _outputQuantities, _getConfig());
mAssetQuantity = mAssetRedeemed.divPrecisely(1e18 - swapFee) + 1;
}
/***************************************
REDEMPTION (INTERNAL)
****************************************/
/**
* @dev Redeem mAsset for a single bAsset
*/
function _redeem(
address _output,
uint256 _inputQuantity,
uint256 _minOutputQuantity,
address _recipient
) internal returns (uint256 bAssetQuantity) {
require(_recipient != address(0), "Invalid recipient");
require(_inputQuantity > 0, "Qty==0");
// Load the bAsset data from storage into memory
BassetData[] memory allBassets = bAssetData;
(uint8 bAssetIndex, BassetPersonal memory personal) = _getAsset(_output);
// Calculate redemption quantities
uint256 scaledFee = _inputQuantity.mulTruncate(swapFee);
bAssetQuantity = forgeValidator.computeRedeem(
allBassets,
bAssetIndex,
_inputQuantity - scaledFee,
_getConfig()
);
require(bAssetQuantity >= _minOutputQuantity, "bAsset qty < min qty");
require(bAssetQuantity > 0, "Output == 0");
// Apply fees, burn mAsset and return bAsset to recipient
// 1.0. Burn the full amount of Masset
_burn(msg.sender, _inputQuantity);
surplus += scaledFee;
Cache memory cache = _getCacheDetails();
// 2.0. Transfer the Bassets to the recipient
Manager.withdrawTokens(
bAssetQuantity,
personal,
allBassets[bAssetIndex],
_recipient,
cache.maxCache
);
// 3.0. Set vault balance
bAssetData[bAssetIndex].vaultBalance =
allBassets[bAssetIndex].vaultBalance -
SafeCast.toUint128(bAssetQuantity);
emit Redeemed(
msg.sender,
_recipient,
_inputQuantity,
personal.addr,
bAssetQuantity,
scaledFee
);
}
/**
* @dev Redeem mAsset for proportional amount of bAssets
*/
function _redeemMasset(
uint256 _inputQuantity,
uint256[] calldata _minOutputQuantities,
address _recipient
) internal returns (uint256[] memory outputQuantities) {
require(_recipient != address(0), "Invalid recipient");
require(_inputQuantity > 0, "Qty==0");
// Calculate mAsset redemption quantities
uint256 scaledFee = _inputQuantity.mulTruncate(redemptionFee);
uint256 mAssetRedemptionAmount = _inputQuantity - scaledFee;
// Burn mAsset quantity
_burn(msg.sender, _inputQuantity);
surplus += scaledFee;
// Calc cache and total mAsset circulating
Cache memory cache = _getCacheDetails();
// Total mAsset = (totalSupply + _inputQuantity - scaledFee) + surplus
uint256 totalMasset = cache.vaultBalanceSum + mAssetRedemptionAmount;
// Load the bAsset data from storage into memory
BassetData[] memory allBassets = bAssetData;
uint256 len = allBassets.length;
address[] memory outputs = new address[](len);
outputQuantities = new uint256[](len);
for (uint256 i = 0; i < len; i++) {
// Get amount out, proportionate to redemption quantity
// Use `cache.sum` here as the total mAsset supply is actually totalSupply + surplus
uint256 amountOut = (allBassets[i].vaultBalance * mAssetRedemptionAmount) / totalMasset;
require(amountOut > 1, "Output == 0");
amountOut -= 1;
require(amountOut >= _minOutputQuantities[i], "bAsset qty < min qty");
// Set output in array
(outputQuantities[i], outputs[i]) = (amountOut, bAssetPersonal[i].addr);
// Transfer the bAsset to the recipient
Manager.withdrawTokens(
amountOut,
bAssetPersonal[i],
allBassets[i],
_recipient,
cache.maxCache
);
// reduce vaultBalance
bAssetData[i].vaultBalance = allBassets[i].vaultBalance - SafeCast.toUint128(amountOut);
}
emit RedeemedMulti(
msg.sender,
_recipient,
_inputQuantity,
outputs,
outputQuantities,
scaledFee
);
}
/** @dev Redeem mAsset for one or more bAssets */
function _redeemExactBassets(
address[] memory _outputs,
uint256[] memory _outputQuantities,
uint256 _maxMassetQuantity,
address _recipient
) internal returns (uint256 mAssetQuantity) {
require(_recipient != address(0), "Invalid recipient");
uint256 len = _outputQuantities.length;
require(len > 0 && len == _outputs.length, "Invalid array input");
require(_maxMassetQuantity > 0, "Qty==0");
(uint8[] memory indexes, BassetPersonal[] memory personal) = _getBassets(_outputs);
// Load bAsset data from storage to memory
BassetData[] memory allBassets = bAssetData;
// Validate redemption
uint256 mAssetRequired =
forgeValidator.computeRedeemExact(allBassets, indexes, _outputQuantities, _getConfig());
mAssetQuantity = mAssetRequired.divPrecisely(1e18 - swapFee);
uint256 fee = mAssetQuantity - mAssetRequired;
require(mAssetQuantity > 0, "Must redeem some mAssets");
mAssetQuantity += 1;
require(mAssetQuantity <= _maxMassetQuantity, "Redeem mAsset qty > max quantity");
// Apply fees, burn mAsset and return bAsset to recipient
// 1.0. Burn the full amount of Masset
_burn(msg.sender, mAssetQuantity);
surplus += fee;
Cache memory cache = _getCacheDetails();
// 2.0. Transfer the Bassets to the recipient and count fees
for (uint256 i = 0; i < len; i++) {
uint8 idx = indexes[i];
Manager.withdrawTokens(
_outputQuantities[i],
personal[i],
allBassets[idx],
_recipient,
cache.maxCache
);
bAssetData[idx].vaultBalance =
allBassets[idx].vaultBalance -
SafeCast.toUint128(_outputQuantities[i]);
}
emit RedeemedMulti(
msg.sender,
_recipient,
mAssetQuantity,
_outputs,
_outputQuantities,
fee
);
}
/***************************************
GETTERS
****************************************/
/**
* @dev Get basket details for `Masset_MassetStructs.Basket`
* @return b Basket struct
*/
function getBasket() external view override returns (bool, bool) {
return (basket.undergoingRecol, basket.failed);
}
/**
* @dev Get data for a all bAssets in basket
* @return personal Struct[] with full bAsset data
* @return data Number of bAssets in the Basket
*/
function getBassets()
external
view
override
returns (BassetPersonal[] memory personal, BassetData[] memory data)
{
return (bAssetPersonal, bAssetData);
}
/**
* @dev Get data for a specific bAsset, if it exists
* @param _bAsset Address of bAsset
* @return personal Struct with full bAsset data
* @return data Struct with full bAsset data
*/
function getBasset(address _bAsset)
external
view
override
returns (BassetPersonal memory personal, BassetData memory data)
{
uint8 idx = bAssetIndexes[_bAsset];
personal = bAssetPersonal[idx];
require(personal.addr == _bAsset, "Invalid asset");
data = bAssetData[idx];
}
/**
* @dev Gets all config needed for general InvariantValidator calls
*/
function getConfig() external view returns (InvariantConfig memory config) {
return _getConfig();
}
/***************************************
GETTERS - INTERNAL
****************************************/
/**
* vaultBalanceSum = totalSupply + 'surplus'
* maxCache = vaultBalanceSum * (cacheSize / 1e18)
* surplus is simply surplus, to reduce SLOADs
*/
struct Cache {
uint256 vaultBalanceSum;
uint256 maxCache;
uint256 surplus;
}
/**
* @dev Gets the supply and cache details for the mAsset, taking into account the surplus
* @return Cache containing (tracked) sum of vault balances, ideal cache size and surplus
*/
function _getCacheDetails() internal view returns (Cache memory) {
// read surplus from storage into memory
uint256 _surplus = surplus;
uint256 sum = totalSupply() + _surplus;
return Cache(sum, sum.mulTruncate(cacheSize), _surplus);
}
/**
* @dev Gets a bAsset from storage
* @param _asset Address of the asset
* @return idx Index of the asset
* @return personal Personal details for the asset
*/
function _getAsset(address _asset)
internal
view
returns (uint8 idx, BassetPersonal memory personal)
{
idx = bAssetIndexes[_asset];
personal = bAssetPersonal[idx];
require(personal.addr == _asset, "Invalid asset");
}
/**
* @dev Gets a an array of bAssets from storage and protects against duplicates
* @param _bAssets Addresses of the assets
* @return indexes Indexes of the assets
* @return personal Personal details for the assets
*/
function _getBassets(address[] memory _bAssets)
internal
view
returns (uint8[] memory indexes, BassetPersonal[] memory personal)
{
uint256 len = _bAssets.length;
indexes = new uint8[](len);
personal = new BassetPersonal[](len);
for (uint256 i = 0; i < len; i++) {
(indexes[i], personal[i]) = _getAsset(_bAssets[i]);
for (uint256 j = i + 1; j < len; j++) {
require(_bAssets[i] != _bAssets[j], "Duplicate asset");
}
}
}
/**
* @dev Gets all config needed for general InvariantValidator calls
*/
function _getConfig() internal view returns (InvariantConfig memory) {
return InvariantConfig(_getA(), weightLimits);
}
/**
* @dev Gets current amplification var A
*/
function _getA() internal view returns (uint256) {
AmpData memory ampData_ = ampData;
uint64 endA = ampData_.targetA;
uint64 endTime = ampData_.rampEndTime;
// If still changing, work out based on current timestmap
if (block.timestamp < endTime) {
uint64 startA = ampData_.initialA;
uint64 startTime = ampData_.rampStartTime;
(uint256 elapsed, uint256 total) = (block.timestamp - startTime, endTime - startTime);
if (endA > startA) {
return startA + (((endA - startA) * elapsed) / total);
} else {
return startA - (((startA - endA) * elapsed) / total);
}
}
// Else return final value
else {
return endA;
}
}
/***************************************
YIELD
****************************************/
/**
* @dev Converts recently accrued swap and redeem fees into mAsset
* @return mintAmount mAsset units generated from swap and redeem fees
* @return newSupply mAsset total supply after mint
*/
function collectInterest()
external
override
onlySavingsManager
returns (uint256 mintAmount, uint256 newSupply)
{
// Set the surplus variable to 1 to optimise for SSTORE costs.
// If setting to 0 here, it would save 5k per savings deposit, but cost 20k for the
// first surplus call (a SWAP or REDEEM).
uint256 surplusFees = surplus;
if (surplusFees > 1) {
mintAmount = surplusFees - 1;
surplus = 1;
// mint new mAsset to savings manager
_mint(msg.sender, mintAmount);
emit MintedMulti(
address(this),
msg.sender,
mintAmount,
new address[](0),
new uint256[](0)
);
}
newSupply = totalSupply();
}
/**
* @dev Collects the interest generated from the Basket, minting a relative
* amount of mAsset and sends it over to the SavingsManager.
* @return mintAmount mAsset units generated from interest collected from lending markets
* @return newSupply mAsset total supply after mint
*/
function collectPlatformInterest()
external
override
onlySavingsManager
whenHealthy
nonReentrant
returns (uint256 mintAmount, uint256 newSupply)
{
uint256[] memory gains;
(mintAmount, gains) = Manager.collectPlatformInterest(
bAssetPersonal,
bAssetData,
forgeValidator,
_getConfig()
);
require(mintAmount > 0, "Must collect something");
_mint(msg.sender, mintAmount);
emit MintedMulti(address(this), msg.sender, mintAmount, new address[](0), gains);
newSupply = totalSupply();
}
/***************************************
STATE
****************************************/
/**
* @dev Sets the MAX cache size for each bAsset. The cache will actually revolve around
* _cacheSize * totalSupply / 2 under normal circumstances.
* @param _cacheSize Maximum percent of total mAsset supply to hold for each bAsset
*/
function setCacheSize(uint256 _cacheSize) external override onlyGovernor {
require(_cacheSize <= 2e17, "Must be <= 20%");
cacheSize = _cacheSize;
emit CacheSizeChanged(_cacheSize);
}
/**
* @dev Upgrades the version of ForgeValidator protocol. Governor can do this
* only while ForgeValidator is unlocked.
* @param _newForgeValidator Address of the new ForgeValidator
*/
function upgradeForgeValidator(address _newForgeValidator) external override onlyGovernor {
require(!forgeValidatorLocked, "ForgeVal locked");
require(_newForgeValidator != address(0), "Null address");
forgeValidator = IInvariantValidator(_newForgeValidator);
emit ForgeValidatorChanged(_newForgeValidator);
}
/**
* @dev Set the ecosystem fee for sewapping bAssets or redeeming specific bAssets
* @param _swapFee Fee calculated in (%/100 * 1e18)
*/
function setFees(uint256 _swapFee, uint256 _redemptionFee) external override onlyGovernor {
require(_swapFee <= MAX_FEE, "Swap rate oob");
require(_redemptionFee <= MAX_FEE, "Redemption rate oob");
swapFee = _swapFee;
redemptionFee = _redemptionFee;
emit FeesChanged(_swapFee, _redemptionFee);
}
/**
* @dev Set the maximum weight for a given bAsset
* @param _min Weight where 100% = 1e18
* @param _max Weight where 100% = 1e18
*/
function setWeightLimits(uint128 _min, uint128 _max) external onlyGovernor {
require(_min <= 1e18 / (bAssetData.length * 2), "Min weight oob");
require(_max >= 1e18 / (bAssetData.length - 1), "Max weight oob");
weightLimits = WeightLimits(_min, _max);
emit WeightLimitsChanged(_min, _max);
}
/**
* @dev Update transfer fee flag for a given bAsset, should it change its fee practice
* @param _bAsset bAsset address
* @param _flag Charge transfer fee when its set to 'true', otherwise 'false'
*/
function setTransferFeesFlag(address _bAsset, bool _flag) external override onlyGovernor {
Manager.setTransferFeesFlag(bAssetPersonal, bAssetIndexes, _bAsset, _flag);
}
/**
* @dev Transfers all collateral from one lending market to another - used initially
* to handle the migration between Aave V1 and Aave V2. Note - only supports non
* tx fee enabled assets. Supports going from no integration to integration, but
* not the other way around.
* @param _bAssets Array of basket assets to migrate
* @param _newIntegration Address of the new platform integration
*/
function migrateBassets(address[] calldata _bAssets, address _newIntegration)
external
override
onlyGovernor
{
Manager.migrateBassets(bAssetPersonal, bAssetIndexes, _bAssets, _newIntegration);
}
/**
* @dev Executes the Auto Redistribution event by isolating the bAsset from the Basket
* @param _bAsset Address of the ERC20 token to isolate
* @param _belowPeg Bool to describe whether the bAsset deviated below peg (t)
* or above (f)
*/
function handlePegLoss(address _bAsset, bool _belowPeg) external onlyGovernor {
Manager.handlePegLoss(basket, bAssetPersonal, bAssetIndexes, _bAsset, _belowPeg);
}
/**
* @dev Negates the isolation of a given bAsset
* @param _bAsset Address of the bAsset
*/
function negateIsolation(address _bAsset) external onlyGovernor {
Manager.negateIsolation(basket, bAssetPersonal, bAssetIndexes, _bAsset);
}
/**
* @dev Starts changing of the amplification var A
* @param _targetA Target A value
* @param _rampEndTime Time at which A will arrive at _targetA
*/
function startRampA(uint256 _targetA, uint256 _rampEndTime) external onlyGovernor {
Manager.startRampA(ampData, _targetA, _rampEndTime, _getA(), A_PRECISION);
}
/**
* @dev Stops the changing of the amplification var A, setting
* it to whatever the current value is.
*/
function stopRampA() external onlyGovernor {
Manager.stopRampA(ampData, _getA());
}
} | * @notice Gets the estimated output from a given redeem @param _output Address of the bAsset to receive @param _mAssetQuantity Quantity of mAsset to redeem @return bAssetOutput Estimated quantity of bAsset units received for the burnt mAssets/ | function getRedeemOutput(address _output, uint256 _mAssetQuantity)
external
view
override
returns (uint256 bAssetOutput)
{
require(_mAssetQuantity > 0, "Qty==0");
(uint8 idx, ) = _getAsset(_output);
uint256 scaledFee = _mAssetQuantity.mulTruncate(swapFee);
bAssetOutput = forgeValidator.computeRedeem(
bAssetData,
idx,
_mAssetQuantity - scaledFee,
_getConfig()
);
}
| 2,378,771 | [
1,
3002,
326,
13137,
876,
628,
279,
864,
283,
24903,
225,
389,
2844,
5411,
5267,
434,
326,
324,
6672,
358,
6798,
225,
389,
81,
6672,
12035,
565,
18189,
434,
312,
6672,
358,
283,
24903,
327,
324,
6672,
1447,
1377,
17787,
17275,
10457,
434,
324,
6672,
4971,
5079,
364,
326,
18305,
88,
312,
10726,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
5561,
24903,
1447,
12,
2867,
389,
2844,
16,
2254,
5034,
389,
81,
6672,
12035,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
3849,
203,
3639,
1135,
261,
11890,
5034,
324,
6672,
1447,
13,
203,
565,
288,
203,
3639,
2583,
24899,
81,
6672,
12035,
405,
374,
16,
315,
53,
4098,
631,
20,
8863,
203,
203,
3639,
261,
11890,
28,
2067,
16,
262,
273,
389,
588,
6672,
24899,
2844,
1769,
203,
203,
3639,
2254,
5034,
12304,
14667,
273,
389,
81,
6672,
12035,
18,
16411,
25871,
12,
22270,
14667,
1769,
203,
3639,
324,
6672,
1447,
273,
21388,
5126,
18,
9200,
426,
24903,
12,
203,
5411,
324,
6672,
751,
16,
203,
5411,
2067,
16,
203,
5411,
389,
81,
6672,
12035,
300,
12304,
14667,
16,
203,
5411,
389,
588,
809,
1435,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/97/0x65d02A3481F3c25DE96671E30044fad2D060ae95/sources/project:/contracts/Exchange/exchange.sol | * @dev Completes bid order @param bidOrder - Object of bid order. @param signature. Emits a {OrderPurchased} event, indicating the seller, token address and token id./ validate endTime for closed auction validate token registry verify signature get unique key check for order status update order status take revenue and send to revenue wallet transfer remaining WBNB to seller transfer token from seller to buyer | function completeBidding(LibBidOrder.BidOrder memory bidOrder, bytes calldata signature) external whenNotPaused nonReentrant {
require(!blacklisted[msg.sender], "Exchange: Blackisted");
require(!blacklisted[bidOrder.buyer], "Exchange: Blackisted");
require(msg.sender == bidOrder.seller, "Caller is not seller");
if(bidOrder.saleType == CLOSED_AUCTION_SALE_CLASS) require(block.timestamp > bidOrder.endTime, "Exchange: Sale not ended yet");
(uint256 revenuePercentage, uint256 royaltyPercentage, bool tradable) = INftRegistry(nftRegistry).tradeRevenue(bidOrder.tokenAddress);
require(tradable, "This sale is not tradable");
bytes32 structHash = LibBidOrder._genBidOrderHash(bidOrder);
bytes32 hashTypedData = _hashTypedDataV4(structHash);
address signer = _verifySignature(hashTypedData, signature);
require(signer == bidOrder.buyer, "Exchange: Buy order is not signed by the buyer");
LibOrder.Order memory order = LibOrder.Order(
bidOrder.tokenType,
bidOrder.saleType,
bidOrder.seller,
bidOrder.tokenAddress,
bidOrder.tokenId,
bidOrder.tokenAmount,
bidOrder.price,
bidOrder.startTime,
bidOrder.endTime,
bidOrder.nonce
);
bytes32 hashKey = LibOrder._genHashKey(order);
_validateOrderStatus(hashKey);
OrderStatus[hashKey] = COMPLETED_ORDER_CLASS;
emit OrderPurchased(bidOrder.seller, bidOrder.buyer, bidOrder.tokenAddress, bidOrder.tokenId);
uint256 revenueAmount = _calculateRevenue(bidOrder.bidAmount, revenuePercentage);
{
WBNB.safeTransferFrom(bidOrder.buyer, INftRegistry(nftRegistry).revenueWallet(), revenueAmount);
}
{
WBNB.safeTransferFrom(bidOrder.buyer, msg.sender, royaltyAmount);
}
{
LibBidOrder.BidOrder memory bidOrderData = bidOrder;
WBNB.safeTransferFrom(bidOrderData.buyer, msg.sender, bidOrderData.bidAmount);
}
{
LibBidOrder.BidOrder memory bidOrderData = bidOrder;
if(order.tokenType == ASSET_TYPE_ERC721) IERC721Upgradeable(bidOrderData.tokenAddress).safeTransferFrom(
msg.sender, bidOrderData.buyer, bidOrderData.tokenId
);
if(order.tokenType == ASSET_TYPE_ERC1155) IERC1155Upgradeable(bidOrderData.tokenAddress).safeTransferFrom(
msg.sender, bidOrderData.buyer, bidOrderData.tokenId, bidOrderData.tokenAmount, ""
);
}
}
| 3,276,162 | [
1,
6297,
281,
9949,
1353,
225,
9949,
2448,
300,
1033,
434,
9949,
1353,
18,
225,
3372,
18,
7377,
1282,
279,
288,
2448,
10262,
343,
8905,
97,
871,
16,
11193,
326,
29804,
16,
1147,
1758,
471,
1147,
612,
18,
19,
1954,
13859,
364,
4375,
279,
4062,
1954,
1147,
4023,
3929,
3372,
336,
3089,
498,
866,
364,
1353,
1267,
1089,
1353,
1267,
4862,
283,
24612,
471,
1366,
358,
283,
24612,
9230,
7412,
4463,
678,
15388,
38,
358,
29804,
7412,
1147,
628,
29804,
358,
27037,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3912,
38,
1873,
310,
12,
5664,
17763,
2448,
18,
17763,
2448,
3778,
9949,
2448,
16,
1731,
745,
892,
3372,
13,
3903,
1347,
1248,
28590,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
5,
11223,
18647,
63,
3576,
18,
15330,
6487,
315,
11688,
30,
22467,
25444,
8863,
203,
3639,
2583,
12,
5,
11223,
18647,
63,
19773,
2448,
18,
70,
16213,
6487,
315,
11688,
30,
22467,
25444,
8863,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
9949,
2448,
18,
1786,
749,
16,
315,
11095,
353,
486,
29804,
8863,
203,
203,
3639,
309,
12,
19773,
2448,
18,
87,
5349,
559,
422,
27160,
67,
14237,
3106,
67,
5233,
900,
67,
5237,
13,
2583,
12,
2629,
18,
5508,
405,
9949,
2448,
18,
409,
950,
16,
315,
11688,
30,
348,
5349,
486,
16926,
4671,
8863,
203,
203,
3639,
261,
11890,
5034,
283,
24612,
16397,
16,
2254,
5034,
721,
93,
15006,
16397,
16,
1426,
1284,
17394,
13,
273,
2120,
1222,
4243,
12,
82,
1222,
4243,
2934,
20077,
426,
24612,
12,
19773,
2448,
18,
2316,
1887,
1769,
203,
3639,
2583,
12,
313,
361,
429,
16,
315,
2503,
272,
5349,
353,
486,
1284,
17394,
8863,
203,
540,
203,
3639,
1731,
1578,
1958,
2310,
273,
10560,
17763,
2448,
6315,
4507,
17763,
2448,
2310,
12,
19773,
2448,
1769,
203,
3639,
1731,
1578,
1651,
11985,
751,
273,
389,
2816,
11985,
751,
58,
24,
12,
1697,
2310,
1769,
203,
3639,
1758,
10363,
273,
389,
8705,
5374,
12,
2816,
11985,
751,
16,
3372,
1769,
203,
3639,
2583,
12,
2977,
264,
422,
9949,
2448,
18,
70,
2
] |
pragma solidity 0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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 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);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract Owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Owned {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
address internal ownerShip;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _start the time (as Unix time) at which point vesting starts
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable,
address _realOwner
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
ownerShip = _realOwner;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
emit Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(ownerShip, refund);
emit Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
/**
* @title TokenVault
* @dev TokenVault is a token holder contract that will allow a
* beneficiary to spend the tokens from some function of a specified ERC20 token
*/
contract TokenVault {
using SafeERC20 for ERC20;
// ERC20 token contract being held
ERC20 public token;
constructor(ERC20 _token) public {
token = _token;
}
/**
* @notice Allow the token itself to send tokens
* using transferFrom().
*/
function fillUpAllowance() public {
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.approve(token, amount);
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(burner, _value);
}
}
contract NEWACE_Token is BurnableToken, Owned {
string public constant name = "NEWACE TOKEN";
string public constant symbol = "ACE";
uint8 public constant decimals = 18;
/// Maximum tokens to be allocated ( 999 million )
uint256 public constant HARD_CAP = 999000000 * 10**uint256(decimals);
/// This address will be used to distribute the team, advisors and reserve tokens
address public saleTokensAddress;
/// This vault is used to keep the Founders, Advisors and Partners tokens
TokenVault public reserveTokensVault;
/// Date when the vesting for regular users starts
uint64 internal daySecond = 86400;
uint64 internal lock90Days = 90;
uint64 internal unlock100Days = 100;
uint64 internal lock365Days = 365;
/// Store the vesting contract addresses for each sale contributor
mapping(address => address) public vestingOf;
constructor(address _saleTokensAddress) public payable {
require(_saleTokensAddress != address(0));
saleTokensAddress = _saleTokensAddress;
/// Maximum tokens to be sold - 499.5 million
uint256 saleTokens = 499500000;
createTokensInt(saleTokens, saleTokensAddress);
require(totalSupply_ <= HARD_CAP);
}
/// @dev Create a ReserveTokenVault
function createReserveTokensVault() external onlyOwner {
require(reserveTokensVault == address(0));
/// Reserve tokens - 499.5 million
uint256 reserveTokens = 499500000;
reserveTokensVault = createTokenVaultInt(reserveTokens);
require(totalSupply_ <= HARD_CAP);
}
/// @dev Create a TokenVault and fill with the specified newly minted tokens
function createTokenVaultInt(uint256 tokens) internal onlyOwner returns (TokenVault) {
TokenVault tokenVault = new TokenVault(ERC20(this));
createTokensInt(tokens, tokenVault);
tokenVault.fillUpAllowance();
return tokenVault;
}
// @dev create specified number of tokens and transfer to destination
function createTokensInt(uint256 _tokens, address _destination) internal onlyOwner {
uint256 tokens = _tokens * 10**uint256(decimals);
totalSupply_ = totalSupply_.add(tokens);
balances[_destination] = balances[_destination].add(tokens);
emit Transfer(0x0, _destination, tokens);
require(totalSupply_ <= HARD_CAP);
}
/// @dev vest Detail : second unit
function vestTokensDetailInt(
address _beneficiary,
uint256 _startS,
uint256 _cliffS,
uint256 _durationS,
bool _revocable,
uint256 _tokensAmountInt) external onlyOwner {
require(_beneficiary != address(0));
uint256 tokensAmount = _tokensAmountInt * 10**uint256(decimals);
if(vestingOf[_beneficiary] == 0x0) {
TokenVesting vesting = new TokenVesting(_beneficiary, _startS, _cliffS, _durationS, _revocable, owner);
vestingOf[_beneficiary] = address(vesting);
}
require(this.transferFrom(reserveTokensVault, vestingOf[_beneficiary], tokensAmount));
}
/// @dev vest StartAt : day unit
function vestTokensStartAtInt(
address _beneficiary,
uint256 _tokensAmountInt,
uint256 _startS,
uint256 _afterDay,
uint256 _cliffDay,
uint256 _durationDay ) public onlyOwner {
require(_beneficiary != address(0));
uint256 tokensAmount = _tokensAmountInt * 10**uint256(decimals);
uint256 afterSec = _afterDay * daySecond;
uint256 cliffSec = _cliffDay * daySecond;
uint256 durationSec = _durationDay * daySecond;
if(vestingOf[_beneficiary] == 0x0) {
TokenVesting vesting = new TokenVesting(_beneficiary, _startS + afterSec, cliffSec, durationSec, true, owner);
vestingOf[_beneficiary] = address(vesting);
}
require(this.transferFrom(reserveTokensVault, vestingOf[_beneficiary], tokensAmount));
}
/// @dev vest function from now
function vestTokensFromNowInt(address _beneficiary, uint256 _tokensAmountInt, uint256 _afterDay, uint256 _cliffDay, uint256 _durationDay ) public onlyOwner {
vestTokensStartAtInt(_beneficiary, _tokensAmountInt, now, _afterDay, _cliffDay, _durationDay);
}
/// @dev vest the sale contributor tokens for 100 days, 1% gradual release
function vestCmdNow1PercentInt(address _beneficiary, uint256 _tokensAmountInt) external onlyOwner {
vestTokensFromNowInt(_beneficiary, _tokensAmountInt, 0, 0, unlock100Days);
}
/// @dev vest the sale contributor tokens for 100 days, 1% gradual release after 3 month later, no cliff
function vestCmd3Month1PercentInt(address _beneficiary, uint256 _tokensAmountInt) external onlyOwner {
vestTokensFromNowInt(_beneficiary, _tokensAmountInt, lock90Days, 0, unlock100Days);
}
/// @dev vest the sale contributor tokens 100% release after 1 year
function vestCmd1YearInstantInt(address _beneficiary, uint256 _tokensAmountInt) external onlyOwner {
vestTokensFromNowInt(_beneficiary, _tokensAmountInt, 0, lock365Days, lock365Days);
}
/// @dev releases vested tokens for the caller's own address
function releaseVestedTokens() external {
releaseVestedTokensFor(msg.sender);
}
/// @dev releases vested tokens for the specified address.
/// Can be called by anyone for any address.
function releaseVestedTokensFor(address _owner) public {
TokenVesting(vestingOf[_owner]).release(this);
}
/// @dev check the vested balance for an address
function lockedBalanceOf(address _owner) public view returns (uint256) {
return balances[vestingOf[_owner]];
}
/// @dev check the locked but releaseable balance of an owner
function releaseableBalanceOf(address _owner) public view returns (uint256) {
if (vestingOf[_owner] == address(0) ) {
return 0;
} else {
return TokenVesting(vestingOf[_owner]).releasableAmount(this);
}
}
/// @dev revoke vested tokens for the specified address.
/// Tokens already vested remain in the contract, the rest are returned to the owner.
function revokeVestedTokensFor(address _owner) public onlyOwner {
TokenVesting(vestingOf[_owner]).revoke(this);
}
/// @dev Create a ReserveTokenVault
function makeReserveToVault() external onlyOwner {
require(reserveTokensVault != address(0));
reserveTokensVault.fillUpAllowance();
}
} | @dev Create a ReserveTokenVault | function makeReserveToVault() external onlyOwner {
require(reserveTokensVault != address(0));
reserveTokensVault.fillUpAllowance();
}
| 618,593 | [
1,
1684,
279,
1124,
6527,
1345,
12003,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
1221,
607,
6527,
774,
12003,
1435,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
455,
6527,
5157,
12003,
480,
1758,
12,
20,
10019,
203,
3639,
20501,
5157,
12003,
18,
5935,
1211,
7009,
1359,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.4;
import "./abstract/HasSecondarySaleFees.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract BlueprintV7 is
ERC721Upgradeable,
HasSecondarySaleFees,
AccessControlEnumerableUpgradeable
{
using StringsUpgradeable for uint256;
uint32 public defaultPlatformPrimaryFeePercentage;
uint32 public defaultBlueprintSecondarySalePercentage;
uint32 public defaultPlatformSecondarySalePercentage;
uint64 public latestErc721TokenIndex;
uint256 public blueprintIndex;
address public asyncSaleFeesRecipient;
address public platform;
address public minterAddress;
mapping(uint256 => uint256) tokenToBlueprintID;
mapping(address => uint256) failedTransferCredits;
mapping(uint256 => Blueprints) public blueprints;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
enum SaleState {
not_prepared,
not_started,
started,
paused
}
struct Blueprints {
bool tokenUriLocked;
uint32 mintAmountArtist;
uint32 mintAmountPlatform;
uint64 capacity;
uint64 erc721TokenIndex;
uint64 maxPurchaseAmount;
uint128 price;
address artist;
address ERC20Token;
string baseTokenUri;
bytes32 merkleroot;
SaleState saleState;
uint32[] primaryFeeBPS;
uint32[] secondaryFeeBPS;
address[] primaryFeeRecipients;
address[] secondaryFeeRecipients;
mapping(address => bool) claimedWhitelistedPieces;
}
event BlueprintSeed(uint256 blueprintID, string randomSeed);
event BlueprintMinted(
uint256 blueprintID,
address artist,
address purchaser,
uint128 tokenId,
uint64 newCapacity,
bytes32 seedPrefix
);
event BlueprintPrepared(
uint256 blueprintID,
address artist,
uint64 capacity,
string blueprintMetaData,
string baseTokenUri
);
event BlueprintSettingsUpdated(
uint256 blueprintID,
uint128 price,
uint32 newMintAmountArtist,
uint32 newMintAmountPlatform,
uint32 newSaleState,
uint64 newMaxPurchaseAmount,
bytes32 newMerkleRoot
);
event SaleStarted(uint256 blueprintID);
event SalePaused(uint256 blueprintID);
event SaleUnpaused(uint256 blueprintID);
event BlueprintTokenUriUpdated(uint256 blueprintID, string newBaseTokenUri);
modifier isBlueprintPrepared(uint256 _blueprintID) {
require(
blueprints[_blueprintID].saleState != SaleState.not_prepared,
"blueprint not prepared"
);
_;
}
modifier hasSaleStarted(uint256 _blueprintID) {
require(_hasSaleStarted(_blueprintID), "Sale not started");
_;
}
modifier BuyerWhitelistedOrSaleStarted(
uint256 _blueprintID,
uint32 _quantity,
bytes32[] calldata proof
) {
require(
_hasSaleStarted(_blueprintID) ||
(_isBlueprintPreparedAndNotStarted(_blueprintID) &&
userWhitelisted(_blueprintID, uint256(_quantity), proof)),
"not available to purchase"
);
_;
}
modifier isQuantityAvailableForPurchase(
uint256 _blueprintID,
uint32 _quantity
) {
require(
blueprints[_blueprintID].capacity >= _quantity,
"quantity exceeds capacity"
);
_;
}
///
///Initialize the implementation
///
function initialize(
string memory name_,
string memory symbol_,
address minter
) public initializer {
// Intialize parent contracts
ERC721Upgradeable.__ERC721_init(name_, symbol_);
HasSecondarySaleFees._initialize();
AccessControlUpgradeable.__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, minter);
platform = msg.sender;
minterAddress = minter;
defaultPlatformPrimaryFeePercentage = 2000; // 20%
defaultBlueprintSecondarySalePercentage = 750; // 7.5%
defaultPlatformSecondarySalePercentage = 250; // 2.5%
asyncSaleFeesRecipient = msg.sender;
}
function _hasSaleStarted(uint256 _blueprintID)
internal
view
returns (bool)
{
return blueprints[_blueprintID].saleState == SaleState.started;
}
function _isBlueprintPreparedAndNotStarted(uint256 _blueprintID)
internal
view
returns (bool)
{
return blueprints[_blueprintID].saleState == SaleState.not_started;
}
function _getFeePortion(uint256 _totalSaleAmount, uint256 _percentage)
internal
pure
returns (uint256)
{
return (_totalSaleAmount * (_percentage)) / 10000;
}
function userWhitelisted(
uint256 _blueprintID,
uint256 _quantity,
bytes32[] calldata proof
) internal view returns (bool) {
require(proof.length != 0, "no proof provided");
require(
!blueprints[_blueprintID].claimedWhitelistedPieces[msg.sender],
"already claimed"
);
bytes32 _merkleroot = blueprints[_blueprintID].merkleroot;
return _verify(_leaf(msg.sender, _quantity), _merkleroot, proof);
}
function feesApplicable(
address[] memory _feeRecipients,
uint32[] memory _feeBPS
) internal pure returns (bool) {
if (_feeRecipients.length != 0 || _feeBPS.length != 0) {
require(
_feeRecipients.length == _feeBPS.length,
"mismatched recipients & Bps"
);
uint32 totalPercent;
for (uint256 i = 0; i < _feeBPS.length; i++) {
totalPercent = totalPercent + _feeBPS[i];
}
require(totalPercent <= 10000, "Fee Bps exceed maximum");
return true;
}
return false;
}
function setBlueprintPrepared(
uint256 _blueprintID,
string memory _blueprintMetaData
) internal {
blueprints[_blueprintID].saleState = SaleState.not_started;
//assign the erc721 token index to the blueprint
blueprints[_blueprintID].erc721TokenIndex = latestErc721TokenIndex;
uint64 _capacity = blueprints[_blueprintID].capacity;
latestErc721TokenIndex += _capacity;
blueprintIndex++;
emit BlueprintPrepared(
_blueprintID,
blueprints[_blueprintID].artist,
_capacity,
_blueprintMetaData,
blueprints[_blueprintID].baseTokenUri
);
}
function setErc20Token(uint256 _blueprintID, address _erc20Token) internal {
if (_erc20Token != address(0)) {
blueprints[_blueprintID].ERC20Token = _erc20Token;
}
}
function _setupBlueprint(
uint256 _blueprintID,
address _erc20Token,
string memory _baseTokenUri,
bytes32 _merkleroot,
uint32 _mintAmountArtist,
uint32 _mintAmountPlatform,
uint32 _maxPurchaseAmount
) internal {
setErc20Token(_blueprintID, _erc20Token);
blueprints[_blueprintID].baseTokenUri = _baseTokenUri;
if (_merkleroot != 0) {
blueprints[_blueprintID].merkleroot = _merkleroot;
}
blueprints[_blueprintID].mintAmountArtist = _mintAmountArtist;
blueprints[_blueprintID].mintAmountPlatform = _mintAmountPlatform;
if (_maxPurchaseAmount != 0) {
blueprints[_blueprintID].maxPurchaseAmount = _maxPurchaseAmount;
}
}
function prepareBlueprint(
address _artist,
uint64 _capacity,
uint128 _price,
address _erc20Token,
string memory _blueprintMetaData,
string memory _baseTokenUri,
bytes32 _merkleroot,
uint32 _mintAmountArtist,
uint32 _mintAmountPlatform,
uint32 _maxPurchaseAmount
) external onlyRole(MINTER_ROLE) {
uint256 _blueprintID = blueprintIndex;
blueprints[_blueprintID].artist = _artist;
blueprints[_blueprintID].capacity = _capacity;
blueprints[_blueprintID].price = _price;
_setupBlueprint(
_blueprintID,
_erc20Token,
_baseTokenUri,
_merkleroot,
_mintAmountArtist,
_mintAmountPlatform,
_maxPurchaseAmount
);
setBlueprintPrepared(_blueprintID, _blueprintMetaData);
}
function updateBlueprintSettings (
uint256 _blueprintID,
uint128 _price,
uint32 _mintAmountArtist,
uint32 _mintAmountPlatform,
uint32 _newSaleState,
uint64 _newMaxPurchaseAmount,
bytes32 _merkleroot
) external onlyRole(MINTER_ROLE) {
blueprints[_blueprintID].price = _price;
blueprints[_blueprintID].mintAmountArtist = _mintAmountArtist;
blueprints[_blueprintID].mintAmountPlatform = _mintAmountPlatform;
blueprints[_blueprintID].saleState = SaleState (_newSaleState);
blueprints[_blueprintID].merkleroot = _merkleroot;
blueprints[_blueprintID].maxPurchaseAmount = _newMaxPurchaseAmount;
emit BlueprintSettingsUpdated(_blueprintID, _price, _mintAmountArtist, _mintAmountPlatform, _newSaleState, _newMaxPurchaseAmount, _merkleroot);
}
function setFeeRecipients(
uint256 _blueprintID,
address[] memory _primaryFeeRecipients,
uint32[] memory _primaryFeeBPS,
address[] memory _secondaryFeeRecipients,
uint32[] memory _secondaryFeeBPS
) external onlyRole(MINTER_ROLE) {
require(
blueprints[_blueprintID].saleState == SaleState.not_started,
"sale started or not prepared"
);
if (feesApplicable(_primaryFeeRecipients, _primaryFeeBPS)) {
blueprints[_blueprintID]
.primaryFeeRecipients = _primaryFeeRecipients;
blueprints[_blueprintID].primaryFeeBPS = _primaryFeeBPS;
}
if (feesApplicable(_secondaryFeeRecipients, _secondaryFeeBPS)) {
blueprints[_blueprintID]
.secondaryFeeRecipients = _secondaryFeeRecipients;
blueprints[_blueprintID].secondaryFeeBPS = _secondaryFeeBPS;
}
}
function beginSale(uint256 blueprintID) external onlyRole(MINTER_ROLE) {
require(
blueprints[blueprintID].saleState == SaleState.not_started,
"sale started or not prepared"
);
blueprints[blueprintID].saleState = SaleState.started;
emit SaleStarted(blueprintID);
}
function pauseSale(uint256 blueprintID)
external
onlyRole(MINTER_ROLE)
hasSaleStarted(blueprintID)
{
blueprints[blueprintID].saleState = SaleState.paused;
emit SalePaused(blueprintID);
}
function unpauseSale(uint256 blueprintID) external onlyRole(MINTER_ROLE) {
require(
blueprints[blueprintID].saleState == SaleState.paused,
"Sale not paused"
);
blueprints[blueprintID].saleState = SaleState.started;
emit SaleUnpaused(blueprintID);
}
function purchaseBlueprintsTo(
uint256 blueprintID,
uint32 quantity,
uint256 tokenAmount,
bytes32[] calldata proof,
address nftRecipient
)
external
payable
BuyerWhitelistedOrSaleStarted(blueprintID, quantity, proof)
isQuantityAvailableForPurchase(blueprintID, quantity)
{
require(
blueprints[blueprintID].maxPurchaseAmount == 0 ||
quantity <= blueprints[blueprintID].maxPurchaseAmount,
"user cannot buy more than maxPurchaseAmount in single tx"
);
require (tx.origin == msg.sender, "purchase cannot be called from another contract");
address _artist = blueprints[blueprintID].artist;
_confirmPaymentAmountAndSettleSale(
blueprintID,
quantity,
tokenAmount,
_artist
);
if (blueprints[blueprintID].saleState == SaleState.not_started) {
blueprints[blueprintID].claimedWhitelistedPieces[msg.sender] = true;
}
_mintQuantity(blueprintID, quantity, nftRecipient);
}
function purchaseBlueprints(
uint256 blueprintID,
uint32 quantity,
uint256 tokenAmount,
bytes32[] calldata proof
)
external
payable
BuyerWhitelistedOrSaleStarted(blueprintID, quantity, proof)
isQuantityAvailableForPurchase(blueprintID, quantity)
{
require(
blueprints[blueprintID].maxPurchaseAmount == 0 ||
quantity <= blueprints[blueprintID].maxPurchaseAmount,
"user cannot buy more than maxPurchaseAmount in single tx"
);
require (tx.origin == msg.sender, "purchase cannot be called from another contract");
address _artist = blueprints[blueprintID].artist;
_confirmPaymentAmountAndSettleSale(
blueprintID,
quantity,
tokenAmount,
_artist
);
if (blueprints[blueprintID].saleState == SaleState.not_started) {
blueprints[blueprintID].claimedWhitelistedPieces[msg.sender] = true;
}
_mintQuantity(blueprintID, quantity, msg.sender);
}
function preSaleMint(uint256 blueprintID, uint32 quantity) external {
require(
_isBlueprintPreparedAndNotStarted(blueprintID),
"Must be prepared and not started"
);
require(
minterAddress == msg.sender ||
blueprints[blueprintID].artist == msg.sender,
"user cannot mint presale"
);
if (minterAddress == msg.sender) {
require(
quantity <= blueprints[blueprintID].mintAmountPlatform,
"cannot mint quantity"
);
blueprints[blueprintID].mintAmountPlatform -= quantity;
} else if (blueprints[blueprintID].artist == msg.sender) {
require(
quantity <= blueprints[blueprintID].mintAmountArtist,
"cannot mint quantity"
);
blueprints[blueprintID].mintAmountArtist -= quantity;
}
_mintQuantity(blueprintID, quantity, msg.sender);
}
/*
* Iterate and mint each blueprint for user
*/
function _mintQuantity(uint256 _blueprintID, uint32 _quantity, address _nftRecipient) private {
uint128 newTokenId = blueprints[_blueprintID].erc721TokenIndex;
uint64 newCap = blueprints[_blueprintID].capacity;
for (uint16 i = 0; i < _quantity; i++) {
require(newCap > 0, "blueprint out of capacity");
_mint(_nftRecipient, newTokenId + i);
tokenToBlueprintID[newTokenId + i] = _blueprintID;
bytes32 prefixHash = keccak256(
abi.encodePacked(
block.number,
block.timestamp,
block.coinbase,
newCap
)
);
emit BlueprintMinted(
_blueprintID,
blueprints[_blueprintID].artist,
_nftRecipient,
newTokenId + i,
newCap,
prefixHash
);
--newCap;
}
blueprints[_blueprintID].erc721TokenIndex += _quantity;
blueprints[_blueprintID].capacity = newCap;
}
function _confirmPaymentAmountAndSettleSale(
uint256 _blueprintID,
uint32 _quantity,
uint256 _tokenAmount,
address _artist
) internal {
address _erc20Token = blueprints[_blueprintID].ERC20Token;
uint128 _price = blueprints[_blueprintID].price;
if (_erc20Token == address(0)) {
require(_tokenAmount == 0, "cannot specify token amount");
require(
msg.value == _quantity * _price,
"Purchase amount must match price"
);
_payFeesAndArtist(_blueprintID, _erc20Token, msg.value, _artist);
} else {
require(msg.value == 0, "cannot specify eth amount");
require(
_tokenAmount == _quantity * _price,
"Purchase amount must match price"
);
IERC20(_erc20Token).transferFrom(
msg.sender,
address(this),
_tokenAmount
);
_payFeesAndArtist(_blueprintID, _erc20Token, _tokenAmount, _artist);
}
}
////////////////////////////////////
////// MERKLEROOT FUNCTIONS ////////
////////////////////////////////////
/**
* Create a merkle tree with address: quantity pairs as the leaves.
* The msg.sender will be verified if it has a corresponding quantity value in the merkletree
*/
function _leaf(address account, uint256 quantity)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account, quantity));
}
function _verify(
bytes32 leaf,
bytes32 merkleroot,
bytes32[] memory proof
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleroot, leaf);
}
////////////////////////////
/// ONLY ADMIN functions ///
////////////////////////////
function updateBlueprintTokenUri(
uint256 blueprintID,
string memory newBaseTokenUri
) external onlyRole(MINTER_ROLE) isBlueprintPrepared(blueprintID) {
require(
!blueprints[blueprintID].tokenUriLocked,
"blueprint URI locked"
);
blueprints[blueprintID].baseTokenUri = newBaseTokenUri;
emit BlueprintTokenUriUpdated(blueprintID, newBaseTokenUri);
}
function lockBlueprintTokenUri(uint256 blueprintID)
external
onlyRole(DEFAULT_ADMIN_ROLE)
isBlueprintPrepared(blueprintID)
{
require(
!blueprints[blueprintID].tokenUriLocked,
"blueprint URI locked"
);
blueprints[blueprintID].tokenUriLocked = true;
}
function _baseURIForBlueprint(uint256 tokenId) internal view returns (string memory) {
return blueprints[tokenToBlueprintID[tokenId]].baseTokenUri;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURIForBlueprint(tokenId);
return
bytes(baseURI).length > 0
? string(
abi.encodePacked(
baseURI,
"/",
tokenId.toString(),
"/",
"token.json"
)
)
: "";
}
function revealBlueprintSeed(uint256 blueprintID, string memory randomSeed)
external
onlyRole(MINTER_ROLE)
isBlueprintPrepared(blueprintID)
{
emit BlueprintSeed(blueprintID, randomSeed);
}
function setAsyncFeeRecipient(address _asyncSaleFeesRecipient)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
asyncSaleFeesRecipient = _asyncSaleFeesRecipient;
}
function changeDefaultPlatformPrimaryFeePercentage(uint32 _basisPoints)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_basisPoints <= 10000);
defaultPlatformPrimaryFeePercentage = _basisPoints;
}
function changeDefaultBlueprintSecondarySalePercentage(uint32 _basisPoints)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_basisPoints + defaultPlatformSecondarySalePercentage <= 10000);
defaultBlueprintSecondarySalePercentage = _basisPoints;
}
function changeDefaultPlatformSecondarySalePercentage(uint32 _basisPoints)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
_basisPoints + defaultBlueprintSecondarySalePercentage <= 10000
);
defaultPlatformSecondarySalePercentage = _basisPoints;
}
function updatePlatformAddress(address _platform)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
grantRole(DEFAULT_ADMIN_ROLE, _platform);
revokeRole(DEFAULT_ADMIN_ROLE, platform);
platform = _platform;
}
// Allows the platform to change the minter address
function updateMinterAddress(address newMinterAddress)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
grantRole(MINTER_ROLE, newMinterAddress);
revokeRole(MINTER_ROLE, minterAddress);
minterAddress = newMinterAddress;
}
////////////////////////////////////
/// Secondary Fees implementation //
////////////////////////////////////
function _payFeesAndArtist(
uint256 _blueprintID,
address _erc20Token,
uint256 _amount,
address _artist
) internal {
address[] memory _primaryFeeRecipients = getPrimaryFeeRecipients(
_blueprintID
);
uint32[] memory _primaryFeeBPS = getPrimaryFeeBps(_blueprintID);
uint256 feesPaid;
for (uint256 i = 0; i < _primaryFeeRecipients.length; i++) {
uint256 fee = _getFeePortion(_amount, _primaryFeeBPS[i]);
feesPaid = feesPaid + fee;
_payout(_primaryFeeRecipients[i], _erc20Token, fee);
}
if (_amount - feesPaid > 0) {
_payout(_artist, _erc20Token, (_amount - feesPaid));
}
}
function _payout(
address _recipient,
address _erc20Token,
uint256 _amount
) internal {
if (_erc20Token != address(0)) {
IERC20(_erc20Token).transfer(_recipient, _amount);
} else {
// attempt to send the funds to the recipient
(bool success, ) = payable(_recipient).call{
value: _amount,
gas: 20000
}("");
// if it failed, update their credit balance so they can pull it later
if (!success) {
failedTransferCredits[_recipient] =
failedTransferCredits[_recipient] +
_amount;
}
}
}
function withdrawAllFailedCredits(address payable recipient) external {
uint256 amount = failedTransferCredits[msg.sender];
require(amount != 0, "no credits to withdraw");
failedTransferCredits[msg.sender] = 0;
(bool successfulWithdraw, ) = recipient.call{value: amount, gas: 20000}(
""
);
require(successfulWithdraw, "withdraw failed");
}
function getPrimaryFeeRecipients(uint256 id)
public
view
returns (address[] memory)
{
if (blueprints[id].primaryFeeRecipients.length == 0) {
address[] memory primaryFeeRecipients = new address[](1);
primaryFeeRecipients[0] = (asyncSaleFeesRecipient);
return primaryFeeRecipients;
} else {
return blueprints[id].primaryFeeRecipients;
}
}
function getPrimaryFeeBps(uint256 id)
public
view
returns (uint32[] memory)
{
if (blueprints[id].primaryFeeBPS.length == 0) {
uint32[] memory primaryFeeBPS = new uint32[](1);
primaryFeeBPS[0] = defaultPlatformPrimaryFeePercentage;
return primaryFeeBPS;
} else {
return blueprints[id].primaryFeeBPS;
}
}
function getFeeRecipients(uint256 id)
public
view
override
returns (address[] memory)
{
if (blueprints[id].secondaryFeeRecipients.length == 0) {
address[] memory feeRecipients = new address[](2);
feeRecipients[0] = (asyncSaleFeesRecipient);
feeRecipients[1] = (blueprints[id].artist);
return feeRecipients;
} else {
return blueprints[id].secondaryFeeRecipients;
}
}
function getFeeBps(uint256 id)
public
view
override
returns (uint32[] memory)
{
if (blueprints[id].secondaryFeeBPS.length == 0) {
uint32[] memory feeBPS = new uint32[](2);
feeBPS[0] = defaultPlatformSecondarySalePercentage;
feeBPS[1] = defaultBlueprintSecondarySalePercentage;
return feeBPS;
} else {
return blueprints[id].secondaryFeeBPS;
}
}
////////////////////////////////////
/// Required function overide //////
////////////////////////////////////
function isApprovedForAll(address account, address operator)
public
view
override
returns (bool)
{
return
super.isApprovedForAll(account, operator) ||
hasRole(DEFAULT_ADMIN_ROLE, operator);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(
ERC721Upgradeable,
ERC165StorageUpgradeable,
AccessControlEnumerableUpgradeable
)
returns (bool)
{
return
ERC721Upgradeable.supportsInterface(interfaceId) ||
ERC165StorageUpgradeable.supportsInterface(interfaceId) ||
AccessControlEnumerableUpgradeable.supportsInterface(interfaceId);
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165StorageUpgradeable.sol";
abstract contract HasSecondarySaleFees is ERC165StorageUpgradeable {
event SecondarySaleFees(
uint256 tokenId,
address[] recipients,
uint256[] bps
);
/*
* bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
* bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
*
* => 0x0ebd4c7f ^ 0xb9c4d9fb == 0xb7799584
*/
bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584;
function _initialize() public initializer {
_registerInterface(_INTERFACE_ID_FEES);
}
function getFeeRecipients(uint256 id)
public
view
virtual
returns (address[] memory);
function getFeeBps(uint256 id)
public
view
virtual
returns (uint32[] memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable 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.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.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 {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `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
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165Storage.sol)
pragma solidity ^0.8.0;
import "./ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Storage based implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165StorageUpgradeable is Initializable, ERC165Upgradeable {
function __ERC165Storage_init() internal initializer {
__ERC165_init_unchained();
__ERC165Storage_init_unchained();
}
function __ERC165Storage_init_unchained() internal initializer {
}
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return super.supportsInterface(interfaceId) || _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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol)
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.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
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
// OpenZeppelin Contracts v4.4.0 (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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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 IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
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
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal 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
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @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) external view returns (address);
/**
* @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) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
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 {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// 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);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// 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))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @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 {AccessControl-_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) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @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) external;
/**
* @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) external;
/**
* @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) external;
} | * @dev Storage based implementation of the {IERC165} interface. Contracts may inherit from this and call {_registerInterface} to declare their support of an interface./ | abstract contract ERC165StorageUpgradeable is Initializable, ERC165Upgradeable {
function __ERC165Storage_init() internal initializer {
__ERC165_init_unchained();
__ERC165Storage_init_unchained();
}
function __ERC165Storage_init_unchained() internal initializer {
}
mapping(bytes4 => bool) private _supportedInterfaces;
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return super.supportsInterface(interfaceId) || _supportedInterfaces[interfaceId];
}
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
| 62,585 | [
1,
3245,
2511,
4471,
434,
326,
288,
45,
654,
39,
28275,
97,
1560,
18,
30131,
2026,
6811,
628,
333,
471,
745,
288,
67,
4861,
1358,
97,
358,
14196,
3675,
2865,
434,
392,
1560,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
4232,
39,
28275,
3245,
10784,
429,
353,
10188,
6934,
16,
4232,
39,
28275,
10784,
429,
288,
203,
203,
565,
445,
1001,
654,
39,
28275,
3245,
67,
2738,
1435,
2713,
12562,
288,
203,
3639,
1001,
654,
39,
28275,
67,
2738,
67,
4384,
8707,
5621,
203,
3639,
1001,
654,
39,
28275,
3245,
67,
2738,
67,
4384,
8707,
5621,
203,
565,
289,
203,
203,
565,
445,
1001,
654,
39,
28275,
3245,
67,
2738,
67,
4384,
8707,
1435,
2713,
12562,
288,
203,
565,
289,
203,
203,
565,
2874,
12,
3890,
24,
516,
1426,
13,
3238,
389,
4127,
10273,
31,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
28064,
1358,
12,
5831,
548,
13,
747,
389,
4127,
10273,
63,
5831,
548,
15533,
203,
565,
289,
203,
203,
565,
445,
389,
4861,
1358,
12,
3890,
24,
1560,
548,
13,
2713,
5024,
288,
203,
3639,
2583,
12,
5831,
548,
480,
374,
28857,
16,
315,
654,
39,
28275,
30,
2057,
1560,
612,
8863,
203,
3639,
389,
4127,
10273,
63,
5831,
548,
65,
273,
638,
31,
203,
565,
289,
203,
565,
2254,
5034,
63,
7616,
65,
3238,
1001,
14048,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^ 0.5 .1;
// ----------------------------------------------------------------------------
//'ButtCoin' contract, version 2.1
// See: https://github.com/butttcoin/0xBUTT
// Symbol : 0xBUTT
// Name : ButtCoin
// Total supply: Dynamic
// Decimals : 8
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
//addition
function add(uint a, uint b) internal pure returns(uint c) {
c = a + b;
require(c >= a);
}
//subtraction
function sub(uint a, uint b) internal pure returns(uint c) {
require(b <= a);
c = a - b;
}
//multiplication
function mul(uint a, uint b) internal pure returns(uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
//division
function div(uint a, uint b) internal pure returns(uint c) {
require(b > 0);
c = a / b;
}
//ceil
function ceil(uint a, uint m) internal pure returns(uint) {
uint c = add(a, m);
uint d = sub(c, 1);
return mul(div(d, m), m);
}
}
library ExtendedMath {
//also known as the minimum
function limitLessThan(uint a, uint b) internal pure returns(uint c) {
if (a > b) return b;
return a;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns(uint);
function burned() public view returns(uint);
function minted() public view returns(uint);
function mintingEpoch() public view returns(uint);
function balanceOf(address tokenOwner) public view returns(uint balance);
function allowance(address tokenOwner, address spender) public view returns(uint remaining);
function transfer(address to, uint tokens) public returns(bool success);
function approve(address spender, uint tokens) public returns(bool success);
function transferFrom(address from, address to, uint tokens) public returns(bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
contract ZERO_X_BUTTv3 is ERC20Interface, Owned {
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint256 public _totalSupply;
uint256 public _burned;
//a big number is easier ; just find a solution that is smaller
uint private n = 212; //the maxiumum target exponent
uint private nFutureTime = now + 1097 days; // about 3 years in future
uint public _MAXIMUM_TARGET = 2 ** n;
bytes32 public challengeNumber; //generate a new one when a new reward is minted
uint public rewardEra;
address public lastRewardTo;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
mapping(bytes32 => bytes32) solutionForChallenge;
uint public tokensMinted;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
uint private basePercent;
bool private locked = false;
address private previousSender = address(0); //the previous user of a contract
uint private miningTarget;
uint private _mintingEpoch;
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
if (locked) revert();
symbol = "0xBUTT";
name = "ButtCoin";
decimals = 8;
basePercent = 100;
uint toMint = 33554432 * 10 ** uint(decimals); //This is an assumption and a kick-start, which resets when 75% is burned.
_mint(msg.sender, toMint);
tokensMinted = toMint;
_totalSupply = _totalSupply.add(toMint);
rewardEra = 22;
miningTarget = _MAXIMUM_TARGET;
_startNewMiningEpoch();
_mintingEpoch = 0;
locked = true;
}
// ------------------------------------------------------------------------
// Minting tokens before the mining.
// ------------------------------------------------------------------------
function _mint(address account, uint256 amount) internal {
if (locked) revert();
require(amount != 0);
balances[account] = balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
// ------------------------------------------------------------------------
// Minting of tokens during the mining.
// ------------------------------------------------------------------------
function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success) {
//the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks
bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce));
//the challenge digest must match the expected
if (digest != challenge_digest) revert();
//the digest must be smaller than the target
if (uint256(digest) > miningTarget) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if (solution != 0x0) revert(); //prevent the same answer from awarding twice
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMinted = tokensMinted.add(reward_amount);
_totalSupply = _totalSupply.add(tokensMinted);
//set readonly diagnostics data
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
emit Mint(msg.sender, reward_amount, rewardEra, challengeNumber);
return true;
}
// ------------------------------------------------------------------------
// Starts a new mining epoch, a new 'block' to be mined.
// ------------------------------------------------------------------------
function _startNewMiningEpoch() internal {
rewardEra = rewardEra + 1; //increment the rewardEra
checkMintedNumber();
_reAdjustDifficulty();
challengeNumber = blockhash(block.number - 1);
}
//checks if the minted number is too high, reduces a tracking number if it is
function checkMintedNumber() internal {
if (tokensMinted >= (2 ** (230))) { //This will not happen in the forseable future.
//50 is neither too low or too high, we'd need additional tracking to get overall totals after this.
tokensMinted = tokensMinted.div(2 ** (50));
_burned = _burned.div(2 ** (50));
_mintingEpoch = _mintingEpoch + 1;
}
}
// ------------------------------------------------------------------------
// Readjust difficulty
// ------------------------------------------------------------------------
function _reAdjustDifficulty() internal {
n = n - 1;
miningTarget = (2 ** n);
nFutureTime = now + 1097 days;
//if difficulty level became too much for the miners and coins are running out of a supply, we need to lower a difficulty to mint new coins...
//this way, the coin does not become store of a value. Nevertheless, it may be required for the miners to do some extra work to lower a difficulty.
uint treshold = (tokensMinted.mul(95)).div(100);
if(_burned>=treshold){
//lower difficulty to significant levels
n = (n.mul(105)).div(100);
if(n > 213){n = 213;}
miningTarget = (2 ** n);
}
}
// -------------------------------------------------------------------------------
// this is a recent ethereum block hash, used to prevent pre-mining future blocks.
// -------------------------------------------------------------------------------
function getChallengeNumber() public view returns(bytes32) {
return challengeNumber;
}
// -------------------------------------------------------------------------------
// Auto adjusts the number of zeroes the digest of the PoW solution requires.
// -------------------------------------------------------------------------------
function getMiningDifficulty() public view returns(uint) {
return _MAXIMUM_TARGET.div(miningTarget);
}
// -------------------------------------------------------------------------------
// returns the miningTarget.
// -------------------------------------------------------------------------------
function getMiningTarget() public view returns(uint) {
return miningTarget;
}
// ------------------------------------------------------------------------
// Gives miners their earned reward, zero if everything is mined.
// ------------------------------------------------------------------------
function getMiningReward() internal returns(uint) {
uint reward = ((234 - n) ** 3) * 10 ** uint(decimals);
return reward;
}
// ------------------------------------------------------------------------
// Used to help debugging the mining software.
// ------------------------------------------------------------------------
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns(bytes32 digesttest) {
bytes32 digest = keccak256(abi.encodePacked(challenge_number, msg.sender, nonce));
return digest;
}
// ------------------------------------------------------------------------
// Used to help debugging the mining software.
// ------------------------------------------------------------------------
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns(bool success) {
bytes32 digest = keccak256(abi.encodePacked(challenge_number, msg.sender, nonce));
if (uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns(uint) {
return tokensMinted.sub(_burned);
}
// ------------------------------------------------------------------------
// Burned tokens
// ------------------------------------------------------------------------
function burned() public view returns(uint) {
return _burned;
}
// ------------------------------------------------------------------------
// Minted tokens
// ------------------------------------------------------------------------
function minted() public view returns(uint) {
return tokensMinted;
}
// ------------------------------------------------------------------------
// Minting epoch
// ------------------------------------------------------------------------
function mintingEpoch() public view returns(uint) {
return _mintingEpoch;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns(uint balance) {
return balances[tokenOwner];
}
function pulseCheck() internal{
//if either the coin is dead or the mining is stuck
if(nFutureTime<=now){
n = (n.mul(150)).div(100);
miningTarget = (2 ** n);
_startNewMiningEpoch();
}
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
//Otherwise, it is a bug
function sendTo(address to, uint tokens) public returns(bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transfer(address to, uint tokens) public returns(bool success) {
pulseCheck();
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
uint256 tokensToBurn = findTwoPercent(tokens);
uint256 toZeroAddress = tokensToBurn.div(2);
uint256 toPreviousAddress = tokensToBurn.sub(toZeroAddress);
uint256 tokensToTransfer = tokens.sub(toZeroAddress.add(toPreviousAddress));
sendTo(msg.sender, to, tokensToTransfer);
sendTo(msg.sender, address(0), toZeroAddress);
if (previousSender != to) { //Don't send the tokens to yourself
sendTo(to, previousSender, toPreviousAddress);
if (previousSender == address(0)) {
_burned = _burned.add(toPreviousAddress);
}
}
if (to == address(0)) {
_burned = _burned.add(tokensToTransfer);
}
_burned = _burned.add(toZeroAddress);
_totalSupply = totalSupply();
previousSender = msg.sender;
return true;
}
// ------------------------------------------------------------------------
// Transfers to multiple accounts
// ------------------------------------------------------------------------
function multiTransfer(address[] memory receivers, uint256[] memory amounts) public {
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
}
}
// ------------------------------------------------------------------------
// Calculates 2% for burning
// ------------------------------------------------------------------------
function findTwoPercent(uint256 value) private view returns(uint256) {
uint256 roundValue = value.ceil(basePercent);
uint256 onePercent = roundValue.mul(basePercent).div(10000);
return onePercent.mul(2);
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns(bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
//otherwise, it is a bug
function sendTo(address from, address to, uint tokens) public returns(bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns(bool success) {
pulseCheck();
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
uint256 tokensToBurn = findTwoPercent(tokens);
uint256 toZeroAddress = tokensToBurn.div(2);
uint256 toPreviousAddress = tokensToBurn - toZeroAddress;
uint256 tokensToTransfer = tokens.sub(toZeroAddress).sub(toPreviousAddress);
sendTo(msg.sender, to, tokensToTransfer);
sendTo(msg.sender, address(0), toZeroAddress);
if (previousSender != to) { //Don't send tokens to yourself
sendTo(to, previousSender, toPreviousAddress);
if (previousSender == address(0)) {
_burned = _burned.add(toPreviousAddress);
}
}
if (to == address(0)) {
_burned = _burned.add(tokensToTransfer);
}
_burned = _burned.add(toZeroAddress);
_totalSupply = totalSupply();
previousSender = msg.sender;
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns(uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns(bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Do not accept ETH
// ------------------------------------------------------------------------
function () external payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns(bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | if either the coin is dead or the mining is stuck | function pulseCheck() internal{
if(nFutureTime<=now){
n = (n.mul(150)).div(100);
miningTarget = (2 ** n);
_startNewMiningEpoch();
}
}
| 12,815,705 | [
1,
430,
3344,
326,
13170,
353,
8363,
578,
326,
1131,
310,
353,
384,
9031,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
31963,
1564,
1435,
2713,
95,
203,
565,
309,
12,
82,
4118,
950,
32,
33,
3338,
15329,
203,
1377,
290,
273,
261,
82,
18,
16411,
12,
23014,
13,
2934,
2892,
12,
6625,
1769,
7010,
1377,
1131,
310,
2326,
273,
261,
22,
2826,
290,
1769,
203,
1377,
389,
1937,
1908,
2930,
310,
14638,
5621,
203,
565,
289,
21281,
4202,
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
] |
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "../interfaces/INCT.sol";
import "../interfaces/INFT20Pair.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "../interfaces/IFlashLoanReceiver.sol";
import "../interfaces/IUniswapV2Router.sol";
contract HashMaskFlash is IFlashLoanReceiver, IERC721Receiver {
INCT public constant NCT = INCT(0x8A9c4dfe8b9D8962B31e4e16F8321C44d48e246E);
IERC721 public constant HASHMASK =
IERC721(0xC2C747E0F7004F9E8817Db2ca4997657a7746928);
INFT20Pair public constant MASK20 =
INFT20Pair(0xc2BdE1A2fA26890c8E6AcB10C91CC6D9c11F4a73);
IUniswapV2Router public constant ROUTER_V2 =
IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
INFT20Pair public constant WETH =
INFT20Pair(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
constructor() public {
HASHMASK.setApprovalForAll(address(MASK20), true);
NCT.approve(address(ROUTER_V2), uint256(-1));
}
function executeOperation(
uint256[] calldata _ids,
uint256[] calldata _amounts,
address initiator,
bytes calldata params
) external override returns (bool) {
NCT.claim(_ids);
// Sell it on uniswap
address[] memory uni_path = new address[](2);
uni_path[0] = address(NCT);
uni_path[1] = address(WETH);
ROUTER_V2.swapExactTokensForTokens(
NCT.balanceOf(address(this)),
0,
uni_path,
address(this),
block.timestamp + 1
);
// Transfer back wETH
WETH.transfer(
address(0x6fBa46974b2b1bEfefA034e236A32e1f10C5A148),
(WETH.balanceOf(address(this)) * 10) / 100
); //transfer 10% to dao
WETH.transfer(initiator, WETH.balanceOf(address(this)));
return true;
}
function onERC721Received(
address operator,
address,
uint256,
bytes memory data
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.6.0;
interface INCT {
function totalSupply() external view returns (uint256);
function balanceOf(address tokenOwner)
external
view
returns (uint256 balance);
function allowance(address tokenOwner, address spender)
external
view
returns (uint256 remaining);
function transfer(address to, uint256 tokens)
external
returns (bool success);
function approve(address spender, uint256 tokens)
external
returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) external returns (bool success);
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function accumulated(uint256 tokenIndex) external view returns (uint256);
function claim(uint256[] calldata tokenIndices) external returns (uint256);
}
pragma solidity ^0.6.0;
// Interface for our erc20 token
interface INFT20Pair {
function totalSupply() external view returns (uint256);
function balanceOf(address tokenOwner)
external
view
returns (uint256 balance);
function allowance(address tokenOwner, address spender)
external
view
returns (uint256 remaining);
function transfer(address to, uint256 tokens)
external
returns (bool success);
function approve(address spender, uint256 tokens)
external
returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) external returns (bool success);
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function nftType() external view returns (uint256);
function nftAddress() external view returns (address);
function track1155(uint256 _id) external view returns (uint256);
function setParams(
uint256 _nftType,
string calldata name,
string calldata symbol,
uint256 value
) external;
function getInfos()
external
view
returns (
uint256 _type,
string memory _name,
string memory _symbol,
uint256 _supply
);
function init(
string calldata name,
string calldata symbol,
address _nftAddress,
uint256 _nftType
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../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: Unlicense
pragma solidity ^0.6.0;
interface IFlashLoanReceiver {
function executeOperation(
uint256[] calldata _ids,
uint256[] calldata _amounts,
address initiator,
bytes calldata params
) external returns (bool);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.6.0;
interface IUniswapV2Router {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| Sell it on uniswap Transfer back wETH | function executeOperation(
uint256[] calldata _ids,
uint256[] calldata _amounts,
address initiator,
bytes calldata params
) external override returns (bool) {
NCT.claim(_ids);
address[] memory uni_path = new address[](2);
uni_path[0] = address(NCT);
uni_path[1] = address(WETH);
ROUTER_V2.swapExactTokensForTokens(
NCT.balanceOf(address(this)),
0,
uni_path,
address(this),
block.timestamp + 1
);
WETH.transfer(
address(0x6fBa46974b2b1bEfefA034e236A32e1f10C5A148),
(WETH.balanceOf(address(this)) * 10) / 100
WETH.transfer(initiator, WETH.balanceOf(address(this)));
return true;
}
| 6,332,685 | [
1,
55,
1165,
518,
603,
640,
291,
91,
438,
12279,
1473,
341,
1584,
44,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
1836,
2988,
12,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
2232,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
8949,
87,
16,
203,
3639,
1758,
26030,
16,
203,
3639,
1731,
745,
892,
859,
203,
565,
262,
3903,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
423,
1268,
18,
14784,
24899,
2232,
1769,
203,
3639,
1758,
8526,
3778,
7738,
67,
803,
273,
394,
1758,
8526,
12,
22,
1769,
203,
3639,
7738,
67,
803,
63,
20,
65,
273,
1758,
12,
50,
1268,
1769,
203,
3639,
7738,
67,
803,
63,
21,
65,
273,
1758,
12,
59,
1584,
44,
1769,
203,
3639,
534,
5069,
654,
67,
58,
22,
18,
22270,
14332,
5157,
1290,
5157,
12,
203,
5411,
423,
1268,
18,
12296,
951,
12,
2867,
12,
2211,
13,
3631,
203,
5411,
374,
16,
203,
5411,
7738,
67,
803,
16,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
1203,
18,
5508,
397,
404,
203,
3639,
11272,
203,
3639,
678,
1584,
44,
18,
13866,
12,
203,
5411,
1758,
12,
20,
92,
26,
74,
38,
69,
24,
8148,
5608,
70,
22,
70,
21,
70,
41,
3030,
29534,
4630,
24,
73,
29941,
37,
1578,
73,
21,
74,
2163,
39,
25,
37,
25005,
3631,
203,
5411,
261,
59,
1584,
44,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
380,
1728,
13,
342,
2130,
203,
3639,
678,
1584,
44,
18,
13866,
12,
2738,
10620,
16,
678,
1584,
44,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xFAAed55Cac3D691257d5250E29aDcfeF720744e3/sources/project_/contracts/HSBCFCNCalculation.sol | This is because the accrued coupon has 10 ** decimals() twice and should be in percent, please do not divide by (10 ** Decimals() ** 2) directly as it causes evaluation to go to zero. | payment.payment_amount = denomination + (denomination * accrued_coupon) / (10 ** decimals) / (10 ** decimals);
| 5,557,020 | [
1,
2503,
353,
2724,
326,
4078,
86,
5957,
16174,
711,
1728,
225,
15105,
1435,
13605,
471,
1410,
506,
316,
5551,
16,
9582,
741,
486,
12326,
635,
261,
2163,
225,
3416,
11366,
1435,
225,
576,
13,
5122,
487,
518,
14119,
9873,
358,
1960,
358,
3634,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
10792,
5184,
18,
9261,
67,
8949,
273,
10716,
1735,
397,
261,
13002,
362,
1735,
380,
4078,
86,
5957,
67,
24090,
13,
342,
261,
2163,
2826,
15105,
13,
342,
261,
2163,
2826,
15105,
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
] |
pragma solidity ^0.4.11;
/*
Use constant modifier if your function does not modify storage and
constant if it does not even read any state information
*/
contract PerfTest
{
address public _owner;
// Constructor
function PerfTest() public {
_owner = msg.sender;
}
/*======================= STORAGE RELATED PATTERNS ========================================================
======================================================================================================*/
/* Useless code : dead code*/
function DeadCode ( uint x ) public constant {
if ( x > 5)
if ( x*x < 20){
//Do someting : but this code will never be executed
}
}
/* Useless code : opaque predicate*/
function OpaquePredicate ( uint x ) public constant {
if ( x > 5)
if ( x > 1){ //opaque predicate
/*Do someting: the previous test is irrelevant, this code will always be executed or not
independently of the outcome of the previous test */
}
}
/*======================= LOOP RELATED PATTERNS ========================================================
/* Remix advise/warning:
If the gas requirement of a function is higher than the block gas limit, it cannot be executed.
Please avoid loops in your functions or actions that modify large areas of storage
(this includes clearing or copying arrays in storage)
/*======================================================================================================
Expensive operations in a loop.
-------------------------------
The variable sum is stored in the storage, The summation involves
==> a SLOAD for loading sumBad to the stack
==> a SSTORE for saving the outcome of the ADD to the storage.
Storage-related operations are very expensive.
An advanced compiler should assign sum to a local variable (e.g., tmp) that resides in the stack,
then add i to tmp inside the loop, and finally assign tmp to sum after the loop. Such optimization
reduces the storage-related operations from 2x to just 2, i.e., one SLOAD and one SSTORE.
======================================================================================================*/
uint public sumBad=0;
function loopBad () public returns ( uint ){
for ( uint i = 1 ; i <= 100 ; i++)
sumBad += i;
return sumBad;
}
function loopGood () public returns ( uint ){
uint sum=0;
for ( uint i = 1 ; i <= 100 ; i++)
sum += i;
return sum;
}
/*======================================================================================================
Constant outcome of a loop
-------------------------------
In some cases, the outcome of a loop may be a constant that can be inferred in compilation.
As shown in Fig.2 (Pattern 4), the storage variable sumBad equals to 5050 after the loop.
Hence, the body of p4 should be simplified as “return 5050;”.
======================================================================================================*/
function loop2Bad () public returns ( uint ){
uint sum = 0;
for ( uint i = 1 ; i <= 100 ; i++)
sum += i;
return sum;
}
function loop2Good () public returns ( uint ){
return 5050;
}
/*============================================================================================
Comparison with unilateral outcome in a loop
--------------------------------------------
Loop fusion. It combines several loops into one if possible and thus reduces the size of bytecode.
In particular, it can reduce the amount of operations, such as conditional jumps and comparison, etc.,
at the entry points of loops. The two loops shown hereunder can be combined into one loop,
where both m and v get updated.
============================================================================================*/
function LoopFusionBad( uint x ) public {
uint m = 0;
uint v = 0;
for ( uint i = 0 ; i < x ; i++)
m += i;
for ( uint j = 0 ; j < x ; j++)
v -= j;
}
function LoopFusionGood( uint x ) public {
uint m = 0;
uint v = 0;
for ( uint i = 0 ; i < x ; i++){
m += i;
v -= i;
}
}
/*============================================================================================
Repeated computations in a loop.
In some cases, there may be expressions that produce the same outcome in each
iteration of a loop. Hence, the gas can be saved by computing the outcome once and then
reusing the value instead of recomputing it in subsequent iterations, especially, for the
expressions involving expensive operands.
In this example, the gas consumption is very high due to the repeated computations.
More precisely, the summation of two storage words (i.e., “x+y”) is quite expensive because
x and y should be loaded into the stack (i.e., SLOAD) before addition. To save gas, this
summation should be finished before the loop, and then the result is reused within the loop
============================================================================================*/
uint x = 1;
uint y = 2;
function RepeatedComputationBad ( uint k ) public {
uint sum = 0;
for ( uint i = 1 ; i <= k ; i++)
sum = sum + x + y;
}
function RepeatedComputationGood( uint k ) public {
uint sum = 0;
uint delta = x+y;
for ( uint i = 1 ; i <= k ; i++)
sum = sum + delta;
}
/*=====================================================================================================
Comparison with unilateral outcome in a loop.
It means that a comparison is executed in each iteration of a loop but the result of the comparison is
the same even if it cannot be determined in compilation (i.e., not an opaque predicate :
The outcome of an opaque predicate is known to be true or false without execution).
For instance, in Fig.4, the comparison at Line 3 should be moved to the place before the loop.
======================================================================================================*/
function ComparisonBad ( uint xx , uint yy ) public returns ( uint ){
for ( int i = 0 ; i < 100 ; i++) {
if ( xx > 0 )
yy += xx;
}
return y;
}
function ComparisonGood ( uint xx , uint yy ) public returns ( uint ){
if ( xx > 0 )
for ( int i = 0 ; i < 100 ; i++) {
yy += xx;
}
return y;
}
} | Useless code : opaque predicate*/ | function OpaquePredicate ( uint x ) public constant {
if ( x > 5)
independently of the outcome of the previous test */
| 12,597,805 | [
1,
57,
1786,
403,
981,
294,
225,
22519,
5641,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
282,
445,
6066,
14886,
8634,
261,
2254,
619,
262,
1071,
5381,
288,
203,
1377,
309,
261,
619,
405,
1381,
13,
203,
2868,
14807,
715,
434,
326,
12884,
434,
326,
2416,
1842,
1195,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
interface IRadRouter is IERC721Receiver {
/**
* @dev Emitted when a retail revenue split is updated for asset ledger `ledger`
*/
event RetailRevenueSplitChange(address indexed ledger, address indexed stakeholder, uint256 share, uint256 totalStakeholders, uint256 totalSplit);
/**
* @dev Emitted when a resale revenue split is updated for asset ledger `ledger`
*/
event ResaleRevenueSplitChange(address indexed ledger, address indexed stakeholder, uint256 share, uint256 totalStakeholders, uint256 totalSplit);
/**
* @dev Emitted when the minimum price of asset `assetId` is updated
*/
event AssetMinPriceChange(address indexed ledger, uint256 indexed assetId, uint256 minPrice);
/**
* @dev Emitted when seller `seller` changes ownership for asset `assetId` in ledger `ledger` to or from this escrow. `escrowed` is true for deposits and false for withdrawals
*/
event SellerEscrowChange(address indexed ledger, uint256 indexed assetId, address indexed seller, bool escrowed);
/**
* @dev Emitted when buyer `buyer` deposits or withdraws ETH from this escrow for asset `assetId` in ledger `ledger`. `escrowed` is true for deposits and false for withdrawals
*/
event BuyerEscrowChange(address indexed ledger, uint256 indexed assetId, address indexed buyer, bool escrowed);
/**
* @dev Emitted when stakeholder `stakeholder` is paid out from a retail sale or resale
*/
event StakeholderPayout(address indexed ledger, uint256 indexed assetId, address indexed stakeholder, uint256 payout, uint256 share, bool retail);
/**
* @dev Emitted when buyer `buyer` deposits or withdraws ETH from this escrow for asset `assetId` in ledger `ledger`. `escrowed` is true for deposits and false for withdrawals
*/
event EscrowFulfill(address indexed ledger, uint256 indexed assetId, address seller, address buyer, uint256 value);
/**
* @dev Sets a stakeholder's revenue share for an asset ledger. If `retail` is true, sets retail revenue splits; otherwise sets resale revenue splits
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
* - `_stakeholder` cannot be the zero address.
* - `_share` must be >= 0 and <= 100
* - Revenue cannot be split more than 5 ways
*
* Emits a {RetailRevenueSplitChange|ResaleRevenueSplitChange} event.
*/
function setRevenueSplit(address _ledger, address payable _stakeholder, uint256 _share, bool _retail) external returns (bool success);
/**
* @dev Returns the revenue share of `_stakeholder` for ledger `_ledger`
*
* See {setRevenueSplit}
*/
function getRevenueSplit(address _ledger, address payable _stakeholder, bool _retail) external view returns (uint256 share);
/**
* @dev Sets multiple stakeholders' revenue shares for an asset ledger. Overwrites any existing revenue share. If `retail` is true, sets retail revenue splits; otherwise sets resale revenue splits
* See {setRevenueSplit}
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
* - `_stakeholders` cannot contain zero addresses.
* - `_shares` must be >= 0 and <= 100
* - Revenue cannot be split more than 5 ways
*
* Emits a {RetailRevenueSplitChange|ResaleRevenueSplitChange} event.
*/
function setRevenueSplits(address _ledger, address payable[] calldata _stakeholders, uint256[] calldata _shares, bool _retail) external returns (bool success);
/**
* @dev For ledger `_ledger`, returns retail revenue stakeholders if `_retail` is true, otherwise returns resale revenue stakeholders.
*/
function getRevenueStakeholders(address _ledger, bool _retail) external view returns (address[] memory stakeholders);
/**
* @dev Sets the minimum price for asset `_assetId`
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
* - `_owner` must first approve this contract as an operator for ledger `_ledger`
* - `_minPrice` is in wei
*
* Emits a {AssetMinPriceChange} event.
*/
function setAssetMinPrice(address _ledger, uint256 _assetId, uint256 _minPrice) external returns (bool success);
/**
* @dev Sets a stakeholder's revenue share for an asset ledger. If `retail` is true, sets retail revenue splits; otherwise sets resale revenue splits.
* Also sets the minimum price for asset `_assetId`
* See {setAssetMinPrice | setRevenueSplits}
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
* - `_stakeholder` cannot be the zero address.
* - `_share` must be > 0 and <= 100
* - Revenue cannot be split more than 5 ways
* - `_owner` must first approve this contract as an operator for ledger `_ledger`
* - `_minPrice` is in wei
*
* Emits a {RetailRevenueSplitChange|ResaleRevenueSplitChange} event.
*/
function setAssetMinPriceAndRevenueSplits(address _ledger, address payable[] calldata _stakeholders, uint256[] calldata _shares, bool _retail, uint256 _assetId, uint256 _minPrice) external returns (bool success);
/**
* @dev Returns the minium price of asset `_assetId` in ledger `_ledger`
*
* See {setAssetMinPrice}
*/
function getAssetMinPrice(address _ledger, uint256 _assetId) external view returns (uint256 minPrice);
/**
* @dev Transfers ownership of asset `_assetId` to this contract for escrow.
* If buyer has already escrowed, triggers escrow fulfillment.
* See {fulfill}
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
* - `_owner` must first approve this contract as an operator for ledger `_ledger`
*
* Emits a {SellerEscrowChange} event.
*/
function sellerEscrowDeposit(address _ledger, uint256 _assetId) external returns (bool success);
/**
* @dev Transfers ownership of asset `_assetId` to this contract for escrow.
* If buyer has already escrowed, triggers escrow fulfillment.
* See {fulfill}
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
* - `_owner` must first approve this contract as an operator for ledger `_ledger`
*
* Emits a {SellerEscrowChange} event.
*/
function sellerEscrowDepositWithCreatorShare(address _ledger, uint256 _assetId, uint256 _creatorResaleShare) external returns (bool success);
function sellerEscrowDepositWithCreatorShareBatch(address _ledger, uint256[] calldata _assetIds, uint256 _creatorResaleShare) external returns (bool success);
/**
* @dev Transfers ownership of asset `_assetId` to this contract for escrow.
* If buyer has already escrowed, triggers escrow fulfillment.
* See {fulfill}
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
* - `_owner` must first approve this contract as an operator for ledger `_ledger`
*
* Emits a {SellerEscrowChange} event.
*/
function sellerEscrowDepositWithCreatorShareWithMinPrice(address _ledger, uint256 _assetId, uint256 _creatorResaleShare, uint256 _minPrice) external returns (bool success);
function sellerEscrowDepositWithCreatorShareWithMinPriceBatch(address _ledger, uint256[] calldata _assetIds, uint256 _creatorResaleShare, uint256 _minPrice) external returns (bool success);
/**
* @dev Transfers ownership of asset `_assetId` to this contract for escrow.
* Sets asset min price to `_minPrice` if `_setMinPrice` is true. Reverts if `_setMinPrice` is true and buyer has already escrowed. Otherwise, if buyer has already escrowed, triggers escrow fulfillment.
* See {fulfill | setAssetMinPrice}
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
* - `_owner` must first approve this contract as an operator for ledger `_ledger`
* - `_minPrice` is in wei
*
* Emits a {SellerEscrowChange} event.
*/
function sellerEscrowDeposit(address _ledger, uint256 _assetId, bool _setMinPrice, uint256 _minPrice) external returns (bool success);
/**
* @dev Transfers ownership of all assets `_assetIds` to this contract for escrow.
* If any buyers have already escrowed, triggers escrow fulfillment for the respective asset.
* See {fulfill}
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
* - `_owner` must first approve this contract as an operator for ledger `_ledger`
*
* Emits a {SellerEscrowChange} event.
*/
function sellerEscrowDepositBatch(address _ledger, uint256[] calldata _assetIds) external returns (bool success);
/**
* @dev Transfers ownership of all assets `_assetIds` to this contract for escrow.
* Sets each asset min price to `_minPrice` if `_setMinPrice` is true. Reverts if `_setMinPrice` is true and buyer has already escrowed. Otherwise, if any buyers have already escrowed, triggers escrow fulfillment for the respective asset.
* See {fulfill | setAssetMinPrice}
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
* - `_owner` must first approve this contract as an operator for ledger `_ledger`
* - `_minPrice` is in wei
*
* Emits a {SellerEscrowChange} event.
*/
function sellerEscrowDepositBatch(address _ledger, uint256[] calldata _assetIds, bool _setMinPrice, uint256 _minPrice) external returns (bool success);
/**
* @dev Transfers ownership of asset `_assetId` from this contract for escrow back to seller.
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
*
* Emits a {SellerEscrowChange} event.
*/
function sellerEscrowWithdraw(address _ledger, uint256 _assetId) external returns (bool success);
/**
* @dev Accepts buyer's `msg.sender` funds into escrow for asset `_assetId` in ledger `_ledger`.
* If seller has already escrowed, triggers escrow fulfillment.
* See {fulfill}
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
* - `msg.value` must be at least the seller's listed price
* - `_assetId` in `ledger` cannot already have an escrowed buyer
*
* Emits a {BuyerEscrowChange} event.
*/
function buyerEscrowDeposit(address _ledger, uint256 _assetId) external payable returns (bool success);
/**
* @dev Returns buyer's `msg.sender` funds back from escrow for asset `_assetId` in ledger `_ledger`.
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
* - `msg.sender` must be the escrowed buyer for asset `_assetId` in ledger `_ledger`, asset owner, or Rad operator
*
* Emits a {BuyerEscrowChange} event.
*/
function buyerEscrowWithdraw(address _ledger, uint256 _assetId) external returns (bool success);
/**
* @dev Returns the wallet address of the seller of asset `_assetId`
*
* See {sellerEscrowDeposit}
*/
function getSellerWallet(address _ledger, uint256 _assetId) external view returns (address wallet);
/**
* @dev Returns the wallet address of the buyer of asset `_assetId`
*
* See {buyerEscrowDeposit}
*/
function getBuyerWallet(address _ledger, uint256 _assetId) external view returns (address wallet);
/**
* @dev Returns the escrowed `_assetId` by the seller of asset `_assetId`
*
* See {sellerEscrowDeposit}
*/
function getSellerDeposit(address _ledger, uint256 _assetId) external view returns (uint256 amount);
/**
* @dev Returns the escrowed amount by the buyer of asset `_assetId`
*
* See {buyerEscrowDeposit}
*/
function getBuyerDeposit(address _ledger, uint256 _assetId) external view returns (uint256 amount);
/**
* @dev Returns the wallet address of the creator of asset `_assetId`
*
* See {sellerEscrowDeposit}
*/
function getCreatorWallet(address _ledger, uint256 _assetId) external view returns (address wallet);
/**
* @dev Returns the amount of the creator's share of asset `_assetId`
*
* See {sellerEscrowDeposit}
*/
function getCreatorShare(address _ledger, uint256 _assetId) external view returns (uint256 amount);
/**
* @dev Returns true if an asset has been sold for retail and will be considered resale moving forward
*/
function getAssetIsResale(address _ledger, uint256 _assetId) external view returns (bool resale);
/**
* @dev Returns an array of all retailed asset IDs for ledger `_ledger`
*/
function getRetailedAssets(address _ledger) external view returns (uint256[] memory assets);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import './IRadRouter.sol';
import './RevenueSplitMapping.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import '@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol';
contract RadRouter is IRadRouter, ERC721Holder {
using RevenueSplitMapping for RevMap;
struct Ledger {
RevMap RetailSplits;
RevMap ResaleSplits;
mapping (uint256 => Asset) Assets;
uint256[] retailedAssets;
}
struct Asset {
address owner; // does not change on escrow, only through sale
uint256 minPrice;
bool resale;
Creator creator;
Buyer buyer;
}
struct Creator {
address wallet;
uint256 share;
}
struct Buyer {
address wallet;
uint256 amountEscrowed;
}
modifier onlyBy(address _account)
{
require(
msg.sender == _account,
'Sender not authorized'
);
_;
}
address public administrator_; // Rad administrator account
mapping(address => Ledger) private Ledgers;
/**
* @dev Initializes the contract and sets the router administrator `administrator_`
*/
constructor() { administrator_ = msg.sender; }
/**
* @dev See {IRadRouter-setRevenueSplit}.
*/
function setRevenueSplit(address _ledger, address payable _stakeholder, uint256 _share, bool _retail) public onlyBy(administrator_) virtual override returns (bool success) {
require(_ledger != address(0), 'Asset ledger cannot be the zero address');
require(_stakeholder != address(0), 'Stakeholder cannot be the zero address');
require(_share >= 0 && _share <= 100, 'Stakeholder share must be at least 0% and at most 100%');
uint256 total;
if (_retail) {
if (_share == 0) {
Ledgers[_ledger].RetailSplits.remove(_stakeholder);
emit RetailRevenueSplitChange(_ledger, _stakeholder, _share, Ledgers[_ledger].RetailSplits.size(), Ledgers[_ledger].RetailSplits.total);
return true;
}
if (Ledgers[_ledger].RetailSplits.contains(_stakeholder)) {
require(Ledgers[_ledger].RetailSplits.size() <= 5, 'Cannot split revenue more than 5 ways.');
total = Ledgers[_ledger].RetailSplits.total - Ledgers[_ledger].RetailSplits.get(_stakeholder);
} else {
require(Ledgers[_ledger].RetailSplits.size() < 5, 'Cannot split revenue more than 5 ways.');
total = Ledgers[_ledger].RetailSplits.total;
}
} else {
if (_share == 0) {
Ledgers[_ledger].ResaleSplits.remove(_stakeholder);
emit ResaleRevenueSplitChange(_ledger, _stakeholder, _share, Ledgers[_ledger].ResaleSplits.size(), Ledgers[_ledger].ResaleSplits.total);
return true;
}
if (Ledgers[_ledger].ResaleSplits.contains(_stakeholder)) {
require(Ledgers[_ledger].ResaleSplits.size() <= 5, 'Cannot split revenue more than 5 ways.');
total = Ledgers[_ledger].ResaleSplits.total - Ledgers[_ledger].RetailSplits.get(_stakeholder);
} else {
require(Ledgers[_ledger].ResaleSplits.size() < 5, 'Cannot split revenue more than 5 ways.');
total = Ledgers[_ledger].ResaleSplits.total;
}
}
require(_share + total <= 100, 'Total revenue split cannot exceed 100%');
if (_retail) {
Ledgers[_ledger].RetailSplits.set(_stakeholder, _share);
emit RetailRevenueSplitChange(_ledger, _stakeholder, _share, Ledgers[_ledger].RetailSplits.size(), Ledgers[_ledger].RetailSplits.total);
} else {
Ledgers[_ledger].ResaleSplits.set(_stakeholder, _share);
emit ResaleRevenueSplitChange(_ledger, _stakeholder, _share, Ledgers[_ledger].ResaleSplits.size(), Ledgers[_ledger].ResaleSplits.total);
}
success = true;
}
/**
* @dev See {IRadRouter-getRevenueSplit}.
*/
function getRevenueSplit(address _ledger, address payable _stakeholder, bool _retail) external view virtual override returns (uint256 share) {
if (_retail) {
share = Ledgers[_ledger].RetailSplits.get(_stakeholder);
} else {
share = Ledgers[_ledger].ResaleSplits.get(_stakeholder);
}
}
/**
* @dev See {IRadRouter-setRevenueSplits}.
*/
function setRevenueSplits(address _ledger, address payable[] calldata _stakeholders, uint256[] calldata _shares, bool _retail) public virtual override returns (bool success) {
require(_stakeholders.length == _shares.length, 'Stakeholders and shares must have equal length');
require(_stakeholders.length <= 5, 'Cannot split revenue more than 5 ways.');
if (_retail) {
Ledgers[_ledger].RetailSplits.clear();
} else {
Ledgers[_ledger].ResaleSplits.clear();
}
for (uint256 i = 0; i < _stakeholders.length; i++) {
setRevenueSplit(_ledger, _stakeholders[i], _shares[i], _retail);
}
success = true;
}
function getRevenueStakeholders(address _ledger, bool _retail) external view virtual override returns (address[] memory stakeholders) {
if (_retail) {
stakeholders = Ledgers[_ledger].RetailSplits.keys;
} else {
stakeholders = Ledgers[_ledger].ResaleSplits.keys;
}
}
/**
* @dev See {IRadRouter-setAssetMinPrice}.
*/
function setAssetMinPrice(address _ledger, uint256 _assetId, uint256 _minPrice) public virtual override returns (bool success) {
require(_ledger != address(0), 'Asset ledger cannot be the zero address');
IERC721 ledger = IERC721(_ledger);
address owner = ledger.ownerOf(_assetId);
require(msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can set the asset minimum price');
require(owner == address(this) || ledger.isApprovedForAll(owner, address(this)) || ledger.getApproved(_assetId) == address(this), 'Must approve Rad Router as an operator before setting minimum price.');
Ledgers[_ledger].Assets[_assetId].owner = owner;
Ledgers[_ledger].Assets[_assetId].minPrice = _minPrice;
emit AssetMinPriceChange(_ledger, _assetId, _minPrice);
success = true;
}
/**
* @dev See {IRadRouter-getAssetMinPrice}.
*/
function getAssetMinPrice(address _ledger, uint256 _assetId) external view virtual override returns (uint256 minPrice) {
minPrice = Ledgers[_ledger].Assets[_assetId].minPrice;
}
/**
* @dev See {IRadRouter-setAssetMinPriceAndRevenueSplits}.
*/
function setAssetMinPriceAndRevenueSplits(address _ledger, address payable[] calldata _stakeholders, uint256[] calldata _shares, bool _retail, uint256 _assetId, uint256 _minPrice) public virtual override returns (bool success) {
success = setRevenueSplits(_ledger, _stakeholders, _shares, _retail) && setAssetMinPrice(_ledger, _assetId, _minPrice);
}
/**
* @dev See {IRadRouter-sellerEscrowDeposit}.
*/
function sellerEscrowDeposit(address _ledger, uint256 _assetId) public virtual override returns (bool success) {
success = sellerEscrowDeposit(_ledger, _assetId, false, 0);
}
/**
* @dev See {IRadRouter-sellerEscrowDepositWithCreatorShare}.
*/
function sellerEscrowDepositWithCreatorShare(address _ledger, uint256 _assetId, uint256 _creatorResaleShare) public virtual override returns (bool success) {
require(_ledger != address(0), 'Asset ledger cannot be the zero address');
require(_creatorResaleShare >= 0 && _creatorResaleShare <= 100, 'Creator share must be at least 0% and at most 100%');
IERC721 ledger = IERC721(_ledger);
address owner = ledger.ownerOf(_assetId);
require(
msg.sender == owner ||
msg.sender == administrator_,
'Only the asset owner or Rad administrator can change asset ownership'
);
require(
ledger.isApprovedForAll(owner, address(this)) ||
ledger.getApproved(_assetId) == address(this),
'Must set Rad Router as an operator for all assets before depositing to escrow.'
);
if (
Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0) ||
Ledgers[_ledger].Assets[_assetId].creator.wallet == owner ||
Ledgers[_ledger].Assets[_assetId].owner == owner
) {
if (Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0)) {
Ledgers[_ledger].Assets[_assetId].creator.wallet = owner;
}
require(
Ledgers[_ledger].Assets[_assetId].creator.wallet == owner ||
Ledgers[_ledger].Assets[_assetId].creator.share == 0 ||
Ledgers[_ledger].Assets[_assetId].owner == owner,
'Cannot set creator share.'
);
uint256 total = Ledgers[_ledger].Assets[_assetId].creator.share;
address[] storage stakeholders = Ledgers[_ledger].ResaleSplits.keys;
for (uint256 i = 0; i < stakeholders.length; i++) {
total += Ledgers[_ledger].ResaleSplits.get(stakeholders[i]);
}
require(total <= 100, 'Creator share cannot exceed total ledger stakeholder when it is 100.');
Ledgers[_ledger].Assets[_assetId].creator.share = _creatorResaleShare;
}
success = sellerEscrowDeposit(_ledger, _assetId, false, 0);
}
/**
* @dev See {IRadRouter-sellerEscrowDepositWithCreatorShareBatch}.
*/
function sellerEscrowDepositWithCreatorShareBatch(address _ledger, uint256[] calldata _assetIds, uint256 _creatorResaleShare) public virtual override returns (bool success) {
success = false;
for (uint256 i = 0; i < _assetIds.length; i++) {
if (!sellerEscrowDepositWithCreatorShare(_ledger, _assetIds[i], _creatorResaleShare)) {
success = false;
break;
} else {
success = true;
}
}
}
/**
* @dev See {IRadRouter-sellerEscrowDepositWithCreatorShareWithMinPrice}.
*/
function sellerEscrowDepositWithCreatorShareWithMinPrice(address _ledger, uint256 _assetId, uint256 _creatorResaleShare, uint256 _minPrice) public virtual override returns (bool success) {
require(_ledger != address(0), 'Asset ledger cannot be the zero address');
require(_creatorResaleShare >= 0 && _creatorResaleShare <= 100, 'Creator share must be at least 0% and at most 100%');
IERC721 ledger = IERC721(_ledger);
address owner = ledger.ownerOf(_assetId);
require(
msg.sender == owner ||
msg.sender == administrator_,
'Only the asset owner or Rad administrator can change asset ownership'
);
require(
ledger.isApprovedForAll(owner, address(this)) ||
ledger.getApproved(_assetId) == address(this),
'Must set Rad Router as an operator for all assets before depositing to escrow.'
);
if (
Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0) ||
Ledgers[_ledger].Assets[_assetId].creator.wallet == owner ||
Ledgers[_ledger].Assets[_assetId].owner == owner
) {
if (Ledgers[_ledger].Assets[_assetId].creator.wallet == address(0)) {
Ledgers[_ledger].Assets[_assetId].creator.wallet = owner;
}
require(
Ledgers[_ledger].Assets[_assetId].creator.wallet == owner ||
Ledgers[_ledger].Assets[_assetId].creator.share == 0 ||
Ledgers[_ledger].Assets[_assetId].owner == owner,
'Cannot set creator share.'
);
uint256 total = Ledgers[_ledger].Assets[_assetId].creator.share;
address[] storage stakeholders = Ledgers[_ledger].ResaleSplits.keys;
for (uint256 i = 0; i < stakeholders.length; i++) {
total += Ledgers[_ledger].ResaleSplits.get(stakeholders[i]);
}
require(total <= 100, 'Creator share cannot exceed total ledger stakeholder when it is 100.');
Ledgers[_ledger].Assets[_assetId].creator.share = _creatorResaleShare;
}
success = sellerEscrowDeposit(_ledger, _assetId, true, _minPrice);
}
/**
* @dev See {IRadRouter-sellerEscrowDepositWithCreatorShareWithMinPriceBatch}.
*/
function sellerEscrowDepositWithCreatorShareWithMinPriceBatch(address _ledger, uint256[] calldata _assetIds, uint256 _creatorResaleShare, uint256 _minPrice) public virtual override returns (bool success) {
success = false;
for (uint256 i = 0; i < _assetIds.length; i++) {
if (!sellerEscrowDepositWithCreatorShareWithMinPrice(_ledger, _assetIds[i], _creatorResaleShare, _minPrice)) {
success = false;
break;
} else {
success = true;
}
}
}
/**
* @dev See {IRadRouter-sellerEscrowDeposit}.
*/
function sellerEscrowDeposit(address _ledger, uint256 _assetId, bool _setMinPrice, uint256 _minPrice) public virtual override returns (bool success) {
require(_ledger != address(0), 'Asset ledger cannot be the zero address');
IERC721 ledger = IERC721(_ledger);
address owner = ledger.ownerOf(_assetId);
require(msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can change asset ownership');
require(ledger.isApprovedForAll(owner, address(this)) || ledger.getApproved(_assetId) == address(this), 'Must set Rad Router as an operator for all assets before depositing to escrow');
if (_setMinPrice) {
setAssetMinPrice(_ledger, _assetId, _minPrice);
}
Ledgers[_ledger].Assets[_assetId].owner = owner;
ledger.safeTransferFrom(owner, address(this), _assetId);
if (Ledgers[_ledger].Assets[_assetId].buyer.wallet != address(0)) {
_fulfill(_ledger, _assetId);
}
emit SellerEscrowChange(_ledger, _assetId, owner, true);
success = true;
}
/**
* @dev See {IRadRouter-sellerEscrowDepositBatch}.
*/
function sellerEscrowDepositBatch(address _ledger, uint256[] calldata _assetIds) external virtual override returns (bool success) {
success = sellerEscrowDepositBatch(_ledger, _assetIds, false, 0);
}
/**
* @dev See {IRadRouter-sellerEscrowDepositBatch}.
*/
function sellerEscrowDepositBatch(address _ledger, uint256[] calldata _assetIds, bool _setMinPrice, uint256 _minPrice) public virtual override returns (bool success) {
for (uint256 i = 0; i < _assetIds.length; i++) {
sellerEscrowDeposit(_ledger, _assetIds[i], _setMinPrice, _minPrice);
}
success = true;
}
/**
* @dev See {IRadRouter-sellerEscrowWithdraw}.
*/
function sellerEscrowWithdraw(address _ledger, uint256 _assetId) external virtual override returns (bool success) {
require(_ledger != address(0), 'Asset ledger cannot be the zero address');
IERC721 ledger = IERC721(_ledger);
address owner = Ledgers[_ledger].Assets[_assetId].owner;
require(msg.sender == owner || msg.sender == administrator_, 'Only the asset owner or Rad administrator can change asset ownership');
require(ledger.isApprovedForAll(owner, address(this)), 'Must set Rad Router as an operator for all assets before depositing to escrow');
Ledgers[_ledger].Assets[_assetId].creator.wallet = address(0);
Ledgers[_ledger].Assets[_assetId].creator.share = 0;
ledger.safeTransferFrom(address(this), owner, _assetId);
emit SellerEscrowChange(_ledger, _assetId, owner, false);
success = true;
}
/**
* @dev See {IRadRouter-buyerEscrowDeposit}.
*/
function buyerEscrowDeposit(address _ledger, uint256 _assetId) external payable virtual override returns (bool success) {
require(_ledger != address(0), 'Asset ledger cannot be the zero address');
require(
Ledgers[_ledger].Assets[_assetId].buyer.wallet == address(0) ||
Ledgers[_ledger].Assets[_assetId].buyer.wallet == msg.sender,
'Another buyer has already escrowed'
);
require(
Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed + msg.value >= Ledgers[_ledger].Assets[_assetId].minPrice,
'Buyer did not send enough ETH'
);
Ledgers[_ledger].Assets[_assetId].buyer.wallet = msg.sender;
Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed += msg.value;
IERC721 ledger = IERC721(_ledger);
if (ledger.ownerOf(_assetId) == address(this)) {
_fulfill(_ledger, _assetId);
}
emit BuyerEscrowChange(_ledger, _assetId, msg.sender, true);
success = true;
}
/**
* @dev See {IRadRouter-buyerEscrowWithdraw}.
*/
function buyerEscrowWithdraw(address _ledger, uint256 _assetId) external virtual override returns (bool success) {
require(_ledger != address(0), 'Asset ledger cannot be the zero address');
require(
msg.sender == Ledgers[_ledger].Assets[_assetId].buyer.wallet ||
msg.sender == Ledgers[_ledger].Assets[_assetId].owner ||
msg.sender == administrator_,
'msg.sender must be the buyer, seller, or Rad operator'
);
payable(Ledgers[_ledger].Assets[_assetId].buyer.wallet).transfer(Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed);
Ledgers[_ledger].Assets[_assetId].buyer.wallet = address(0);
Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed = 0;
emit BuyerEscrowChange(_ledger, _assetId, msg.sender, false);
success = true;
}
/**
* @dev See {IRadRouter-getSellerWallet}.
*/
function getSellerWallet(address _ledger, uint256 _assetId) public view override returns (address wallet) {
if (Ledgers[_ledger].Assets[_assetId].owner == address(0)) {
require(_ledger != address(0), 'Asset ledger cannot be the zero address');
IERC721 ledger = IERC721(_ledger);
wallet = ledger.ownerOf(_assetId);
} else {
wallet = Ledgers[_ledger].Assets[_assetId].owner;
}
}
/**
* @dev See {IRadRouter-getSellerWallet}.
*/
function getSellerDeposit(address _ledger, uint256 _assetId) public view override returns (uint256 amount) {
require(_ledger != address(0), 'Asset ledger cannot be the zero address');
IERC721 ledger = IERC721(_ledger);
address owner = ledger.ownerOf(_assetId);
if (owner == address(this)) {
return _assetId;
}
return 0;
}
/**
* @dev See {IRadRouter-getBuyerWallet}.
*/
function getBuyerWallet(address _ledger, uint256 _assetId) public view override returns (address wallet) {
wallet = Ledgers[_ledger].Assets[_assetId].buyer.wallet;
}
/**
* @dev See {IRadRouter-getBuyerDeposit}.
*/
function getBuyerDeposit(address _ledger, uint256 _assetId) public view override returns (uint256 amount) {
amount = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed;
}
/**
* @dev See {IRadRouter-getAssetIsResale}.
*/
function getAssetIsResale(address _ledger, uint256 _assetId) public view override returns (bool resale) {
resale = Ledgers[_ledger].Assets[_assetId].resale;
}
/**
* @dev See {IRadRouter-getRetailedAssets}.
*/
function getRetailedAssets(address _ledger) public view override returns (uint256[] memory assets) {
assets = Ledgers[_ledger].retailedAssets;
}
/**
* @dev See {IRadRouter-getCreatorWallet}.
*/
function getCreatorWallet(address _ledger, uint256 _assetId) public view override returns (address wallet) {
wallet = Ledgers[_ledger].Assets[_assetId].creator.wallet;
}
/**
* @dev See {IRadRouter-getCreatorShare}.
*/
function getCreatorShare(address _ledger, uint256 _assetId) public view override returns (uint256 amount) {
amount = Ledgers[_ledger].Assets[_assetId].creator.share;
}
/**
* @dev Fulfills asset sale transaction and pays out all revenue split stakeholders
*
* Requirements:
*
* - `_ledger` cannot be the zero address.
* - `_assetId` owner must be this contract
* - `_assetId` buyer must not be the zero address
*
* Emits a {EscrowFulfill} event.
*/
function _fulfill(address _ledger, uint256 _assetId) internal virtual returns (bool success) {
IERC721 ledger = IERC721(_ledger);
require(
ledger.ownerOf(_assetId) == address(this),
'Seller has not escrowed'
);
require(
Ledgers[_ledger].Assets[_assetId].buyer.wallet != address(0),
'Buyer has not escrowed'
);
require(
Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed >= Ledgers[_ledger].Assets[_assetId].minPrice,
'Buyer escrow amount is less than asset min price'
);
ledger.safeTransferFrom(
address(this),
Ledgers[_ledger].Assets[_assetId].buyer.wallet,
_assetId
);
if (!Ledgers[_ledger].Assets[_assetId].resale) {
if (Ledgers[_ledger].RetailSplits.size() > 0) {
uint256 totalShareSplit = 0;
for (uint256 i = 0; i < Ledgers[_ledger].RetailSplits.size(); i++) {
address stakeholder = Ledgers[_ledger].RetailSplits.getKeyAtIndex(i);
uint256 share = Ledgers[_ledger].RetailSplits.get(stakeholder);
if (totalShareSplit + share > 100) {
share = totalShareSplit + share - 100;
}
uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * share / 100;
payable(stakeholder).transfer(payout);
emit StakeholderPayout(_ledger, _assetId, stakeholder, payout, share, true);
totalShareSplit += share;
// ignore other share stake holders if total max split has been reached
if (totalShareSplit >= 100) {
break;
}
}
if (totalShareSplit < 100) {
uint256 remainingShare = 100 - totalShareSplit;
uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * remainingShare / 100;
payable(Ledgers[_ledger].Assets[_assetId].owner).transfer(payout);
emit StakeholderPayout(_ledger, _assetId, Ledgers[_ledger].Assets[_assetId].owner, payout, remainingShare, true);
}
} else { // if no revenue split is defined, send all to asset owner
uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed;
payable(Ledgers[_ledger].Assets[_assetId].owner).transfer(payout);
emit StakeholderPayout(_ledger, _assetId, Ledgers[_ledger].Assets[_assetId].owner, payout, 100, true);
}
Ledgers[_ledger].Assets[_assetId].resale = true;
Ledgers[_ledger].retailedAssets.push(_assetId);
} else {
uint256 totalShareSplit = 0;
if (
Ledgers[_ledger].Assets[_assetId].creator.share > 0 &&
Ledgers[_ledger].Assets[_assetId].creator.wallet != address(0)
) {
uint256 creatorPayout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * Ledgers[_ledger].Assets[_assetId].creator.share / 100;
if (creatorPayout > 0) {
totalShareSplit = Ledgers[_ledger].Assets[_assetId].creator.share;
payable(Ledgers[_ledger].Assets[_assetId].creator.wallet).transfer(creatorPayout);
}
emit StakeholderPayout(
_ledger,
_assetId,
Ledgers[_ledger].Assets[_assetId].creator.wallet,
creatorPayout,
Ledgers[_ledger].Assets[_assetId].creator.share,
false);
}
if (Ledgers[_ledger].ResaleSplits.size() > 0) {
for (uint256 i = 0; i < Ledgers[_ledger].ResaleSplits.size(); i++) {
address stakeholder = Ledgers[_ledger].ResaleSplits.getKeyAtIndex(i);
uint256 share = Ledgers[_ledger].ResaleSplits.get(stakeholder) - (Ledgers[_ledger].Assets[_assetId].creator.share / 100);
if (totalShareSplit + share > 100) {
share = totalShareSplit + share - 100;
}
uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * share / 100;
payable(stakeholder).transfer(payout);
emit StakeholderPayout(_ledger, _assetId, stakeholder, payout, share, false);
totalShareSplit += share;
// ignore other share stake holders if total max split has been reached
if (totalShareSplit >= 100) {
break;
}
}
if (totalShareSplit < 100) {
uint256 remainingShare = 100 - totalShareSplit;
uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * remainingShare / 100;
payable(Ledgers[_ledger].Assets[_assetId].owner).transfer(payout);
emit StakeholderPayout(_ledger, _assetId, Ledgers[_ledger].Assets[_assetId].owner, payout, remainingShare, false);
}
} else { // if no revenue split is defined, send all to asset owner
uint256 remainingShare = 100 - totalShareSplit;
uint256 payout = Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed * remainingShare / 100;
payable(Ledgers[_ledger].Assets[_assetId].owner).transfer(payout);
emit StakeholderPayout(_ledger, _assetId, Ledgers[_ledger].Assets[_assetId].owner, payout, remainingShare, false);
}
}
emit EscrowFulfill(
_ledger,
_assetId,
Ledgers[_ledger].Assets[_assetId].owner,
Ledgers[_ledger].Assets[_assetId].buyer.wallet,
Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed
);
Ledgers[_ledger].Assets[_assetId].owner = Ledgers[_ledger].Assets[_assetId].buyer.wallet;
Ledgers[_ledger].Assets[_assetId].minPrice = 0;
Ledgers[_ledger].Assets[_assetId].buyer.wallet = address(0);
Ledgers[_ledger].Assets[_assetId].buyer.amountEscrowed = 0;
success = true;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.6.8 <0.9.0;
struct RevMap {
address[] keys;
uint256 total;
mapping(address => IndexValue) values;
}
struct IndexValue {
uint256 value;
uint256 indexOf;
bool inserted;
}
// https://solidity-by-example.org/app/iterable-mapping/
library RevenueSplitMapping {
function get(RevMap storage map, address key) external view returns (uint256) {
return map.values[key].value;
}
function getKeyAtIndex(RevMap storage map, uint256 index) external view returns (address) {
return map.keys[index];
}
function size(RevMap storage map) external view returns (uint256) {
return map.keys.length;
}
function set(RevMap storage map, address key, uint256 val) external {
if (map.values[key].inserted) {
map.total-=map.values[key].value;
map.values[key].value = val;
map.total+=val;
} else {
map.values[key].inserted = true;
map.values[key].value = val;
map.total+=val;
map.values[key].indexOf = map.keys.length;
map.keys.push(key);
}
}
function remove(RevMap storage map, address key) external {
if (!map.values[key].inserted) {
return;
}
map.total-=map.values[key].value;
uint256 index = map.values[key].indexOf;
uint256 lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.values[lastKey].indexOf = index;
delete map.values[key];
map.keys[index] = lastKey;
map.keys.pop();
}
function contains(RevMap storage map, address key) external view returns(bool) {
return map.values[key].inserted;
}
function clear(RevMap storage map) external {
for (uint256 i = 0; i < map.keys.length; i++) {
delete map.values[map.keys[i]];
}
delete map.keys;
map.total = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// 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);
}
| * @dev See {IRadRouter-sellerEscrowDepositWithCreatorShareWithMinPriceBatch}./ | function sellerEscrowDepositWithCreatorShareWithMinPriceBatch(address _ledger, uint256[] calldata _assetIds, uint256 _creatorResaleShare, uint256 _minPrice) public virtual override returns (bool success) {
success = false;
for (uint256 i = 0; i < _assetIds.length; i++) {
if (!sellerEscrowDepositWithCreatorShareWithMinPrice(_ledger, _assetIds[i], _creatorResaleShare, _minPrice)) {
success = false;
break;
success = true;
}
}
}
| 1,269,340 | [
1,
9704,
288,
45,
6621,
8259,
17,
1786,
749,
6412,
492,
758,
1724,
1190,
10636,
9535,
1190,
2930,
5147,
4497,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
29804,
6412,
492,
758,
1724,
1190,
10636,
9535,
1190,
2930,
5147,
4497,
12,
2867,
389,
1259,
693,
16,
2254,
5034,
8526,
745,
892,
389,
9406,
2673,
16,
2254,
5034,
389,
20394,
607,
5349,
9535,
16,
2254,
5034,
389,
1154,
5147,
13,
1071,
5024,
3849,
1135,
261,
6430,
2216,
13,
288,
203,
565,
2216,
273,
629,
31,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
9406,
2673,
18,
2469,
31,
277,
27245,
288,
203,
1377,
309,
16051,
1786,
749,
6412,
492,
758,
1724,
1190,
10636,
9535,
1190,
2930,
5147,
24899,
1259,
693,
16,
389,
9406,
2673,
63,
77,
6487,
389,
20394,
607,
5349,
9535,
16,
389,
1154,
5147,
3719,
288,
203,
3639,
2216,
273,
629,
31,
203,
3639,
898,
31,
203,
3639,
2216,
273,
638,
31,
203,
1377,
289,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/97/0xf6d94f597Aa4807E4A94E8121De10f45f31803d2/sources/PikaToken.sol | return getBalance()+999; | return balanceOf;
| 11,393,686 | [
1,
2463,
2882,
6112,
1435,
15,
11984,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
327,
11013,
951,
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,
-100
] |
/*
website: cityswap.io
██╗ █████╗ ██╗ ██╗ █████╗ ██████╗ ████████╗ █████╗ ██████╗██╗████████╗██╗ ██╗
██║██╔══██╗██║ ██╔╝██╔══██╗██╔══██╗╚══██╔══╝██╔══██╗ ██╔════╝██║╚══██╔══╝╚██╗ ██╔╝
██║███████║█████╔╝ ███████║██████╔╝ ██║ ███████║ ██║ ██║ ██║ ╚████╔╝
██ ██║██╔══██║██╔═██╗ ██╔══██║██╔══██╗ ██║ ██╔══██║ ██║ ██║ ██║ ╚██╔╝
╚█████╔╝██║ ██║██║ ██╗██║ ██║██║ ██║ ██║ ██║ ██║ ╚██████╗██║ ██║ ██║
╚════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═╝
*/
pragma solidity ^0.6.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev 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;
}
}
/**
* @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 { }
}
// CityToken with Governance.
contract JakartaCityToken is ERC20("JAKARTA.cityswap.io", "JAKARTA"), Ownable {
uint256 public constant MAX_SUPPLY = 9498000 * 10**18;
/**
* @notice Creates `_amount` token to `_to`. Must only be called by the owner (TravelAgency).
*/
function mint(address _to, uint256 _amount) public onlyOwner {
uint256 _totalSupply = totalSupply();
if(_totalSupply.add(_amount) > MAX_SUPPLY) {
_amount = MAX_SUPPLY.sub(_totalSupply);
}
require(_totalSupply.add(_amount) <= MAX_SUPPLY);
_mint(_to, _amount);
}
}
contract JakartaAgency is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of CITYs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCityPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accCityPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. CITYs to distribute per block.
uint256 lastRewardBlock; // Last block number that CITYs distribution occurs.
uint256 accCityPerShare; // Accumulated CITYs per share, times 1e12. See below.
}
// The CITY TOKEN!
JakartaCityToken public city;
// Dev address.
address public devaddr;
// Block number when bonus CITY period ends.
uint256 public bonusEndBlock;
// CITY tokens created per block.
uint256 public cityPerBlock;
// Bonus muliplier for early city travels.
uint256 public constant BONUS_MULTIPLIER = 1; // no bonus
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when CITY mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
JakartaCityToken _city,
address _devaddr,
uint256 _cityPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
city = _city;
devaddr = _devaddr;
cityPerBlock = _cityPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCityPerShare: 0
}));
}
// Update the given pool's CITY allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending CITYs on frontend.
function pendingCity(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCityPerShare = pool.accCityPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cityReward = multiplier.mul(cityPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accCityPerShare = accCityPerShare.add(cityReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accCityPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function mint(uint256 amount) public onlyOwner{
city.mint(devaddr, amount);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cityReward = multiplier.mul(cityPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
city.mint(devaddr, cityReward.div(20)); // 5%
city.mint(address(this), cityReward);
pool.accCityPerShare = pool.accCityPerShare.add(cityReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to TravelAgency for CITY allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accCityPerShare).div(1e12).sub(user.rewardDebt);
safeCityTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accCityPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accCityPerShare).div(1e12).sub(user.rewardDebt);
safeCityTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accCityPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe city transfer function, just in case if rounding error causes pool to not have enough CITYs.
function safeCityTransfer(address _to, uint256 _amount) internal {
uint256 cityBal = city.balanceOf(address(this));
if (_amount > cityBal) {
city.transfer(_to, cityBal);
} else {
city.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | CityToken with Governance. | contract JakartaCityToken is ERC20("JAKARTA.cityswap.io", "JAKARTA"), Ownable {
uint256 public constant MAX_SUPPLY = 9498000 * 10**18;
function mint(address _to, uint256 _amount) public onlyOwner {
uint256 _totalSupply = totalSupply();
if(_totalSupply.add(_amount) > MAX_SUPPLY) {
_amount = MAX_SUPPLY.sub(_totalSupply);
}
require(_totalSupply.add(_amount) <= MAX_SUPPLY);
_mint(_to, _amount);
}
function mint(address _to, uint256 _amount) public onlyOwner {
uint256 _totalSupply = totalSupply();
if(_totalSupply.add(_amount) > MAX_SUPPLY) {
_amount = MAX_SUPPLY.sub(_totalSupply);
}
require(_totalSupply.add(_amount) <= MAX_SUPPLY);
_mint(_to, _amount);
}
}
| 13,612,555 | [
1,
22236,
1345,
598,
611,
1643,
82,
1359,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
804,
581,
485,
69,
22236,
1345,
353,
4232,
39,
3462,
2932,
46,
14607,
4928,
37,
18,
14240,
22270,
18,
1594,
3113,
315,
46,
14607,
4928,
37,
6,
3631,
14223,
6914,
288,
203,
377,
203,
565,
2254,
5034,
1071,
5381,
4552,
67,
13272,
23893,
273,
2468,
7616,
26021,
380,
1728,
636,
2643,
31,
203,
540,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
2254,
5034,
389,
4963,
3088,
1283,
273,
2078,
3088,
1283,
5621,
203,
540,
203,
3639,
309,
24899,
4963,
3088,
1283,
18,
1289,
24899,
8949,
13,
405,
4552,
67,
13272,
23893,
13,
288,
203,
5411,
389,
8949,
273,
4552,
67,
13272,
23893,
18,
1717,
24899,
4963,
3088,
1283,
1769,
203,
3639,
289,
203,
203,
3639,
2583,
24899,
4963,
3088,
1283,
18,
1289,
24899,
8949,
13,
1648,
4552,
67,
13272,
23893,
1769,
203,
540,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
565,
289,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
2254,
5034,
389,
4963,
3088,
1283,
273,
2078,
3088,
1283,
5621,
203,
540,
203,
3639,
309,
24899,
4963,
3088,
1283,
18,
1289,
24899,
8949,
13,
405,
4552,
67,
13272,
23893,
13,
288,
203,
5411,
389,
8949,
273,
4552,
67,
13272,
23893,
18,
1717,
24899,
4963,
3088,
1283,
1769,
203,
3639,
289,
203,
203,
3639,
2583,
24899,
4963,
3088,
1283,
18,
1289,
24899,
8949,
13,
1648,
4552,
67,
13272,
23893,
1769,
203,
2
] |
./full_match/1/0xFd69464919Fe344b68d2292823aB989193d01C06/sources/PreachersCompFiLqdt.sol | ************************************************************************************* Preacher's Method II 1. Obtain Flash Loan in USDC from dYdX in the amount of equal value in the liquidation amount. 2. If the liquidate token is cUSDC, skip to step (3). Otherwise, swap (Kyber) the USDC for an equal value of the liquidate tokens. 3. Pay down the liquidate amount, liquidateBorrow(). CompFi will award an equal value from the unsafe account's collateral + incentive reward. 4. Swap the received collateral tokens for USDC. 5. Repay the flash loan with the USDC. 6. Transfer what is left of the USDC to the Msg.sender./ Decode the parameters in "calldata" as passed by doCompFiLiquidate. function approve(address _spender, uint256 _value) public returns (bool success) Step 2. Swap USDC for targetToken | function callFunction(
address, /* sender */
Info calldata, /* accountInfo */
bytes calldata data
) external onlyPool {
(address flashToken,
uint256 flashAmount,
uint256 balanceBefore,
address targetAccount,
address targetToken,
uint256 liquidateAmmount,
address collateralToken) =
abi.decode(data, (address, uint256, uint256, address, address,
uint256, address));
ERC20 cFlashToken = ERC20(flashToken);
require(cFlashToken.balanceOf(address(this)) - balanceBefore >=
flashAmount ,"contract did not get the loan");
emit Borrowed(flashToken, cFlashToken.balanceOf(address(this)));
require(underlying.approve(address(cFlashToken), flashAmount) == true,
ERC20 cTargetToken = ERC20(targetToken);
if (targetToken != kcUSDC) {
require( executeKyberSwap(cFlashToken, flashAmount,
cTargetToken, payable(address(this)),
liquidateAmmount) > 0, "02 First Token swap failed");
}
require(cTargetToken.approve(address(this), liquidateAmmount) == true,
"02 approval failed.");
address[] memory cTokens = new address[](1);
cTokens[0] = targetToken;
uint[] memory ERRORS = ctroll.enterMarkets(cTokens);
if (ERRORS[0] != 0) {
revert("01 Comptroller enter Markets for target token failed. ");
}
if (targetToken == kcETH){
c_or_w_ETH ceTargetToken = c_or_w_ETH(targetToken);
(targetAccount, collateralToken);
cTargetToken.liquidateBorrow(targetAccount, flashAmount, collateralToken);
}
require(ctroll.exitMarket(targetToken) == 0,
"Exit Market of target token failed. ");
ERRORS = ctroll.enterMarkets(cTokens);
require(ERRORS[0] == 0, "02 Comptroller.enter Markets for collateral Token failed.");
ERC20 cCollateralToken = ERC20(collateralToken);
require(cCollateralToken.approve(address(this), liquidateAmmount) == true,
"03 Collateral Token approval failed.");
if (collateralToken != kcUSDC) {
require( executeKyberSwap(cCollateralToken,
cCollateralToken.balanceOf(address(this)),
cTargetToken, payable(address(this)),
899999999999999999) > 0, "02 First Token swap failed");
}
| 3,177,526 | [
1,
1386,
27779,
1807,
2985,
23076,
404,
18,
24850,
15014,
3176,
304,
316,
11836,
5528,
628,
302,
61,
72,
60,
316,
326,
3844,
434,
3959,
460,
316,
326,
4501,
26595,
367,
3844,
18,
576,
18,
971,
326,
4501,
26595,
340,
1147,
353,
276,
3378,
5528,
16,
2488,
358,
2235,
261,
23,
2934,
5272,
16,
7720,
261,
47,
93,
744,
13,
326,
11836,
5528,
364,
392,
3959,
460,
434,
326,
4501,
26595,
340,
2430,
18,
890,
18,
13838,
2588,
326,
4501,
26595,
340,
3844,
16,
4501,
26595,
340,
38,
15318,
7675,
5427,
42,
77,
903,
279,
2913,
392,
3959,
460,
628,
326,
7127,
2236,
1807,
4508,
2045,
287,
397,
316,
2998,
688,
19890,
18,
1059,
18,
12738,
326,
5079,
4508,
2045,
287,
2430,
364,
11836,
5528,
18,
1381,
18,
868,
10239,
326,
9563,
28183,
598,
326,
11836,
5528,
18,
1666,
18,
12279,
4121,
353,
2002,
434,
326,
11836,
5528,
358,
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,
745,
2083,
12,
203,
3639,
1758,
16,
1748,
5793,
1195,
203,
3639,
3807,
745,
892,
16,
1748,
2236,
966,
1195,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
3903,
1338,
2864,
288,
203,
202,
203,
3639,
261,
2867,
9563,
1345,
16,
7010,
3639,
2254,
5034,
9563,
6275,
16,
7010,
3639,
2254,
5034,
11013,
4649,
16,
203,
3639,
1758,
1018,
3032,
16,
7010,
3639,
1758,
1018,
1345,
16,
7010,
3639,
2254,
5034,
4501,
26595,
340,
9864,
4778,
16,
203,
3639,
1758,
4508,
2045,
287,
1345,
13,
273,
7010,
1082,
202,
21457,
18,
3922,
12,
892,
16,
261,
2867,
16,
2254,
5034,
16,
2254,
5034,
16,
1758,
16,
1758,
16,
7010,
1082,
202,
11890,
5034,
16,
1758,
10019,
203,
203,
202,
202,
654,
39,
3462,
276,
11353,
1345,
273,
4232,
39,
3462,
12,
13440,
1345,
1769,
203,
203,
202,
202,
6528,
12,
71,
11353,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
300,
11013,
4649,
1545,
203,
1082,
565,
9563,
6275,
269,
6,
16351,
5061,
486,
336,
326,
28183,
8863,
203,
202,
202,
18356,
605,
15318,
329,
12,
13440,
1345,
16,
276,
11353,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
1769,
203,
1082,
203,
202,
202,
6528,
12,
9341,
6291,
18,
12908,
537,
12,
2867,
12,
71,
11353,
1345,
3631,
9563,
6275,
13,
422,
638,
16,
7010,
1082,
203,
202,
202,
654,
39,
3462,
276,
2326,
1345,
273,
4232,
39,
3462,
12,
3299,
1345,
1769,
203,
3639,
309,
261,
3299,
1345,
480,
22154,
3378,
5528,
13,
288,
203,
377,
202,
2
] |
pragma solidity ^0.5.17;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title Secondary
* @dev A Secondary contract can only be used by its primary account (the one that created it)
*/
contract Secondary {
address private _primary;
event PrimaryTransferred(
address recipient
);
/**
* @dev Sets the primary account to the one that is creating the Secondary contract.
*/
constructor () internal {
_primary = msg.sender;
emit PrimaryTransferred(_primary);
}
/**
* @dev Reverts if called from any account other than the primary.
*/
modifier onlyPrimary() {
require(msg.sender == _primary);
_;
}
/**
* @return the address of the primary.
*/
function primary() public view returns (address) {
return _primary;
}
/**
* @dev Transfers contract to a new primary.
* @param recipient The address of new primary.
*/
function transferPrimary(address recipient) public onlyPrimary {
require(recipient != address(0));
_primary = recipient;
emit PrimaryTransferred(_primary);
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Burnable.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
// File: node_modules\openzeppelin-solidity\contracts\access\Roles.sol
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
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));
return role.bearer[account];
}
}
// File: node_modules\openzeppelin-solidity\contracts\access\roles\MinterRole.sol
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Mintable.sol
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
// File: contracts\ERC20Frozenable.sol
//truffle-flattener Token.sol
contract ERC20Frozenable is ERC20Burnable, ERC20Mintable, Ownable {
mapping (address => bool) private _frozenAccount;
event FrozenFunds(address target, bool frozen);
function frozenAccount(address _address) public view returns(bool isFrozen) {
return _frozenAccount[_address];
}
function freezeAccount(address target, bool freeze) public onlyOwner {
require(_frozenAccount[target] != freeze, "Same as current");
_frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function _transfer(address from, address to, uint256 value) internal {
require(!_frozenAccount[from], "error - frozen");
require(!_frozenAccount[to], "error - frozen");
super._transfer(from, to, value);
}
}
// File: openzeppelin-solidity\contracts\token\ERC20\ERC20Detailed.sol
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
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;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
/**
* @title Escrow
* @dev Base escrow contract, holds funds designated for a payee until they
* withdraw them.
* @dev Intended usage: This contract (and derived escrow contracts) should be a
* standalone contract, that only interacts with the contract that instantiated
* it. That way, it is guaranteed that all Ether will be handled according to
* the Escrow rules, and there is no need to check for payable functions or
* transfers in the inheritance tree. The contract that uses the escrow as its
* payment method should be its primary, and provide public methods redirecting
* to the escrow's deposit and withdraw.
*/
contract Escrow is Secondary {
using SafeMath for uint256;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private _deposits;
function depositsOf(address payee) public view returns (uint256) {
return _deposits[payee];
}
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param payee The destination address of the funds.
*/
function deposit(address payee) public onlyPrimary payable {
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee].add(amount);
emit Deposited(payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee.
* @param payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address payable payee) public onlyPrimary {
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.transfer(payment);
emit Withdrawn(payee, payment);
}
}
/**
* @title PullPayment
* @dev Base contract supporting async send for pull payments. Inherit from this
* contract and use _asyncTransfer instead of send or transfer.
*/
contract PullPayment {
Escrow private _escrow;
constructor () internal {
_escrow = new Escrow();
}
/**
* @dev Withdraw accumulated balance.
* @param payee Whose balance will be withdrawn.
*/
function withdrawPayments(address payable payee) public {
_escrow.withdraw(payee);
}
/**
* @dev Returns the credit owed to an address.
* @param dest The creditor's address.
*/
function payments(address dest) public view returns (uint256) {
return _escrow.depositsOf(dest);
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function _asyncTransfer(address dest, uint256 amount) internal {
_escrow.deposit.value(amount)(dest);
}
}
contract PaymentSplitter {
using SafeMath for uint256;
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Constructor
*/
constructor (address[] memory payees, uint256[] memory 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 {
emit PaymentReceived(msg.sender, msg.value);
}
/**
* @return the total shares of the contract.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @return the total amount already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @return the shares of an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @return the amount already released to an account.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @return the address of a payee.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Release one of the payee's proportional payment.
* @param account Whose payments will be released.
*/
function release(address payable account) public {
require(_shares[account] > 0);
uint256 totalReceived = address(this).balance.add(_totalReleased);
uint256 payment = totalReceived.mul(_shares[account]).div(_totalShares).sub(_released[account]);
require(payment != 0);
_released[account] = _released[account].add(payment);
_totalReleased = _totalReleased.add(payment);
account.transfer(payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0));
require(shares_ > 0);
require(_shares[account] == 0);
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares.add(shares_);
emit PayeeAdded(account, shares_);
}
}
contract ConditionalEscrow is Escrow {
/**
* @dev Returns whether an address is allowed to withdraw their funds. To be
* implemented by derived contracts.
* @param payee The destination address of the funds.
*/
function withdrawalAllowed(address payee) public view returns (bool);
function withdraw(address payable payee) public {
require(withdrawalAllowed(payee));
super.withdraw(payee);
}
}
contract RefundEscrow is ConditionalEscrow {
enum State { Active, Refunding, Closed }
event RefundsClosed();
event RefundsEnabled();
State private _state;
address payable private _beneficiary;
/**
* @dev Constructor.
* @param beneficiary The beneficiary of the deposits.
*/
constructor (address payable beneficiary) public {
require(beneficiary != address(0));
_beneficiary = beneficiary;
_state = State.Active;
}
/**
* @return the current state of the escrow.
*/
function state() public view returns (State) {
return _state;
}
/**
* @return the beneficiary of the escrow.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @dev Stores funds that may later be refunded.
* @param refundee The address funds will be sent to if a refund occurs.
*/
function deposit(address refundee) public payable {
require(_state == State.Active);
super.deposit(refundee);
}
/**
* @dev Allows for the beneficiary to withdraw their funds, rejecting
* further deposits.
*/
function close() public onlyPrimary {
require(_state == State.Active);
_state = State.Closed;
emit RefundsClosed();
}
/**
* @dev Allows for refunds to take place, rejecting further deposits.
*/
function enableRefunds() public onlyPrimary {
require(_state == State.Active);
_state = State.Refunding;
emit RefundsEnabled();
}
/**
* @dev Withdraws the beneficiary's funds.
*/
function beneficiaryWithdraw() public {
require(_state == State.Closed);
_beneficiary.transfer(address(this).balance);
}
/**
* @dev Returns whether refundees can withdraw their deposits (be refunded). The overridden function receives a
* 'payee' argument, but we ignore it here since the condition is global, not per-payee.
*/
function withdrawalAllowed(address) public view returns (bool) {
return _state == State.Refunding;
}
}
// File: contracts\Token.sol
//truffle-flattener Token.sol
contract Blocks is ERC20Frozenable, ERC20Detailed {
constructor()
ERC20Detailed("GEP Token", "GEP", 18)
public {
uint256 supply = 1000000000;
uint256 initialSupply = supply * uint(10) ** decimals();
_mint(msg.sender, initialSupply);
}
} | truffle-flattener Token.sol | contract ERC20Frozenable is ERC20Burnable, ERC20Mintable, Ownable {
mapping (address => bool) private _frozenAccount;
event FrozenFunds(address target, bool frozen);
function frozenAccount(address _address) public view returns(bool isFrozen) {
return _frozenAccount[_address];
}
function freezeAccount(address target, bool freeze) public onlyOwner {
require(_frozenAccount[target] != freeze, "Same as current");
_frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function _transfer(address from, address to, uint256 value) internal {
require(!_frozenAccount[from], "error - frozen");
require(!_frozenAccount[to], "error - frozen");
super._transfer(from, to, value);
}
}
| 572,520 | [
1,
313,
10148,
17,
2242,
4558,
708,
3155,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
3462,
42,
303,
94,
7589,
353,
4232,
39,
3462,
38,
321,
429,
16,
4232,
39,
3462,
49,
474,
429,
16,
14223,
6914,
288,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
28138,
3032,
31,
203,
565,
871,
478,
9808,
42,
19156,
12,
2867,
1018,
16,
1426,
12810,
1769,
203,
203,
203,
203,
565,
445,
12810,
3032,
12,
2867,
389,
2867,
13,
1071,
1476,
1135,
12,
6430,
17646,
9808,
13,
288,
203,
3639,
327,
389,
28138,
3032,
63,
67,
2867,
15533,
203,
565,
289,
203,
203,
565,
445,
16684,
3032,
12,
2867,
1018,
16,
1426,
16684,
13,
225,
1071,
1338,
5541,
288,
203,
3639,
2583,
24899,
28138,
3032,
63,
3299,
65,
480,
16684,
16,
315,
8650,
487,
783,
8863,
203,
3639,
389,
28138,
3032,
63,
3299,
65,
273,
16684,
31,
203,
3639,
3626,
478,
9808,
42,
19156,
12,
3299,
16,
16684,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
13866,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
460,
13,
2713,
288,
203,
3639,
2583,
12,
5,
67,
28138,
3032,
63,
2080,
6487,
315,
1636,
300,
12810,
8863,
203,
3639,
2583,
12,
5,
67,
28138,
3032,
63,
869,
6487,
315,
1636,
300,
12810,
8863,
203,
3639,
2240,
6315,
13866,
12,
2080,
16,
358,
16,
460,
1769,
203,
565,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xdefac16715671b7b6aeeFE012125f1E19Ee4b7d7/sources/_PrimeToken.sol | * @dev Transfer tokens from one address to multiple others. @param from Address to send from. @param to Array of addresses to transfer to. @param value Array of amounts to be transferred. Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License)/ | function multiTransferFrom(
address from,
address[] calldata to,
uint256[] calldata value
) public whenNotPaused onlyBundler returns (bool) {
expect(to.length > 0, ERROR_EMPTY_ARRAY);
expect(value.length == to.length, ERROR_LENGTH_MISMATCH);
for (uint256 i = 0; i < to.length; i++) {
if (!isFrozen(to[i])) {
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value[i]);
_transfer(from, to[i], value[i]);
emit MultiTransferPrevented(from, to[i], value[i]);
}
}
return true;
}
| 2,630,661 | [
1,
5912,
2430,
628,
1245,
1758,
358,
3229,
10654,
18,
225,
628,
5267,
358,
1366,
628,
18,
225,
358,
1510,
434,
6138,
358,
7412,
358,
18,
225,
460,
1510,
434,
30980,
358,
506,
906,
4193,
18,
3914,
30389,
1312,
9173,
261,
27233,
1582,
1462,
4276,
716,
328,
3606,
603,
17,
5639,
3970,
19656,
16832,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
3309,
5912,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
8526,
745,
892,
358,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
460,
203,
565,
262,
1071,
1347,
1248,
28590,
1338,
15405,
1135,
261,
6430,
13,
288,
203,
3639,
4489,
12,
869,
18,
2469,
405,
374,
16,
5475,
67,
13625,
67,
8552,
1769,
203,
3639,
4489,
12,
1132,
18,
2469,
422,
358,
18,
2469,
16,
5475,
67,
7096,
67,
30062,
11793,
1769,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
358,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
16051,
291,
42,
9808,
12,
869,
63,
77,
22643,
288,
203,
7734,
2935,
63,
2080,
6362,
3576,
18,
15330,
65,
273,
2935,
63,
2080,
6362,
3576,
18,
15330,
8009,
1717,
12,
1132,
63,
77,
19226,
203,
7734,
389,
13866,
12,
2080,
16,
358,
63,
77,
6487,
460,
63,
77,
19226,
203,
7734,
3626,
5991,
5912,
25828,
329,
12,
2080,
16,
358,
63,
77,
6487,
460,
63,
77,
19226,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: ISC
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
// Libraries
import "./synthetix/SafeDecimalMath.sol";
import "./synthetix/SignedSafeDecimalMath.sol";
// Inherited
import "@openzeppelin/contracts/access/Ownable.sol";
// Interfaces
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IBlackScholes.sol";
import "./interfaces/ILyraGlobals.sol";
import "./interfaces/IOptionMarket.sol";
import "./interfaces/IOptionMarketPricer.sol";
import "./interfaces/IOptionGreekCache.sol";
/**
* @title OptionGreekCache
* @author Lyra
* @dev Aggregates the netDelta and netStdVega of the OptionMarket by iterating over current listings.
* Needs to be called by an external override actor as it's not feasible to do all the computation during the trade flow and
* because delta/vega change over time and with movements in asset price and volatility.
*/
contract OptionGreekCache is IOptionGreekCache, Ownable {
using SafeMath for uint;
using SafeDecimalMath for uint;
using SignedSafeMath for int;
using SignedSafeDecimalMath for int;
ILyraGlobals internal globals;
IOptionMarket internal optionMarket;
IOptionMarketPricer internal optionPricer;
IBlackScholes internal blackScholes;
// Limit due to gas constraints when updating
uint public constant override MAX_LISTINGS_PER_BOARD = 10;
// For calculating if the cache is stale based on spot price
// These values can be quite wide as per listing updates occur whenever a trade does.
uint public override staleUpdateDuration = 2 days;
uint public override priceScalingPeriod = 7 days;
uint public override maxAcceptablePercent = (1e18 / 100) * 20; // 20%
uint public override minAcceptablePercent = (1e18 / 100) * 10; // 10%
bool internal initialized;
uint[] public override liveBoards; // Should be a clone of OptionMarket.liveBoards
mapping(uint => OptionListingCache) public override listingCaches;
mapping(uint => OptionBoardCache) public override boardCaches;
GlobalCache public override globalCache;
constructor() Ownable() {}
/**
* @dev Initialize the contract.
*
* @param _globals LyraGlobals address
* @param _optionMarket OptionMarket address
* @param _optionPricer OptionMarketPricer address
*/
function init(
ILyraGlobals _globals,
IOptionMarket _optionMarket,
IOptionMarketPricer _optionPricer,
IBlackScholes _blackScholes
) external {
require(!initialized, "Contract already initialized");
globals = _globals;
optionMarket = _optionMarket;
optionPricer = _optionPricer;
blackScholes = _blackScholes;
initialized = true;
}
function setStaleCacheParameters(
uint _staleUpdateDuration,
uint _priceScalingPeriod,
uint _maxAcceptablePercent,
uint _minAcceptablePercent
) external override onlyOwner {
require(_staleUpdateDuration >= 2 hours, "staleUpdateDuration too low");
require(_maxAcceptablePercent >= _minAcceptablePercent, "maxAcceptablePercent must be >= min");
require(_minAcceptablePercent >= (1e18 / 100) * 1, "minAcceptablePercent too low");
// Note: this value can be zero even though it is in the divisor as timeToExpiry must be < priceScalingPeriod for it
// to be used.
priceScalingPeriod = _priceScalingPeriod;
minAcceptablePercent = _minAcceptablePercent;
maxAcceptablePercent = _maxAcceptablePercent;
staleUpdateDuration = _staleUpdateDuration;
emit StaleCacheParametersUpdated(
priceScalingPeriod,
minAcceptablePercent,
maxAcceptablePercent,
staleUpdateDuration
);
}
////
// Add/Remove boards
////
/**
* @notice Adds a new OptionBoardCache.
* @dev Called by the OptionMarket when an OptionBoard is added.
*
* @param boardId The id of the OptionBoard.
*/
function addBoard(uint boardId) external override onlyOptionMarket {
// Load in board from OptionMarket, adding net positions to global count
(, uint expiry, uint iv, ) = optionMarket.optionBoards(boardId);
uint[] memory listings = optionMarket.getBoardListings(boardId);
require(listings.length <= MAX_LISTINGS_PER_BOARD, "too many listings for board");
OptionBoardCache storage boardCache = boardCaches[boardId];
boardCache.id = boardId;
boardCache.expiry = expiry;
boardCache.iv = iv;
liveBoards.push(boardId);
for (uint i = 0; i < listings.length; i++) {
_addNewListingToListingCache(boardCache, listings[i]);
}
_updateBoardLastUpdatedAt(boardCache);
}
/**
* @notice Removes an OptionBoardCache.
* @dev Called by the OptionMarket when an OptionBoard is liquidated.
*
* @param boardId The id of the OptionBoard.
*/
function removeBoard(uint boardId) external override onlyOptionMarket {
// Remove board from cache, removing net positions from global count
OptionBoardCache memory boardCache = boardCaches[boardId];
globalCache.netDelta = globalCache.netDelta.sub(boardCache.netDelta);
globalCache.netStdVega = globalCache.netStdVega.sub(boardCache.netStdVega);
// Clean up, cache isn't necessary for settle logic
for (uint i = 0; i < boardCache.listings.length; i++) {
delete listingCaches[boardCache.listings[i]];
}
for (uint i = 0; i < liveBoards.length; i++) {
if (liveBoards[i] == boardId) {
liveBoards[i] = liveBoards[liveBoards.length - 1];
liveBoards.pop();
break;
}
}
delete boardCaches[boardId];
emit GlobalCacheUpdated(globalCache.netDelta, globalCache.netStdVega);
}
/**
* @dev modifies an OptionBoard's baseIv
*
* @param boardId The id of the OptionBoard.
* @param newIv The baseIv of the OptionBoard.
*/
function setBoardIv(uint boardId, uint newIv) external override onlyOptionMarket {
// Remove board from cache, removing net positions from global count
OptionBoardCache storage boardCache = boardCaches[boardId];
boardCache.iv = newIv;
}
/**
* @dev modifies an OptionListing's skew
*
* @param listingId The id of the OptionListing.
* @param newSkew The skew of the OptionListing.
*/
function setListingSkew(uint listingId, uint newSkew) external override onlyOptionMarket {
// Remove board from cache, removing net positions from global count
OptionListingCache storage listingCache = listingCaches[listingId];
listingCache.skew = newSkew;
}
/**
* @notice Add a new listing to the listingCaches and the listingId to the boardCache
*
* @param boardId The id of the Board
* @param listingId The id of the OptionListing.
*/
function addListingToBoard(uint boardId, uint listingId) external override onlyOptionMarket {
OptionBoardCache storage boardCache = boardCaches[boardId];
require(boardCache.listings.length + 1 <= MAX_LISTINGS_PER_BOARD, "too many listings for board");
_addNewListingToListingCache(boardCache, listingId);
}
/**
* @notice Add a new listing to the listingCaches
*
* @param boardCache The OptionBoardCache object the listing is being added to
* @param listingId The id of the OptionListing.
*/
function _addNewListingToListingCache(OptionBoardCache storage boardCache, uint listingId) internal {
IOptionMarket.OptionListing memory listing = getOptionMarketListing(listingId);
// This is only called when a new board or a new listing is added, so exposure values will be 0
OptionListingCache storage listingCache = listingCaches[listing.id];
listingCache.id = listing.id;
listingCache.strike = listing.strike;
listingCache.boardId = listing.boardId;
listingCache.skew = listing.skew;
boardCache.listings.push(listingId);
}
/**
* @notice Retrieves an OptionListing from the OptionMarket.
*
* @param listingId The id of the OptionListing.
*/
function getOptionMarketListing(uint listingId) internal view returns (IOptionMarket.OptionListing memory) {
(uint id, uint strike, uint skew, uint longCall, uint shortCall, uint longPut, uint shortPut, uint boardId) =
optionMarket.optionListings(listingId);
return IOptionMarket.OptionListing(id, strike, skew, longCall, shortCall, longPut, shortPut, boardId);
}
////
// Updating greeks/caches
////
/**
* @notice Updates all stale boards.
*/
function updateAllStaleBoards() external override returns (int) {
// Check all boards to see if they are stale
ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals = globals.getGreekCacheGlobals(address(optionMarket));
_updateAllStaleBoards(greekCacheGlobals);
return globalCache.netDelta;
}
/**
* @dev Updates all stale boards.
*
* @param greekCacheGlobals The GreekCacheGlobals.
*/
function _updateAllStaleBoards(ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals) internal {
for (uint i = 0; i < liveBoards.length; i++) {
uint boardId = liveBoards[i];
if (_isBoardCacheStale(boardId, greekCacheGlobals.spotPrice)) {
// This updates all listings in the board, even though it is not strictly necessary
_updateBoardCachedGreeks(greekCacheGlobals, boardId);
}
}
}
/**
* @notice Updates the cached greeks for an OptionBoardCache.
*
* @param boardCacheId The id of the OptionBoardCache.
*/
function updateBoardCachedGreeks(uint boardCacheId) external override {
_updateBoardCachedGreeks(globals.getGreekCacheGlobals(address(optionMarket)), boardCacheId);
}
/**
* @dev Updates the cached greeks for an OptionBoardCache.
*
* @param greekCacheGlobals The GreekCacheGlobals.
* @param boardCacheId The id of the OptionBoardCache.
*/
function _updateBoardCachedGreeks(ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals, uint boardCacheId)
internal
{
OptionBoardCache storage boardCache = boardCaches[boardCacheId];
// In the case the board doesnt exist, listings.length is 0, so nothing happens
for (uint i = 0; i < boardCache.listings.length; i++) {
OptionListingCache storage listingCache = listingCaches[boardCache.listings[i]];
_updateListingCachedGreeks(
greekCacheGlobals,
listingCache,
boardCache,
true,
listingCache.callExposure,
listingCache.putExposure
);
}
boardCache.minUpdatedAt = block.timestamp;
boardCache.minUpdatedAtPrice = greekCacheGlobals.spotPrice;
boardCache.maxUpdatedAtPrice = greekCacheGlobals.spotPrice;
_updateGlobalLastUpdatedAt();
}
/**
* @notice Updates the OptionListingCache to reflect the new exposure.
*
* @param greekCacheGlobals The GreekCacheGlobals.
* @param listingCacheId The id of the OptionListingCache.
* @param newCallExposure The new call exposure of the OptionListing.
* @param newPutExposure The new put exposure of the OptionListing.
* @param iv The new iv of the OptionBoardCache.
* @param skew The new skew of the OptionListingCache.
*/
function updateListingCacheAndGetPrice(
ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals,
uint listingCacheId,
int newCallExposure,
int newPutExposure,
uint iv,
uint skew
) external override onlyOptionMarketPricer returns (IOptionMarketPricer.Pricing memory) {
require(!_isGlobalCacheStale(greekCacheGlobals.spotPrice), "Global cache is stale");
OptionListingCache storage listingCache = listingCaches[listingCacheId];
OptionBoardCache storage boardCache = boardCaches[listingCache.boardId];
int callExposureDiff = newCallExposure.sub(listingCache.callExposure);
int putExposureDiff = newPutExposure.sub(listingCache.putExposure);
require(callExposureDiff == 0 || putExposureDiff == 0, "both call and put exposure updated");
boardCache.iv = iv;
listingCache.skew = skew;
// The AMM's net std vega is opposite to the global sum of user's std vega
int preTradeAmmNetStdVega = -globalCache.netStdVega;
IOptionMarketPricer.Pricing memory pricing =
_updateListingCachedGreeks(
greekCacheGlobals,
listingCache,
boardCache,
callExposureDiff != 0,
newCallExposure,
newPutExposure
);
pricing.preTradeAmmNetStdVega = preTradeAmmNetStdVega;
_updateBoardLastUpdatedAt(boardCache);
return pricing;
}
/**
* @dev Updates an OptionListingCache.
*
* @param greekCacheGlobals The GreekCacheGlobals.
* @param listingCache The OptionListingCache.
* @param boardCache The OptionBoardCache.
* @param returnCallPrice If true, return the call price, otherwise return the put price.
*/
function _updateListingCachedGreeks(
ILyraGlobals.GreekCacheGlobals memory greekCacheGlobals,
OptionListingCache storage listingCache,
OptionBoardCache storage boardCache,
bool returnCallPrice,
int newCallExposure,
int newPutExposure
) internal returns (IOptionMarketPricer.Pricing memory pricing) {
IBlackScholes.PricesDeltaStdVega memory pricesDeltaStdVega =
blackScholes.pricesDeltaStdVega(
timeToMaturitySeconds(boardCache.expiry),
boardCache.iv.multiplyDecimal(listingCache.skew),
greekCacheGlobals.spotPrice,
listingCache.strike,
greekCacheGlobals.rateAndCarry
);
// (newCallExposure * newCallDelta - oldCallExposure * oldCallDelta)
// + (newPutExposure * newPutDelta - oldPutExposure * oldPutDelta)
int netDeltaDiff =
(
(newCallExposure.multiplyDecimal(pricesDeltaStdVega.callDelta)) // newCall
.sub(listingCache.callExposure.multiplyDecimal(listingCache.callDelta))
.add(
(newPutExposure.multiplyDecimal(pricesDeltaStdVega.putDelta)).sub(
listingCache.putExposure.multiplyDecimal(listingCache.putDelta)
)
)
);
int netStdVegaDiff =
newCallExposure.add(newPutExposure).multiplyDecimal(int(pricesDeltaStdVega.stdVega)).sub(
listingCache.callExposure.add(listingCache.putExposure).multiplyDecimal(int(listingCache.stdVega))
);
if (listingCache.callExposure != newCallExposure || listingCache.putExposure != newPutExposure) {
emit ListingExposureUpdated(listingCache.id, newCallExposure, newPutExposure);
}
listingCache.callExposure = newCallExposure;
listingCache.putExposure = newPutExposure;
listingCache.callDelta = pricesDeltaStdVega.callDelta;
listingCache.putDelta = pricesDeltaStdVega.putDelta;
listingCache.stdVega = pricesDeltaStdVega.stdVega;
listingCache.updatedAt = block.timestamp;
listingCache.updatedAtPrice = greekCacheGlobals.spotPrice;
boardCache.netDelta = boardCache.netDelta.add(netDeltaDiff);
boardCache.netStdVega = boardCache.netStdVega.add(netStdVegaDiff);
globalCache.netDelta = globalCache.netDelta.add(netDeltaDiff);
globalCache.netStdVega = globalCache.netStdVega.add(netStdVegaDiff);
pricing.optionPrice = returnCallPrice ? pricesDeltaStdVega.callPrice : pricesDeltaStdVega.putPrice;
// AMM's net positions are the inverse of the user's net position
pricing.postTradeAmmNetStdVega = -globalCache.netStdVega;
pricing.callDelta = pricesDeltaStdVega.callDelta;
emit ListingGreeksUpdated(
listingCache.id,
pricesDeltaStdVega.callDelta,
pricesDeltaStdVega.putDelta,
pricesDeltaStdVega.stdVega,
greekCacheGlobals.spotPrice,
boardCache.iv,
listingCache.skew
);
emit GlobalCacheUpdated(globalCache.netDelta, globalCache.netStdVega);
return pricing;
}
/**
* @notice Checks if the GlobalCache is stale.
*/
function isGlobalCacheStale() external view override returns (bool) {
// Check all boards to see if they are stale
uint currentPrice = getCurrentPrice();
return _isGlobalCacheStale(currentPrice);
}
/**
* @dev Checks if the GlobalCache is stale.
*
* @param spotPrice The price of the baseAsset.
*/
function _isGlobalCacheStale(uint spotPrice) internal view returns (bool) {
// Check all boards to see if they are stale
return (isUpdatedAtTimeStale(globalCache.minUpdatedAt) ||
!isPriceMoveAcceptable(
globalCache.minUpdatedAtPrice,
spotPrice,
timeToMaturitySeconds(globalCache.minExpiryTimestamp)
) ||
!isPriceMoveAcceptable(
globalCache.maxUpdatedAtPrice,
spotPrice,
timeToMaturitySeconds(globalCache.minExpiryTimestamp)
));
}
/**
* @notice Checks if the OptionBoardCache is stale.
*
* @param boardCacheId The OptionBoardCache id.
*/
function isBoardCacheStale(uint boardCacheId) external view override returns (bool) {
uint spotPrice = getCurrentPrice();
return _isBoardCacheStale(boardCacheId, spotPrice);
}
/**
* @dev Checks if the OptionBoardCache is stale.
*
* @param boardCacheId The OptionBoardCache id.
* @param spotPrice The price of the baseAsset.
*/
function _isBoardCacheStale(uint boardCacheId, uint spotPrice) internal view returns (bool) {
// We do not have to check every individual listing, as the OptionBoardCache
// should always keep the minimum values.
OptionBoardCache memory boardCache = boardCaches[boardCacheId];
require(boardCache.id != 0, "Board does not exist");
return
isUpdatedAtTimeStale(boardCache.minUpdatedAt) ||
!isPriceMoveAcceptable(boardCache.minUpdatedAtPrice, spotPrice, timeToMaturitySeconds(boardCache.expiry)) ||
!isPriceMoveAcceptable(boardCache.maxUpdatedAtPrice, spotPrice, timeToMaturitySeconds(boardCache.expiry));
}
/**
* @dev Checks if `updatedAt` is stale.
*
* @param updatedAt The time of the last update.
*/
function isUpdatedAtTimeStale(uint updatedAt) internal view returns (bool) {
// This can be more complex than just checking the item wasn't updated in the last two hours
return getSecondsTo(updatedAt, block.timestamp) > staleUpdateDuration;
}
/**
* @dev Check if the price move of an asset is acceptable given the time to expiry.
*
* @param pastPrice The previous price.
* @param currentPrice The current price.
* @param timeToExpirySec The time to expiry in seconds.
*/
function isPriceMoveAcceptable(
uint pastPrice,
uint currentPrice,
uint timeToExpirySec
) internal view returns (bool) {
uint acceptablePriceMovementPercent = maxAcceptablePercent;
if (timeToExpirySec < priceScalingPeriod) {
acceptablePriceMovementPercent = ((maxAcceptablePercent.sub(minAcceptablePercent)).mul(timeToExpirySec))
.div(priceScalingPeriod)
.add(minAcceptablePercent);
}
uint acceptablePriceMovement = pastPrice.multiplyDecimal(acceptablePriceMovementPercent);
if (currentPrice > pastPrice) {
return currentPrice.sub(pastPrice) < acceptablePriceMovement;
} else {
return pastPrice.sub(currentPrice) < acceptablePriceMovement;
}
}
/**
* @dev Updates `lastUpdatedAt` for an OptionBoardCache.
*
* @param boardCache The OptionBoardCache.
*/
function _updateBoardLastUpdatedAt(OptionBoardCache storage boardCache) internal {
OptionListingCache memory listingCache = listingCaches[boardCache.listings[0]];
uint minUpdate = listingCache.updatedAt;
uint minPrice = listingCache.updatedAtPrice;
uint maxPrice = listingCache.updatedAtPrice;
for (uint i = 1; i < boardCache.listings.length; i++) {
listingCache = listingCaches[boardCache.listings[i]];
if (listingCache.updatedAt < minUpdate) {
minUpdate = listingCache.updatedAt;
}
if (listingCache.updatedAtPrice < minPrice) {
minPrice = listingCache.updatedAtPrice;
} else if (listingCache.updatedAtPrice > maxPrice) {
maxPrice = listingCache.updatedAtPrice;
}
}
boardCache.minUpdatedAt = minUpdate;
boardCache.minUpdatedAtPrice = minPrice;
boardCache.maxUpdatedAtPrice = maxPrice;
_updateGlobalLastUpdatedAt();
}
/**
* @dev Updates global `lastUpdatedAt`.
*/
function _updateGlobalLastUpdatedAt() internal {
OptionBoardCache memory boardCache = boardCaches[liveBoards[0]];
uint minUpdate = boardCache.minUpdatedAt;
uint minPrice = boardCache.minUpdatedAtPrice;
uint minExpiry = boardCache.expiry;
uint maxPrice = boardCache.maxUpdatedAtPrice;
for (uint i = 1; i < liveBoards.length; i++) {
boardCache = boardCaches[liveBoards[i]];
if (boardCache.minUpdatedAt < minUpdate) {
minUpdate = boardCache.minUpdatedAt;
}
if (boardCache.minUpdatedAtPrice < minPrice) {
minPrice = boardCache.minUpdatedAtPrice;
}
if (boardCache.maxUpdatedAtPrice > maxPrice) {
maxPrice = boardCache.maxUpdatedAtPrice;
}
if (boardCache.expiry < minExpiry) {
minExpiry = boardCache.expiry;
}
}
globalCache.minUpdatedAt = minUpdate;
globalCache.minUpdatedAtPrice = minPrice;
globalCache.maxUpdatedAtPrice = maxPrice;
globalCache.minExpiryTimestamp = minExpiry;
}
/**
* @dev Returns time to maturity for a given expiry.
*/
function timeToMaturitySeconds(uint expiry) internal view returns (uint) {
return getSecondsTo(block.timestamp, expiry);
}
/**
* @dev Returns the difference in seconds between two dates.
*/
function getSecondsTo(uint fromTime, uint toTime) internal pure returns (uint) {
if (toTime > fromTime) {
return toTime - fromTime;
}
return 0;
}
/**
* @dev Get the price of the baseAsset for the OptionMarket.
*/
function getCurrentPrice() internal view returns (uint) {
return globals.getSpotPriceForMarket(address(optionMarket));
}
/**
* @dev Get the current cached global netDelta value.
*/
function getGlobalNetDelta() external view override returns (int) {
return globalCache.netDelta;
}
modifier onlyOptionMarket virtual {
require(msg.sender == address(optionMarket), "Only optionMarket permitted");
_;
}
modifier onlyOptionMarketPricer virtual {
require(msg.sender == address(optionPricer), "Only optionPricer permitted");
_;
}
/**
* @dev Emitted when stale cache parameters are updated.
*/
event StaleCacheParametersUpdated(
uint priceScalingPeriod,
uint minAcceptablePercent,
uint maxAcceptablePercent,
uint staleUpdateDuration
);
/**
* @dev Emitted when the cache of an OptionListing is updated.
*/
event ListingGreeksUpdated(
uint indexed listingId,
int callDelta,
int putDelta,
uint vega,
uint price,
uint baseIv,
uint skew
);
/**
* @dev Emitted when the exposure of an OptionListing is updated.
*/
event ListingExposureUpdated(uint indexed listingId, int newCallExposure, int newPutExposure);
/**
* @dev Emitted when the GlobalCache is updated.
*/
event GlobalCacheUpdated(int netDelta, int netStdVega);
}
| Note: this value can be zero even though it is in the divisor as timeToExpiry must be < priceScalingPeriod for it to be used. | function setStaleCacheParameters(
uint _staleUpdateDuration,
uint _priceScalingPeriod,
uint _maxAcceptablePercent,
uint _minAcceptablePercent
) external override onlyOwner {
require(_staleUpdateDuration >= 2 hours, "staleUpdateDuration too low");
require(_maxAcceptablePercent >= _minAcceptablePercent, "maxAcceptablePercent must be >= min");
require(_minAcceptablePercent >= (1e18 / 100) * 1, "minAcceptablePercent too low");
priceScalingPeriod = _priceScalingPeriod;
minAcceptablePercent = _minAcceptablePercent;
maxAcceptablePercent = _maxAcceptablePercent;
staleUpdateDuration = _staleUpdateDuration;
emit StaleCacheParametersUpdated(
priceScalingPeriod,
minAcceptablePercent,
maxAcceptablePercent,
staleUpdateDuration
);
}
| 912,956 | [
1,
8067,
30,
333,
460,
848,
506,
3634,
5456,
11376,
518,
353,
316,
326,
15013,
487,
23813,
14633,
1297,
506,
411,
6205,
8471,
5027,
364,
518,
358,
506,
1399,
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,
225,
445,
444,
19155,
1649,
2402,
12,
203,
565,
2254,
389,
334,
5349,
1891,
5326,
16,
203,
565,
2254,
389,
8694,
8471,
5027,
16,
203,
565,
2254,
389,
1896,
5933,
429,
8410,
16,
203,
565,
2254,
389,
1154,
5933,
429,
8410,
203,
225,
262,
3903,
3849,
1338,
5541,
288,
203,
565,
2583,
24899,
334,
5349,
1891,
5326,
1545,
576,
7507,
16,
315,
334,
5349,
1891,
5326,
4885,
4587,
8863,
203,
565,
2583,
24899,
1896,
5933,
429,
8410,
1545,
389,
1154,
5933,
429,
8410,
16,
315,
1896,
5933,
429,
8410,
1297,
506,
1545,
1131,
8863,
203,
565,
2583,
24899,
1154,
5933,
429,
8410,
1545,
261,
21,
73,
2643,
342,
2130,
13,
380,
404,
16,
315,
1154,
5933,
429,
8410,
4885,
4587,
8863,
203,
565,
6205,
8471,
5027,
273,
389,
8694,
8471,
5027,
31,
203,
565,
1131,
5933,
429,
8410,
273,
389,
1154,
5933,
429,
8410,
31,
203,
565,
943,
5933,
429,
8410,
273,
389,
1896,
5933,
429,
8410,
31,
203,
565,
14067,
1891,
5326,
273,
389,
334,
5349,
1891,
5326,
31,
203,
203,
565,
3626,
934,
5349,
1649,
2402,
7381,
12,
203,
1377,
6205,
8471,
5027,
16,
203,
1377,
1131,
5933,
429,
8410,
16,
203,
1377,
943,
5933,
429,
8410,
16,
203,
1377,
14067,
1891,
5326,
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
] |
./partial_match/1/0x8D35372EA3E85C49A60F0A72EdeFF8629dA3999A/sources/OneInchExchange.sol | * @dev Forward data to 1Inch contract @param _1inchExchange address of 1Inch (currently 0x11111112542d85b3ef69ae05771c2dccff4faa26 for mainnet) @return description - description of the swap/ call `swap()` call `unoswap()` Revert with original error message | {
if (data[0] == 0x7c) {
(, description, ) = abi.decode(data[4:], (address, I1Inch3.SwapDescription, bytes));
(address srcToken, uint256 amount, uint256 minReturn, bytes32[] memory pathData) = abi.decode(
data[4:],
(address, uint256, uint256, bytes32[])
);
description.srcToken = srcToken;
description.amount = amount;
description.minReturnAmount = minReturn;
description.flags = 0;
uint256 lastPath = uint256(pathData[pathData.length - 1]);
IUniRouter uniRouter = IUniRouter(address(lastPath & ADDRESS_MASK));
bool isReverse = lastPath & REVERSE_MASK > 0;
description.dstToken = isReverse ? uniRouter.token0() : uniRouter.token1();
description.dstReceiver = address(this);
}
IERC20(description.srcToken).safeApprove(address(_1inchExchange), description.amount);
uint256 balanceBefore = IERC20(description.dstToken).balanceOf(description.dstReceiver);
if (!success) {
assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
uint256 balanceAfter = IERC20(description.dstToken).balanceOf(description.dstReceiver);
returnedAmount = balanceAfter.sub(balanceBefore);
emit Swapped(description, returnedAmount);
}
| 2,698,444 | [
1,
8514,
501,
358,
404,
382,
343,
6835,
225,
389,
21,
267,
343,
11688,
1758,
434,
404,
382,
343,
261,
2972,
715,
374,
92,
23680,
2499,
2138,
6564,
22,
72,
7140,
70,
23,
10241,
8148,
8906,
6260,
4700,
21,
71,
22,
72,
952,
1403,
24,
507,
69,
5558,
364,
2774,
2758,
13,
327,
2477,
300,
2477,
434,
326,
7720,
19,
745,
1375,
22270,
20338,
745,
1375,
318,
538,
91,
438,
20338,
868,
1097,
598,
2282,
555,
883,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
288,
203,
3639,
309,
261,
892,
63,
20,
65,
422,
374,
92,
27,
71,
13,
288,
203,
5411,
261,
16,
2477,
16,
262,
273,
24126,
18,
3922,
12,
892,
63,
24,
30,
6487,
261,
2867,
16,
467,
21,
382,
343,
23,
18,
12521,
3291,
16,
1731,
10019,
203,
5411,
261,
2867,
1705,
1345,
16,
2254,
5034,
3844,
16,
2254,
5034,
1131,
990,
16,
1731,
1578,
8526,
3778,
589,
751,
13,
273,
24126,
18,
3922,
12,
203,
7734,
501,
63,
24,
30,
6487,
203,
7734,
261,
2867,
16,
2254,
5034,
16,
2254,
5034,
16,
1731,
1578,
63,
5717,
203,
5411,
11272,
203,
5411,
2477,
18,
4816,
1345,
273,
1705,
1345,
31,
203,
5411,
2477,
18,
8949,
273,
3844,
31,
203,
5411,
2477,
18,
1154,
990,
6275,
273,
1131,
990,
31,
203,
5411,
2477,
18,
7133,
273,
374,
31,
203,
5411,
2254,
5034,
1142,
743,
273,
2254,
5034,
12,
803,
751,
63,
803,
751,
18,
2469,
300,
404,
19226,
203,
5411,
467,
984,
77,
8259,
7738,
8259,
273,
467,
984,
77,
8259,
12,
2867,
12,
2722,
743,
473,
11689,
10203,
67,
11704,
10019,
203,
5411,
1426,
353,
12650,
273,
1142,
743,
473,
2438,
28489,
67,
11704,
405,
374,
31,
203,
5411,
2477,
18,
11057,
1345,
273,
353,
12650,
692,
7738,
8259,
18,
2316,
20,
1435,
294,
7738,
8259,
18,
2316,
21,
5621,
203,
5411,
2477,
18,
11057,
12952,
273,
1758,
12,
2211,
1769,
203,
3639,
289,
203,
203,
3639,
467,
654,
39,
3462,
12,
3384,
18,
4816,
1345,
2934,
4626,
12053,
537,
12,
2867,
24899,
2
] |
pragma solidity ^0.5.0;
import '../node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol';
import '../node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol';
contract Star is ERC721, ERC721Metadata {
constructor() ERC721Metadata("UdaTokenName", "USYMB") public {
}
struct OneStar {
string starName;
string starStory;
string ra;
string dec;
string mag;
bytes32 coordsHash;
uint256 diameter;
uint256 temp;
}
mapping(uint256 => OneStar) public tokenIdToStarInfo;
mapping(bytes32 => bool) public unique;
mapping(uint256 => uint256) public starsForSale;
mapping(address => uint256[]) public starsOwner;
uint256 public tokenAt;
function createStar(string memory starName, string memory starStory, string memory ra, string memory dec, string memory mag) public {
tokenAt++;
bytes32 coordinates;
// It should be greater than 3
require(bytes(starName).length > 3, "It should be greater than 3");
// coordinates = keccak256(abi.encodePacked(ra, dec, mag));
coordinates = coordinatesToHash(ra, dec, mag);
require(!checkIfStarExist(coordinates), "We have that Star!");
OneStar memory newStar = OneStar(starName, starStory, ra, dec, mag, coordinates, 5, 7);
uint256 tokenId = tokenAt;
tokenIdToStarInfo[tokenId] = newStar;
unique[coordinates] = true;
starsOwner[msg.sender].push(tokenAt);
_mint(msg.sender, tokenId);
}
function getListPlanets(address ownerOfPlanet) public view returns(uint256[] memory) {
return starsOwner[ownerOfPlanet];
}
function getTokenIdToStarInfo(uint256 tokenId) public view returns(string memory, string memory, string memory, string memory, string memory) {
return (tokenIdToStarInfo[tokenId].starName, tokenIdToStarInfo[tokenId].starStory, tokenIdToStarInfo[tokenId].ra,
tokenIdToStarInfo[tokenId].dec, tokenIdToStarInfo[tokenId].mag);
}
function checkIfStarExist(bytes32 coordinates) public view returns(bool) {
return unique[coordinates];
}
// To avoid: Warning: Function state mutability can be restricted to pure
function coordinatesToHash(string memory ra, string memory dec, string memory mag) public pure returns(bytes32) {
return keccak256(abi.encodePacked(ra, dec, mag));
}
function putStarUpForSale(uint256 tokenId, uint256 price) public {
require(this.ownerOf(tokenId) == msg.sender, "You are not the owner of that Star!");
starsForSale[tokenId] = price;
}
function buyStar(uint256 tokenId) public payable {
// If it has a price, it is up for sale
require(starsForSale[tokenId] > 0, "If it has a price, it is up for sale");
uint256 starCost = starsForSale[tokenId];
address payable starOwner = address(uint160(this.ownerOf(tokenId)));
require(msg.value >= starCost, "It cost more!");
_removeTokenFrom(starOwner, tokenId);
_addTokenTo(msg.sender, tokenId);
starOwner.transfer(starCost);
// If the value sent is more than the value of the star, we send the remaining back
if(msg.value > starCost) {
msg.sender.transfer(msg.value - starCost);
}
// And since it was sold, we remove it from the mapping
starsForSale[tokenId] = 0;
}
// https://medium.com/coinmonks/exploring-non-fungible-token-with-zeppelin-library-erc721-399cb180cfaf
function mint(uint256 tokenId) public {
super._mint(msg.sender, tokenId);
}
function transferStar(address starOwner, address to, uint256 tokenId) public {
safeTransferFrom(starOwner, to, tokenId);
}
function exchangeStars(address user1, uint256 user1TokenId, address user2, uint256 user2TokenId) public {
require(this.ownerOf(user1TokenId) == user1, "it is owner1");
require(this.ownerOf(user2TokenId) == user2, "it is owner2");
_removeTokenFrom(user1, user1TokenId);
_addTokenTo(user2, user1TokenId);
_removeTokenFrom(user2, user2TokenId);
_addTokenTo(user1, user2TokenId);
}
function _removeTokenFrom(address user, uint256 userTokenId) public {
}
function _addTokenTo(address user, uint256 userTokenId) public {
}
}
| ERROR: type should be string, got " https:medium.com/coinmonks/exploring-non-fungible-token-with-zeppelin-library-erc721-399cb180cfaf" | function mint(uint256 tokenId) public {
super._mint(msg.sender, tokenId);
}
| 929,995 | [
1,
4528,
30,
19011,
18,
832,
19,
12645,
2586,
7904,
19,
338,
412,
6053,
17,
5836,
17,
12125,
75,
1523,
17,
2316,
17,
1918,
17,
94,
881,
84,
292,
267,
17,
12083,
17,
12610,
27,
5340,
17,
23,
2733,
7358,
18278,
71,
507,
74,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
915,
312,
474,
12,
11890,
5034,
1147,
548,
13,
1071,
288,
203,
202,
202,
9565,
6315,
81,
474,
12,
3576,
18,
15330,
16,
1147,
548,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x33e652AE420704634Dc2c5ca3F5915e1f7287Be8/sources/HedgeyPutsV1.sol | grab the calls by their index
| Put storage put = puts[i]; | 3,298,141 | [
1,
2752,
70,
326,
4097,
635,
3675,
770,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
4399,
2502,
1378,
273,
8200,
63,
77,
15533,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x77337dEEA78720542f0A1325394Def165918D562/sources/src/SplitSwapRouter.sol | uni v3 optimistically sends tokenOut funds, then calls this function for the tokenIn amount | if (amount0Delta > 0) ERC20(tokenIn).safeTransfer(msg.sender, uint256(amount0Delta));
| 16,513,900 | [
1,
318,
77,
331,
23,
5213,
5846,
1230,
9573,
1147,
1182,
284,
19156,
16,
1508,
4097,
333,
445,
364,
326,
1147,
382,
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
] | [
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,
309,
261,
8949,
20,
9242,
405,
374,
13,
4232,
39,
3462,
12,
2316,
382,
2934,
4626,
5912,
12,
3576,
18,
15330,
16,
2254,
5034,
12,
8949,
20,
9242,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "./V2Keep3rPublicJob.sol";
contract TendV2Keep3rJob is V2Keep3rPublicJob {
constructor(
address _mechanicsRegistry,
address _yOracle,
address _keep3r,
address _bond,
uint256 _minBond,
uint256 _earned,
uint256 _age,
bool _onlyEOA,
address _v2Keeper,
uint256 _workCooldown
)
V2Keep3rPublicJob(_mechanicsRegistry, _yOracle, _keep3r, _bond, _minBond, _earned, _age, _onlyEOA, _v2Keeper, _workCooldown)
// solhint-disable-next-line no-empty-blocks
{
}
function workable(address _strategy) external view override returns (bool) {
return _workable(_strategy);
}
function _workable(address _strategy) internal view override returns (bool) {
if (!super._workable(_strategy)) return false;
return IBaseStrategy(_strategy).tendTrigger(_getCallCosts(_strategy));
}
function _work(address _strategy) internal override {
lastWorkAt[_strategy] = block.timestamp;
V2Keeper.tend(_strategy);
}
// Keep3r actions
function work(address _strategy) external override notPaused onlyKeeper(msg.sender) returns (uint256 _credits) {
_credits = _workInternal(_strategy);
_paysKeeperAmount(msg.sender, _credits);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "./V2Keep3rJob.sol";
import "../../interfaces/jobs/v2/IV2Keep3rPublicJob.sol";
abstract contract V2Keep3rPublicJob is V2Keep3rJob, IV2Keep3rPublicJob {
constructor(
address _mechanicsRegistry,
address _yOracle,
address _keep3r,
address _bond,
uint256 _minBond,
uint256 _earned,
uint256 _age,
bool _onlyEOA,
address _v2Keeper,
uint256 _workCooldown
) V2Keep3rJob(_mechanicsRegistry, _yOracle, _keep3r, _bond, _minBond, _earned, _age, _onlyEOA, _v2Keeper, _workCooldown) {}
// Mechanics keeper bypass
function forceWork(address _strategy) external override onlyGovernorOrMechanic {
_forceWork(_strategy);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@lbertenasco/contract-utils/contracts/abstract/MachineryReady.sol";
import "@lbertenasco/contract-utils/interfaces/keep3r/IKeep3rV1Helper.sol";
import "@lbertenasco/contract-utils/contracts/keep3r/Keep3rAbstract.sol";
import "../../interfaces/jobs/v2/IV2Keeper.sol";
import "../../interfaces/jobs/v2/IV2Keep3rJob.sol";
import "../../interfaces/yearn/IBaseStrategy.sol";
import "../../interfaces/oracle/IYOracle.sol";
import "../../interfaces/keep3r/IChainLinkFeed.sol";
abstract contract V2Keep3rJob is MachineryReady, Keep3r, IV2Keep3rJob {
using EnumerableSet for EnumerableSet.AddressSet;
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public override fastGasOracle = 0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C;
uint256 public constant PRECISION = 1_000;
uint256 public constant MAX_REWARD_MULTIPLIER = 1 * PRECISION; // 1x max reward multiplier
uint256 public override rewardMultiplier = 950;
IV2Keeper public V2Keeper;
address public yOracle;
EnumerableSet.AddressSet internal _availableStrategies;
mapping(address => uint256) public requiredAmount;
mapping(address => uint256) public lastWorkAt;
// custom cost oracle calcs
mapping(address => address) public costToken;
mapping(address => address) public costPair;
uint256 public workCooldown;
constructor(
address _mechanicsRegistry,
address _yOracle,
address _keep3r,
address _bond,
uint256 _minBond,
uint256 _earned,
uint256 _age,
bool _onlyEOA,
address _v2Keeper,
uint256 _workCooldown
) MachineryReady(_mechanicsRegistry) Keep3r(_keep3r) {
_setYOracle(_yOracle);
_setKeep3rRequirements(_bond, _minBond, _earned, _age, _onlyEOA);
V2Keeper = IV2Keeper(_v2Keeper);
if (_workCooldown > 0) _setWorkCooldown(_workCooldown);
}
// Keep3r Setters
function setKeep3r(address _keep3r) external override onlyGovernor {
_setKeep3r(_keep3r);
}
function setV2Keep3r(address _v2Keeper) external override onlyGovernor {
V2Keeper = IV2Keeper(_v2Keeper);
}
function setYOracle(address _yOracle) external override onlyGovernor {
_setYOracle(_yOracle);
}
function _setYOracle(address _yOracle) internal {
yOracle = _yOracle;
}
function setFastGasOracle(address _fastGasOracle) external override onlyGovernor {
require(_fastGasOracle != address(0), "V2Keep3rJob::set-fas-gas-oracle:not-zero-address");
fastGasOracle = _fastGasOracle;
}
function setKeep3rRequirements(
address _bond,
uint256 _minBond,
uint256 _earned,
uint256 _age,
bool _onlyEOA
) external override onlyGovernor {
_setKeep3rRequirements(_bond, _minBond, _earned, _age, _onlyEOA);
}
function setRewardMultiplier(uint256 _rewardMultiplier) external override onlyGovernorOrMechanic {
_setRewardMultiplier(_rewardMultiplier);
emit SetRewardMultiplier(_rewardMultiplier);
}
function _setRewardMultiplier(uint256 _rewardMultiplier) internal {
require(_rewardMultiplier <= MAX_REWARD_MULTIPLIER, "V2Keep3rJob::set-reward-multiplier:multiplier-exceeds-max");
rewardMultiplier = _rewardMultiplier;
}
// Setters
function setWorkCooldown(uint256 _workCooldown) external override onlyGovernorOrMechanic {
_setWorkCooldown(_workCooldown);
}
function _setWorkCooldown(uint256 _workCooldown) internal {
require(_workCooldown > 0, "V2Keep3rJob::set-work-cooldown:should-not-be-zero");
workCooldown = _workCooldown;
}
// Governor
function addStrategies(
address[] calldata _strategies,
uint256[] calldata _requiredAmounts,
address[] calldata _costTokens,
address[] calldata _costPairs
) external override onlyGovernorOrMechanic {
require(_strategies.length == _requiredAmounts.length, "V2Keep3rJob::add-strategies:strategies-required-amounts-different-length");
for (uint256 i; i < _strategies.length; i++) {
_addStrategy(_strategies[i], _requiredAmounts[i], _costTokens[i], _costPairs[i]);
}
}
function addStrategy(
address _strategy,
uint256 _requiredAmount,
address _costToken,
address _costPair
) external override onlyGovernorOrMechanic {
_addStrategy(_strategy, _requiredAmount, _costToken, _costPair);
}
function _addStrategy(
address _strategy,
uint256 _requiredAmount,
address _costToken,
address _costPair
) internal {
require(!_availableStrategies.contains(_strategy), "V2Keep3rJob::add-strategy:strategy-already-added");
_setRequiredAmount(_strategy, _requiredAmount);
_setCostTokenAndPair(_strategy, _costToken, _costPair);
emit StrategyAdded(_strategy, _requiredAmount);
_availableStrategies.add(_strategy);
}
function updateRequiredAmounts(address[] calldata _strategies, uint256[] calldata _requiredAmounts)
external
override
onlyGovernorOrMechanic
{
require(_strategies.length == _requiredAmounts.length, "V2Keep3rJob::update-strategies:strategies-required-amounts-different-length");
for (uint256 i; i < _strategies.length; i++) {
_updateRequiredAmount(_strategies[i], _requiredAmounts[i]);
}
}
function updateRequiredAmount(address _strategy, uint256 _requiredAmount) external override onlyGovernorOrMechanic {
_updateRequiredAmount(_strategy, _requiredAmount);
}
function _updateRequiredAmount(address _strategy, uint256 _requiredAmount) internal {
require(_availableStrategies.contains(_strategy), "V2Keep3rJob::update-required-amount:strategy-not-added");
_setRequiredAmount(_strategy, _requiredAmount);
emit StrategyModified(_strategy, _requiredAmount);
}
function updateCostTokenAndPair(
address _strategy,
address _costToken,
address _costPair
) external override onlyGovernorOrMechanic {
_updateCostTokenAndPair(_strategy, _costToken, _costPair);
}
function _updateCostTokenAndPair(
address _strategy,
address _costToken,
address _costPair
) internal {
require(_availableStrategies.contains(_strategy), "V2Keep3rJob::update-required-amount:strategy-not-added");
_setCostTokenAndPair(_strategy, _costToken, _costPair);
}
function removeStrategy(address _strategy) external override onlyGovernorOrMechanic {
require(_availableStrategies.contains(_strategy), "V2Keep3rJob::remove-strategy:strategy-not-added");
delete requiredAmount[_strategy];
_availableStrategies.remove(_strategy);
emit StrategyRemoved(_strategy);
}
function _setRequiredAmount(address _strategy, uint256 _requiredAmount) internal {
requiredAmount[_strategy] = _requiredAmount;
}
function _setCostTokenAndPair(
address _strategy,
address _costToken,
address _costPair
) internal {
costToken[_strategy] = _costToken;
costPair[_strategy] = _costPair;
}
// Getters
function strategies() public view override returns (address[] memory _strategies) {
_strategies = new address[](_availableStrategies.length());
for (uint256 i; i < _availableStrategies.length(); i++) {
_strategies[i] = _availableStrategies.at(i);
}
}
// Keeper view actions (internal)
function _workable(address _strategy) internal view virtual returns (bool) {
require(_availableStrategies.contains(_strategy), "V2Keep3rJob::workable:strategy-not-added");
if (workCooldown == 0 || block.timestamp > lastWorkAt[_strategy] + workCooldown) return true;
return false;
}
// Get eth costs
function _getCallCosts(address _strategy) internal view returns (uint256 _callCost) {
if (requiredAmount[_strategy] == 0) return 0;
uint256 _ethCost = requiredAmount[_strategy] * uint256(IChainLinkFeed(fastGasOracle).latestAnswer());
if (costToken[_strategy] == address(0)) return _ethCost;
return IYOracle(yOracle).getAmountOut(costPair[_strategy], WETH, _ethCost, costToken[_strategy]);
}
// Keep3r actions
function _workInternal(address _strategy) internal returns (uint256 _credits) {
uint256 _initialGas = gasleft();
require(_workable(_strategy), "V2Keep3rJob::work:not-workable");
_work(_strategy);
_credits = _calculateCredits(_initialGas);
emit Worked(_strategy, msg.sender, _credits);
}
function _calculateCredits(uint256 _initialGas) internal view returns (uint256 _credits) {
// Gets default credits from KP3R_Helper and applies job reward multiplier
return (_getQuoteLimitFor(msg.sender, _initialGas) * rewardMultiplier) / PRECISION;
}
function _forceWork(address _strategy) internal {
_work(_strategy);
emit ForceWorked(_strategy);
}
function _work(address _strategy) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
interface IV2Keep3rPublicJob {}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// 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);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// 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))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import './UtilsReady.sol';
import '../utils/Machinery.sol';
abstract
contract MachineryReady is UtilsReady, Machinery {
constructor(address _mechanicsRegistry) Machinery(_mechanicsRegistry) UtilsReady() {
}
// Machinery: restricted-access
function setMechanicsRegistry(address _mechanicsRegistry) external override onlyGovernor {
_setMechanicsRegistry(_mechanicsRegistry);
}
// Machinery: modifiers
modifier onlyGovernorOrMechanic() {
require(isGovernor(msg.sender) || isMechanic(msg.sender), "Machinery::onlyGovernorOrMechanic:invalid-msg-sender");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IKeep3rV1Helper {
function quote(uint256 eth) external view returns (uint256);
function getFastGas() external view returns (uint256);
function bonds(address keeper) external view returns (uint256);
function getQuoteLimit(uint256 gasUsed) external view returns (uint256);
function getQuoteLimitFor(address origin, uint256 gasUsed) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '../../interfaces/keep3r/IKeep3rV1.sol';
import '../../interfaces/keep3r/IKeep3r.sol';
abstract
contract Keep3r is IKeep3r {
IKeep3rV1 internal _Keep3r;
address public override bond;
uint256 public override minBond;
uint256 public override earned;
uint256 public override age;
bool public override onlyEOA;
constructor(address _keep3r) {
_setKeep3r(_keep3r);
}
// Setters
function _setKeep3r(address _keep3r) internal {
_Keep3r = IKeep3rV1(_keep3r);
emit Keep3rSet(_keep3r);
}
function _setKeep3rRequirements(address _bond, uint256 _minBond, uint256 _earned, uint256 _age, bool _onlyEOA) internal {
bond = _bond;
minBond = _minBond;
earned = _earned;
age = _age;
onlyEOA = _onlyEOA;
emit Keep3rRequirementsSet(_bond, _minBond, _earned, _age, _onlyEOA);
}
// Modifiers
// Only checks if caller is a valid keeper, payment should be handled manually
modifier onlyKeeper(address _keeper) {
_isKeeper(_keeper);
_;
}
// view
function keep3r() external view override returns (address _keep3r) {
return address(_Keep3r);
}
// handles default payment after execution
modifier paysKeeper(address _keeper) {
_;
_paysKeeper(_keeper);
}
// Internal helpers
function _isKeeper(address _keeper) internal {
if (onlyEOA) require(_keeper == tx.origin, "keep3r::isKeeper:keeper-is-not-eoa");
if (minBond == 0 && earned == 0 && age == 0) {
// If no custom keeper requirements are set, just evaluate if sender is a registered keeper
require(_Keep3r.isKeeper(_keeper), "keep3r::isKeeper:keeper-is-not-registered");
} else {
if (bond == address(0)) {
// Checks for min KP3R, earned and age.
require(_Keep3r.isMinKeeper(_keeper, minBond, earned, age), "keep3r::isKeeper:keeper-not-min-requirements");
} else {
// Checks for min custom-bond, earned and age.
require(_Keep3r.isBondedKeeper(_keeper, bond, minBond, earned, age), "keep3r::isKeeper:keeper-not-custom-min-requirements");
}
}
}
function _getQuoteLimitFor(address _for, uint256 _initialGas) internal view returns (uint256 _credits) {
return _Keep3r.KPRH().getQuoteLimitFor(_for, _initialGas - gasleft());
}
// pays in bonded KP3R after execution
function _paysKeeper(address _keeper) internal {
_Keep3r.worked(_keeper);
}
// pays _amount in KP3R after execution
function _paysKeeperInTokens(address _keeper, uint256 _amount) internal {
_Keep3r.receipt(address(_Keep3r), _keeper, _amount);
}
// pays _amount in bonded KP3R after execution
function _paysKeeperAmount(address _keeper, uint256 _amount) internal {
_Keep3r.workReceipt(_keeper, _amount);
}
// pays _amount in _credit after execution
function _paysKeeperCredit(address _credit, address _keeper, uint256 _amount) internal {
_Keep3r.receipt(_credit, _keeper, _amount);
}
// pays _amount in ETH after execution
function _paysKeeperEth(address _keeper, uint256 _amount) internal {
_Keep3r.receiptETH(_keeper, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
interface IV2Keeper {
// Getters
function jobs() external view returns (address[] memory);
event JobAdded(address _job);
event JobRemoved(address _job);
// Setters
function addJobs(address[] calldata _jobs) external;
function addJob(address _job) external;
function removeJob(address _job) external;
// Jobs actions
function tend(address _strategy) external;
function harvest(address _strategy) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
import "../IKeep3rJob.sol";
interface IV2Keep3rJob is IKeep3rJob {
// event Keep3rSet(address keep3r);
event Keep3rHelperSet(address keep3rHelper);
event SlidingOracleSet(address slidingOracle);
// Setters
event StrategyAdded(address _strategy, uint256 _requiredAmount);
event StrategyModified(address _strategy, uint256 _requiredAmount);
event StrategyRemoved(address _strategy);
// Actions by Keeper
event Worked(address _strategy, address _keeper, uint256 _credits);
// Actions forced by governor
event ForceWorked(address _strategy);
// Getters
function fastGasOracle() external view returns (address _fastGasOracle);
function strategies() external view returns (address[] memory);
function workable(address _strategy) external view returns (bool);
// Setters
function setV2Keep3r(address _v2Keeper) external;
function setYOracle(address _v2Keeper) external;
function setFastGasOracle(address _fastGasOracle) external;
function setWorkCooldown(uint256 _workCooldown) external;
function addStrategies(
address[] calldata _strategy,
uint256[] calldata _requiredAmount,
address[] calldata _costTokens,
address[] calldata _costPairs
) external;
function addStrategy(
address _strategy,
uint256 _requiredAmount,
address _costToken,
address _costPair
) external;
function updateRequiredAmounts(address[] calldata _strategies, uint256[] calldata _requiredAmounts) external;
function updateRequiredAmount(address _strategy, uint256 _requiredAmount) external;
function updateCostTokenAndPair(
address _strategy,
address _costToken,
address _costPair
) external;
function removeStrategy(address _strategy) external;
// Keeper actions
function work(address _strategy) external returns (uint256 _credits);
// Mechanics keeper bypass
function forceWork(address _strategy) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IBaseStrategy {
function vault() external view returns (address _vault);
function strategist() external view returns (address _strategist);
function rewards() external view returns (address _rewards);
function keeper() external view returns (address _keeper);
function want() external view returns (address _want);
function name() external view returns (string memory _name);
function profitFactor() external view returns (uint256 _profitFactor);
function maxReportDelay() external view returns (uint256 _maxReportDelay);
// custom view
function crv() external view returns (address _crv);
// Setters
function setStrategist(address _strategist) external;
function setKeeper(address _keeper) external;
function setRewards(address _rewards) external;
function tendTrigger(uint256 callCost) external view returns (bool);
function tend() external;
function harvestTrigger(uint256 callCost) external view returns (bool);
function harvest() external;
function setBorrowCollateralizationRatio(uint256 _c) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IYOracle {
function defaultOracle() external view returns (address _defaultOracle);
function pairOracle(address _pair) external view returns (address _oracle);
function setPairOracle(address _pair, address _oracle) external;
function setDefaultOracle(address _oracle) external;
function getAmountOut(
address _pair,
address _tokenIn,
uint256 _amountIn,
address _tokenOut
) external view returns (uint256 _amountOut);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IChainLinkFeed {
function latestAnswer() external view returns (int256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '../utils/Governable.sol';
import '../utils/CollectableDust.sol';
import '../utils/Pausable.sol';
abstract
contract UtilsReady is Governable, CollectableDust, Pausable {
constructor() Governable(msg.sender) { }
// Governable: restricted-access
function setPendingGovernor(address _pendingGovernor) external override onlyGovernor {
_setPendingGovernor(_pendingGovernor);
}
function acceptGovernor() external override onlyPendingGovernor {
_acceptGovernor();
}
// Collectable Dust: restricted-access
function sendDust(
address _to,
address _token,
uint256 _amount
) external override virtual onlyGovernor {
_sendDust(_to, _token, _amount);
}
// Pausable: restricted-access
function pause(bool _paused) external override onlyGovernor {
_pause(_paused);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import '../../interfaces/utils/IMachinery.sol';
import '../../interfaces/mechanics/IMechanicsRegistry.sol';
contract Machinery is IMachinery {
using EnumerableSet for EnumerableSet.AddressSet;
IMechanicsRegistry internal _mechanicsRegistry;
constructor(address __mechanicsRegistry) {
_setMechanicsRegistry(__mechanicsRegistry);
}
modifier onlyMechanic {
require(_mechanicsRegistry.isMechanic(msg.sender), 'Machinery: not mechanic');
_;
}
function setMechanicsRegistry(address __mechanicsRegistry) external virtual override {
_setMechanicsRegistry(__mechanicsRegistry);
}
function _setMechanicsRegistry(address __mechanicsRegistry) internal {
_mechanicsRegistry = IMechanicsRegistry(__mechanicsRegistry);
}
// View helpers
function mechanicsRegistry() external view override returns (address _mechanicRegistry) {
return address(_mechanicsRegistry);
}
function isMechanic(address _mechanic) public view override returns (bool _isMechanic) {
return _mechanicsRegistry.isMechanic(_mechanic);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '../../interfaces/utils/IGovernable.sol';
contract Governable is IGovernable {
address public override governor;
address public override pendingGovernor;
constructor(address _governor) {
require(_governor != address(0), 'governable/governor-should-not-be-zero-address');
governor = _governor;
}
function setPendingGovernor(address _pendingGovernor) external virtual override onlyGovernor {
_setPendingGovernor(_pendingGovernor);
}
function acceptGovernor() external virtual override onlyPendingGovernor {
_acceptGovernor();
}
function _setPendingGovernor(address _pendingGovernor) internal {
require(_pendingGovernor != address(0), 'governable/pending-governor-should-not-be-zero-addres');
pendingGovernor = _pendingGovernor;
emit PendingGovernorSet(_pendingGovernor);
}
function _acceptGovernor() internal {
governor = pendingGovernor;
pendingGovernor = address(0);
emit GovernorAccepted();
}
function isGovernor(address _account) public view override returns (bool _isGovernor) {
return _account == governor;
}
modifier onlyGovernor {
require(isGovernor(msg.sender), 'governable/only-governor');
_;
}
modifier onlyPendingGovernor {
require(msg.sender == pendingGovernor, 'governable/only-pending-governor');
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import '../../interfaces/utils/ICollectableDust.sol';
abstract
contract CollectableDust is ICollectableDust {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
EnumerableSet.AddressSet internal protocolTokens;
constructor() {}
function _addProtocolToken(address _token) internal {
require(!protocolTokens.contains(_token), 'collectable-dust/token-is-part-of-the-protocol');
protocolTokens.add(_token);
}
function _removeProtocolToken(address _token) internal {
require(protocolTokens.contains(_token), 'collectable-dust/token-not-part-of-the-protocol');
protocolTokens.remove(_token);
}
function _sendDust(
address _to,
address _token,
uint256 _amount
) internal {
require(_to != address(0), 'collectable-dust/cant-send-dust-to-zero-address');
require(!protocolTokens.contains(_token), 'collectable-dust/token-is-part-of-the-protocol');
if (_token == ETH_ADDRESS) {
payable(_to).transfer(_amount);
} else {
IERC20(_token).safeTransfer(_to, _amount);
}
emit DustSent(_to, _token, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '../../interfaces/utils/IPausable.sol';
abstract
contract Pausable is IPausable {
bool public paused;
constructor() {}
modifier notPaused() {
require(!paused, 'paused');
_;
}
function _pause(bool _paused) internal {
require(paused != _paused, 'no-change');
paused = _paused;
emit Paused(_paused);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IGovernable {
event PendingGovernorSet(address pendingGovernor);
event GovernorAccepted();
function setPendingGovernor(address _pendingGovernor) external;
function acceptGovernor() external;
function governor() external view returns (address _governor);
function pendingGovernor() external view returns (address _pendingGovernor);
function isGovernor(address _account) external view returns (bool _isGovernor);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface ICollectableDust {
event DustSent(address _to, address token, uint256 amount);
function sendDust(address _to, address _token, uint256 _amount) external;
}
// 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.4;
interface IPausable {
event Paused(bool _paused);
function pause(bool _paused) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IMachinery {
// View helpers
function mechanicsRegistry() external view returns (address _mechanicsRegistry);
function isMechanic(address mechanic) external view returns (bool _isMechanic);
// Setters
function setMechanicsRegistry(address _mechanicsRegistry) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IMechanicsRegistry {
event MechanicAdded(address _mechanic);
event MechanicRemoved(address _mechanic);
function addMechanic(address _mechanic) external;
function removeMechanic(address _mechanic) external;
function mechanics() external view returns (address[] memory _mechanicsList);
function isMechanic(address mechanic) external view returns (bool _isMechanic);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IKeep3rV1Helper.sol";
interface IKeep3rV1 is IERC20 {
function name() external returns (string memory);
function KPRH() external view returns (IKeep3rV1Helper);
function isKeeper(address _keeper) external returns (bool);
function isMinKeeper(address _keeper, uint256 _minBond, uint256 _earned, uint256 _age) external returns (bool);
function isBondedKeeper(address _keeper, address _bond, uint256 _minBond, uint256 _earned, uint256 _age) external returns (bool);
function addKPRCredit(address _job, uint256 _amount) external;
function addJob(address _job) external;
function removeJob(address _job) external;
function addVotes(address voter, uint256 amount) external;
function removeVotes(address voter, uint256 amount) external;
function revoke(address keeper) external;
function worked(address _keeper) external;
function workReceipt(address _keeper, uint256 _amount) external;
function receipt(address credit, address _keeper, uint256 _amount) external;
function receiptETH(address _keeper, uint256 _amount) external;
function addLiquidityToJob(address liquidity, address job, uint amount) external;
function applyCreditToJob(address provider, address liquidity, address job) external;
function unbondLiquidityFromJob(address liquidity, address job, uint amount) external;
function removeLiquidityFromJob(address liquidity, address job) external;
function jobs(address _job) external view returns (bool);
function jobList(uint256 _index) external view returns (address _job);
function credits(address _job, address _credit) external view returns (uint256 _amount);
function liquidityAccepted(address _liquidity) external view returns (bool);
function liquidityProvided(address _provider, address _liquidity, address _job) external view returns (uint256 _amount);
function liquidityApplied(address _provider, address _liquidity, address _job) external view returns (uint256 _amount);
function liquidityAmount(address _provider, address _liquidity, address _job) external view returns (uint256 _amount);
function liquidityUnbonding(address _provider, address _liquidity, address _job) external view returns (uint256 _amount);
function liquidityAmountsUnbonding(address _provider, address _liquidity, address _job) external view returns (uint256 _amount);
function bond(address bonding, uint256 amount) external;
function activate(address bonding) external;
function unbond(address bonding, uint256 amount) external;
function withdraw(address bonding) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IKeep3r {
event Keep3rSet(address _keep3r);
event Keep3rRequirementsSet(address _bond, uint256 _minBond, uint256 _earned, uint256 _age, bool _onlyEOA);
function keep3r() external view returns (address _keep3r);
function bond() external view returns (address _bond);
function minBond() external view returns (uint256 _minBond);
function earned() external view returns (uint256 _earned);
function age() external view returns (uint256 _age);
function onlyEOA() external view returns (bool _onlyEOA);
function setKeep3r(address _keep3r) external;
function setKeep3rRequirements(address _bond, uint256 _minBond, uint256 _earned, uint256 _age, bool _onlyEOA) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IKeep3rJob {
event SetRewardMultiplier(uint256 _rewardMultiplier);
function rewardMultiplier() external view returns (uint256 _rewardMultiplier);
function setRewardMultiplier(uint256 _rewardMultiplier) external;
}
| pays _amount in _credit after execution | function _paysKeeperCredit(address _credit, address _keeper, uint256 _amount) internal {
_Keep3r.receipt(_credit, _keeper, _amount);
}
| 1,421,499 | [
1,
84,
8271,
389,
8949,
316,
389,
20688,
1839,
4588,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
389,
84,
8271,
17891,
16520,
12,
2867,
389,
20688,
16,
1758,
389,
79,
9868,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
565,
389,
11523,
23,
86,
18,
8606,
8138,
24899,
20688,
16,
389,
79,
9868,
16,
389,
8949,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
/**
* Math operations with safety checks that throw on error
*/
contract SafeMath {
function safeMul(uint256 a, uint256 b) public pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) public pure returns (uint256) {
//assert(a > 0);// Solidity automatically throws when dividing by 0
//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 safeSub(uint256 a, uint256 b) public pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) public pure returns (uint256) {
uint256 c = a + b;
assert(c>=a && c>=b);
return c;
}
}
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public constant returns (uint256);
function balanceOf(address _owner) public constant returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256);
/* ERC20 Events */
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ContractReceiver {
function tokenFallback(address _from, uint256 _value, bytes _data) public;
}
contract ERC223 is ERC20 {
function transfer(address _to, uint256 _value, bytes _data) public returns (bool success);
function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public returns (bool success);
/* ERC223 Events */
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes _data);
}
contract BankeraToken is ERC223, SafeMath {
string public constant name = "Banker Token"; // Set the name for display purposes
string public constant symbol = "BNK"; // Set the symbol for display purposes
uint8 public constant decimals = 8; // Amount of decimals for display purposes
uint256 private issued = 0; // tokens count issued to addresses
uint256 private totalTokens = 25000000000 * 100000000; //25,000,000,000.0000 0000 BNK
address private contractOwner;
address private rewardManager;
address private roundManager;
address private issueManager;
uint64 public currentRound = 0;
bool public paused = false;
mapping (uint64 => Reward) public reward; //key - round, value - reward in round
mapping (address => AddressBalanceInfoStructure) public accountBalances; //key - address, value - address balance info
mapping (uint64 => uint256) public issuedTokensInRound; //key - round, value - issued tokens
mapping (address => mapping (address => uint256)) internal allowed;
uint256 public blocksPerRound; // blocks per round
uint256 public lastBlockNumberInRound;
struct Reward {
uint64 roundNumber;
uint256 rewardInWei;
uint256 rewardRate; //reward rate in wei. 1 sBNK - xxx wei
bool isConfigured;
}
struct AddressBalanceInfoStructure {
uint256 addressBalance;
mapping (uint256 => uint256) roundBalanceMap; //key - round number, value - total token amount in round
mapping (uint64 => bool) wasModifiedInRoundMap; //key - round number, value - is modified in round
uint64[] mapKeys; //round balance map keys
uint64 claimedRewardTillRound;
uint256 totalClaimedReward;
}
/* Initializes contract with initial blocks per round number*/
function BankeraToken(uint256 _blocksPerRound, uint64 _round) public {
contractOwner = msg.sender;
lastBlockNumberInRound = block.number;
blocksPerRound = _blocksPerRound;
currentRound = _round;
}
function() public whenNotPaused payable {
}
// Public functions
/**
* @dev Reject all ERC223 compatible tokens
* @param _from address The address that is transferring the tokens
* @param _value uint256 the amount of the specified token
* @param _data Bytes The data passed from the caller.
*/
function tokenFallback(address _from, uint256 _value, bytes _data) public whenNotPaused view {
revert();
}
function setReward(uint64 _roundNumber, uint256 _roundRewardInWei) public whenNotPaused onlyRewardManager {
isNewRound();
Reward storage rewardInfo = reward[_roundNumber];
//validations
assert(rewardInfo.roundNumber == _roundNumber);
assert(!rewardInfo.isConfigured); //allow just not configured reward configuration
rewardInfo.rewardInWei = _roundRewardInWei;
if(_roundRewardInWei > 0){
rewardInfo.rewardRate = safeDiv(_roundRewardInWei, issuedTokensInRound[_roundNumber]);
}
rewardInfo.isConfigured = true;
}
/* Change contract owner */
function changeContractOwner(address _newContractOwner) public onlyContractOwner {
isNewRound();
if (_newContractOwner != contractOwner) {
contractOwner = _newContractOwner;
} else {
revert();
}
}
/* Change reward contract owner */
function changeRewardManager(address _newRewardManager) public onlyContractOwner {
isNewRound();
if (_newRewardManager != rewardManager) {
rewardManager = _newRewardManager;
} else {
revert();
}
}
/* Change round contract owner */
function changeRoundManager(address _newRoundManager) public onlyContractOwner {
isNewRound();
if (_newRoundManager != roundManager) {
roundManager = _newRoundManager;
} else {
revert();
}
}
/* Change issue contract owner */
function changeIssueManager(address _newIssueManager) public onlyContractOwner {
isNewRound();
if (_newIssueManager != issueManager) {
issueManager = _newIssueManager;
} else {
revert();
}
}
function setBlocksPerRound(uint64 _newBlocksPerRound) public whenNotPaused onlyRoundManager {
blocksPerRound = _newBlocksPerRound;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyContractOwner whenNotPaused public {
paused = true;
}
/**
* @dev called by the owner to resume, returns to normal state
*/
function resume() onlyContractOwner whenPaused public {
paused = false;
}
/**
*
* permission checker
*/
modifier onlyContractOwner() {
if(msg.sender != contractOwner){
revert();
}
_;
}
/**
* set reward for round (reward admin)
*/
modifier onlyRewardManager() {
if(msg.sender != rewardManager && msg.sender != contractOwner){
revert();
}
_;
}
/**
* adjust round length (round admin)
*/
modifier onlyRoundManager() {
if(msg.sender != roundManager && msg.sender != contractOwner){
revert();
}
_;
}
/**
* issue tokens to ETH addresses (issue admin)
*/
modifier onlyIssueManager() {
if(msg.sender != issueManager && msg.sender != contractOwner){
revert();
}
_;
}
modifier notSelf(address _to) {
if(msg.sender == _to){
revert();
}
_;
}
/**
* @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);
_;
}
function getRoundBalance(address _address, uint256 _round) public view returns (uint256) {
return accountBalances[_address].roundBalanceMap[_round];
}
function isModifiedInRound(address _address, uint64 _round) public view returns (bool) {
return accountBalances[_address].wasModifiedInRoundMap[_round];
}
function getBalanceModificationRounds(address _address) public view returns (uint64[]) {
return accountBalances[_address].mapKeys;
}
//action for issue tokens
function issueTokens(address _receiver, uint256 _tokenAmount) public whenNotPaused onlyIssueManager {
isNewRound();
issue(_receiver, _tokenAmount);
}
function withdrawEther() public onlyContractOwner {
isNewRound();
if(this.balance > 0) {
contractOwner.transfer(this.balance);
} else {
revert();
}
}
/* Send coins from owner to other address */
/*Override*/
function transfer(address _to, uint256 _value) public notSelf(_to) whenNotPaused returns (bool success){
require(_to != address(0));
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(msg.sender, _to, _value, empty);
}
else {
return transferToAddress(msg.sender, _to, _value, empty);
}
}
/*Override*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return accountBalances[_owner].addressBalance;
}
/*Override*/
function totalSupply() public constant returns (uint256){
return totalTokens;
}
/**
* @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
*/
/*Override*/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
require(_to != address(0));
require(_value <= allowed[_from][msg.sender]);
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
require(transferToContract(_from, _to, _value, empty));
}
else {
require(transferToAddress(_from, _to, _value, empty));
}
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _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.
*/
/*Override*/
function approve(address _spender, uint256 _value) public whenNotPaused 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.
*/
/*Override*/
function allowance(address _owner, address _spender) public view whenNotPaused returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = safeAdd(allowed[msg.sender][_spender], _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, uint256 _subtractedValue) public returns (bool) {
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = safeSub(oldValue, _subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
// Function that is called when a user or another contract wants to transfer funds .
/*Override*/
function transfer(address _to, uint256 _value, bytes _data) public whenNotPaused notSelf(_to) returns (bool success){
require(_to != address(0));
if(isContract(_to)) {
return transferToContract(msg.sender, _to, _value, _data);
}
else {
return transferToAddress(msg.sender, _to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds.
/*Override*/
function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public whenNotPaused notSelf(_to) returns (bool success){
require(_to != address(0));
if(isContract(_to)) {
if(accountBalances[msg.sender].addressBalance < _value){ // Check if the sender has enough
revert();
}
if(safeAdd(accountBalances[_to].addressBalance, _value) < accountBalances[_to].addressBalance){ // Check for overflows
revert();
}
isNewRound();
subFromAddressBalancesInfo(msg.sender, _value); // Subtract from the sender
addToAddressBalancesInfo(_to, _value); // Add the same to the recipient
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
/* Notify anyone listening that this transfer took place */
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
else {
return transferToAddress(msg.sender, _to, _value, _data);
}
}
function claimReward() public whenNotPaused returns (uint256 rewardAmountInWei) {
isNewRound();
return claimRewardTillRound(currentRound);
}
function claimRewardTillRound(uint64 _claimTillRound) public whenNotPaused returns (uint256 rewardAmountInWei) {
isNewRound();
rewardAmountInWei = calculateClaimableRewardTillRound(msg.sender, _claimTillRound);
accountBalances[msg.sender].claimedRewardTillRound = _claimTillRound;
if (rewardAmountInWei > 0){
accountBalances[msg.sender].totalClaimedReward = safeAdd(accountBalances[msg.sender].totalClaimedReward, rewardAmountInWei);
msg.sender.transfer(rewardAmountInWei);
}
return rewardAmountInWei;
}
function calculateClaimableReward(address _address) public constant returns (uint256 rewardAmountInWei) {
return calculateClaimableRewardTillRound(_address, currentRound);
}
function calculateClaimableRewardTillRound(address _address, uint64 _claimTillRound) public constant returns (uint256) {
uint256 rewardAmountInWei = 0;
if (_claimTillRound > currentRound) { revert(); }
if (currentRound < 1) { revert(); }
AddressBalanceInfoStructure storage accountBalanceInfo = accountBalances[_address];
if(accountBalanceInfo.mapKeys.length == 0){ revert(); }
uint64 userLastClaimedRewardRound = accountBalanceInfo.claimedRewardTillRound;
if (_claimTillRound < userLastClaimedRewardRound) { revert(); }
for (uint64 workRound = userLastClaimedRewardRound; workRound < _claimTillRound; workRound++) {
Reward storage rewardInfo = reward[workRound];
assert(rewardInfo.isConfigured); //don't allow to withdraw reward if affected reward is not configured
if(accountBalanceInfo.wasModifiedInRoundMap[workRound]){
rewardAmountInWei = safeAdd(rewardAmountInWei, safeMul(accountBalanceInfo.roundBalanceMap[workRound], rewardInfo.rewardRate));
} else {
uint64 lastBalanceModifiedRound = 0;
for (uint256 i = accountBalanceInfo.mapKeys.length; i > 0; i--) {
uint64 modificationInRound = accountBalanceInfo.mapKeys[i-1];
if (modificationInRound <= workRound) {
lastBalanceModifiedRound = modificationInRound;
break;
}
}
rewardAmountInWei = safeAdd(rewardAmountInWei, safeMul(accountBalanceInfo.roundBalanceMap[lastBalanceModifiedRound], rewardInfo.rewardRate));
}
}
return rewardAmountInWei;
}
function createRounds(uint256 maxRounds) public {
uint256 blocksAfterLastRound = safeSub(block.number, lastBlockNumberInRound); //current block number - last round block number = blocks after last round
if(blocksAfterLastRound >= blocksPerRound){ // need to increase reward round if blocks after last round is greater or equal blocks per round
uint256 roundsNeedToCreate = safeDiv(blocksAfterLastRound, blocksPerRound); //calculate how many rounds need to create
if(roundsNeedToCreate > maxRounds){
roundsNeedToCreate = maxRounds;
}
lastBlockNumberInRound = safeAdd(lastBlockNumberInRound, safeMul(roundsNeedToCreate, blocksPerRound));
for (uint256 i = 0; i < roundsNeedToCreate; i++) {
updateRoundInformation();
}
}
}
// Private functions
//assemble the given address bytecode. If bytecode exists then the _address is a contract.
function isContract(address _address) private view returns (bool is_contract) {
uint256 length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_address)
}
return (length > 0);
}
function isNewRound() private {
uint256 blocksAfterLastRound = safeSub(block.number, lastBlockNumberInRound); //current block number - last round block number = blocks after last round
if(blocksAfterLastRound >= blocksPerRound){ // need to increase reward round if blocks after last round is greater or equal blocks per round
updateRoundsInformation(blocksAfterLastRound);
}
}
function updateRoundsInformation(uint256 _blocksAfterLastRound) private {
uint256 roundsNeedToCreate = safeDiv(_blocksAfterLastRound, blocksPerRound); //calculate how many rounds need to create
lastBlockNumberInRound = safeAdd(lastBlockNumberInRound, safeMul(roundsNeedToCreate, blocksPerRound)); //calculate last round creation block number
for (uint256 i = 0; i < roundsNeedToCreate; i++) {
updateRoundInformation();
}
}
function updateRoundInformation() private {
issuedTokensInRound[currentRound] = issued;
Reward storage rewardInfo = reward[currentRound];
rewardInfo.roundNumber = currentRound;
currentRound = currentRound + 1;
}
function issue(address _receiver, uint256 _tokenAmount) private {
if(_tokenAmount == 0){
revert();
}
uint256 newIssuedAmount = safeAdd(_tokenAmount, issued);
if(newIssuedAmount > totalTokens){
revert();
}
addToAddressBalancesInfo(_receiver, _tokenAmount);
issued = newIssuedAmount;
bytes memory empty;
if(isContract(_receiver)) {
ContractReceiver receiverContract = ContractReceiver(_receiver);
receiverContract.tokenFallback(msg.sender, _tokenAmount, empty);
}
/* Notify anyone listening that this transfer took place */
Transfer(msg.sender, _receiver, _tokenAmount, empty);
Transfer(msg.sender, _receiver, _tokenAmount);
}
function addToAddressBalancesInfo(address _receiver, uint256 _tokenAmount) private {
AddressBalanceInfoStructure storage accountBalance = accountBalances[_receiver];
if(!accountBalance.wasModifiedInRoundMap[currentRound]){ //allow just push one time per round
// If user first time get update balance set user claimed reward round to round before.
if(accountBalance.mapKeys.length == 0 && currentRound > 0){
accountBalance.claimedRewardTillRound = currentRound;
}
accountBalance.mapKeys.push(currentRound);
accountBalance.wasModifiedInRoundMap[currentRound] = true;
}
accountBalance.addressBalance = safeAdd(accountBalance.addressBalance, _tokenAmount);
accountBalance.roundBalanceMap[currentRound] = accountBalance.addressBalance;
}
function subFromAddressBalancesInfo(address _adr, uint256 _tokenAmount) private {
AddressBalanceInfoStructure storage accountBalance = accountBalances[_adr];
if(!accountBalance.wasModifiedInRoundMap[currentRound]){ //allow just push one time per round
accountBalance.mapKeys.push(currentRound);
accountBalance.wasModifiedInRoundMap[currentRound] = true;
}
accountBalance.addressBalance = safeSub(accountBalance.addressBalance, _tokenAmount);
accountBalance.roundBalanceMap[currentRound] = accountBalance.addressBalance;
}
//function that is called when transaction target is an address
function transferToAddress(address _from, address _to, uint256 _value, bytes _data) private returns (bool success) {
if(accountBalances[_from].addressBalance < _value){ // Check if the sender has enough
revert();
}
if(safeAdd(accountBalances[_to].addressBalance, _value) < accountBalances[_to].addressBalance){ // Check for overflows
revert();
}
isNewRound();
subFromAddressBalancesInfo(_from, _value); // Subtract from the sender
addToAddressBalancesInfo(_to, _value); // Add the same to the recipient
/* Notify anyone listening that this transfer took place */
Transfer(_from, _to, _value, _data);
Transfer(_from, _to, _value);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _from, address _to, uint256 _value, bytes _data) private returns (bool success) {
if(accountBalances[_from].addressBalance < _value){ // Check if the sender has enough
revert();
}
if(safeAdd(accountBalances[_to].addressBalance, _value) < accountBalances[_to].addressBalance){ // Check for overflows
revert();
}
isNewRound();
subFromAddressBalancesInfo(_from, _value); // Subtract from the sender
addToAddressBalancesInfo(_to, _value); // Add the same to the recipient
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(_from, _value, _data);
/* Notify anyone listening that this transfer took place */
Transfer(_from, _to, _value, _data);
Transfer(_from, _to, _value);
return true;
}
} | Add the same to the recipient
| addToAddressBalancesInfo(_to, _value); | 6,212,614 | [
1,
986,
326,
1967,
358,
326,
8027,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1082,
202,
1289,
774,
1887,
38,
26488,
966,
24899,
869,
16,
389,
1132,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.5;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
/*
* @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;
}
}
contract SupporterRole is Context {
using Roles for Roles.Role;
event SupporterAdded(address indexed account);
event SupporterRemoved(address indexed account);
Roles.Role private _supporters;
constructor () internal {
_addSupporter(_msgSender());
}
modifier onlySupporter() {
require(isSupporter(_msgSender()), "SupporterRole: caller does not have the Supporter role");
_;
}
function isSupporter(address account) public view returns (bool) {
return _supporters.has(account);
}
function addSupporter(address account) public onlySupporter {
_addSupporter(account);
}
function renounceSupporter() public {
_removeSupporter(_msgSender());
}
function _addSupporter(address account) internal {
_supporters.add(account);
emit SupporterAdded(account);
}
function _removeSupporter(address account) internal {
_supporters.remove(account);
emit SupporterRemoved(account);
}
}
contract PauserRole is Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(_msgSender());
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @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() internal 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() internal 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;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev A Secondary contract can only be used by its primary account (the one that created it).
*/
contract Secondary is Context {
address private _primary;
/**
* @dev Emitted when the primary contract changes.
*/
event PrimaryTransferred(
address recipient
);
/**
* @dev Sets the primary account to the one that is creating the Secondary contract.
*/
constructor () internal {
address msgSender = _msgSender();
_primary = msgSender;
emit PrimaryTransferred(msgSender);
}
/**
* @dev Reverts if called from any account other than the primary.
*/
modifier onlyPrimary() {
require(_msgSender() == _primary, "Secondary: caller is not the primary account");
_;
}
/**
* @return the address of the primary.
*/
function primary() public view returns (address) {
return _primary;
}
/**
* @dev Transfers contract to a new primary.
* @param recipient The address of new primary.
*/
function transferPrimary(address recipient) public onlyPrimary {
require(recipient != address(0), "Secondary: new primary is the zero address");
_primary = recipient;
emit PrimaryTransferred(recipient);
}
}
/**
* @title __unstable__TokenVault
* @dev Similar to an Escrow for tokens, this contract allows its primary account to spend its tokens as it sees fit.
* This contract is an internal helper for PostDeliveryCrowdsale, and should not be used outside of this context.
*/
// solhint-disable-next-line contract-name-camelcase
contract __unstable__TokenVault is Secondary {
function transferToken(IERC20 token, address to, uint256 amount) public onlyPrimary {
token.transfer(to, amount);
}
function transferFunds(address payable to, uint256 amount) public onlyPrimary {
require (address(this).balance >= amount);
to.transfer(amount);
}
function () external payable {}
}
/**
* @title MoonStaking
*/
contract MoonStaking is Ownable, Pausable, SupporterRole, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct Pool {
uint256 rate;
uint256 adapter;
uint256 totalStaked;
}
struct User {
mapping(address => UserSp) tokenPools;
UserSp ePool;
}
struct UserSp {
uint256 staked;
uint256 lastRewardTime;
uint256 earned;
}
mapping(address => User) users;
mapping(address => Pool) pools;
// The MOON TOKEN!
IERC20 public moon;
uint256 eRate;
uint256 eAdapter;
uint256 eTotalStaked;
__unstable__TokenVault private _vault;
/**
* @param _moon The MOON token.
*/
constructor(IERC20 _moon) public {
_vault = new __unstable__TokenVault();
moon = _moon;
}
/**
* @dev Update token pool rate
* @return True when successful
*/
function updatePoolRate(address pool, uint256 _rate, uint256 _adapter)
public onlyOwner returns (bool) {
pools[pool].rate = _rate;
pools[pool].adapter = _adapter;
return true;
}
/**
* @dev Update epool pool rate
* @return True when successful
*/
function updateEpoolRate(uint256 _rate, uint256 _adapter)
public onlyOwner returns (bool) {
eRate = _rate;
eAdapter = _adapter;
return true;
}
/**
* @dev Checks whether the pool is available.
* @return Whether the pool is available.
*/
function isPoolAvailable(address pool) public view returns (bool) {
return pools[pool].rate != 0;
}
/**
* @dev View pool token info
* @param _pool Token address.
* @return Pool info
*/
function poolTokenInfo(address _pool) public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
Pool storage pool = pools[_pool];
return (pool.rate, pool.adapter, pool.totalStaked);
}
/**
* @dev View pool E info
* @return Pool info
*/
function poolInfo(address poolAddress) public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
Pool storage sPool = pools[poolAddress];
return (sPool.rate, sPool.adapter, sPool.totalStaked);
}
/**
* @dev View pool E info
* @return Pool info
*/
function poolEInfo() public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
return (eRate, eAdapter, eTotalStaked);
}
/**
* @dev Get earned reward in e pool.
*/
function getEarnedEpool() public view returns (uint256) {
UserSp storage pool = users[_msgSender()].ePool;
return _getEarned(eRate, eAdapter, pool);
}
/**
* @dev Get earned reward in t pool.
*/
function getEarnedTpool(address stakingPoolAddress) public view returns (uint256) {
UserSp storage stakingPool = users[_msgSender()].tokenPools[stakingPoolAddress];
Pool storage pool = pools[stakingPoolAddress];
return _getEarned(pool.rate, pool.adapter, stakingPool);
}
/**
* @dev Stake with E
* @return true if successful
*/
function stakeE() public payable returns (bool) {
uint256 _value = msg.value;
require(_value != 0, "Zero amount");
address(uint160((address(_vault)))).transfer(_value);
UserSp storage ePool = users[_msgSender()].ePool;
ePool.earned = ePool.earned.add(_getEarned(eRate, eAdapter, ePool));
ePool.lastRewardTime = block.timestamp;
ePool.staked = ePool.staked.add(_value);
eTotalStaked = eTotalStaked.add(_value);
return true;
}
/**
* @dev Stake with tokens
* @param _value Token amount.
* @param token Token address.
* @return true if successful
*/
function stake(uint256 _value, IERC20 token) public returns (bool) {
require(token.balanceOf(_msgSender()) >= _value, "Insufficient Funds");
require(token.allowance(_msgSender(), address(this)) >= _value, "Insufficient Funds Approved");
address tokenAddress = address(token);
require(isPoolAvailable(tokenAddress), "Pool is not available");
_forwardFundsToken(token, _value);
Pool storage pool = pools[tokenAddress];
UserSp storage tokenPool = users[_msgSender()].tokenPools[tokenAddress];
tokenPool.earned = tokenPool.earned.add(_getEarned(pool.rate, pool.adapter, tokenPool));
tokenPool.lastRewardTime = block.timestamp;
tokenPool.staked = tokenPool.staked.add(_value);
pool.totalStaked = pool.totalStaked.add(_value);
return true;
}
/**
* @dev Withdraw all available tokens.
*/
function withdrawTokenPool(address token) public whenNotPaused nonReentrant returns (bool) {
UserSp storage tokenStakingPool = users[_msgSender()].tokenPools[token];
require(tokenStakingPool.staked > 0 != tokenStakingPool.earned > 0, "Not available");
if (tokenStakingPool.earned > 0) {
Pool storage pool = pools[token];
_vault.transferToken(moon, _msgSender(), _getEarned(pool.rate, pool.adapter, tokenStakingPool));
tokenStakingPool.lastRewardTime = block.timestamp;
tokenStakingPool.earned = 0;
}
if (tokenStakingPool.staked > 0) {
_vault.transferToken(IERC20(token), _msgSender(), tokenStakingPool.staked);
tokenStakingPool.staked = 0;
}
return true;
}
/**
* @dev Withdraw all available tokens.
*/
function withdrawEPool() public whenNotPaused nonReentrant returns (bool) {
UserSp storage eStakingPool = users[_msgSender()].ePool;
require(eStakingPool.staked > 0 != eStakingPool.earned > 0, "Not available");
if (eStakingPool.earned > 0) {
_vault.transferToken(moon, _msgSender(), _getEarned(eRate, eAdapter, eStakingPool));
eStakingPool.lastRewardTime = block.timestamp;
eStakingPool.earned = 0;
}
if (eStakingPool.staked > 0) {
_vault.transferFunds(_msgSender(), eStakingPool.staked);
eStakingPool.staked = 0;
}
return true;
}
/**
* @dev Claim earned Moon.
*/
function claimMoonInTpool(address token) public whenNotPaused returns (bool) {
UserSp storage tokenStakingPool = users[_msgSender()].tokenPools[token];
require(tokenStakingPool.staked > 0 != tokenStakingPool.earned > 0, "Not available");
Pool storage pool = pools[token];
_vault.transferToken(moon, _msgSender(), _getEarned(pool.rate, pool.adapter, tokenStakingPool));
tokenStakingPool.lastRewardTime = block.timestamp;
tokenStakingPool.earned = 0;
return true;
}
/**
* @dev Claim earned Moon.
*/
function claimMoonInEpool() public whenNotPaused returns (bool) {
UserSp storage eStakingPool = users[_msgSender()].ePool;
require(eStakingPool.staked > 0 != eStakingPool.earned > 0, "Not available");
_vault.transferToken(moon, _msgSender(), _getEarned(eRate, eAdapter, eStakingPool));
eStakingPool.lastRewardTime = block.timestamp;
eStakingPool.earned = 0;
return true;
}
/**
* @dev Get reserved token.
*/
function getReserved() public view onlyOwner
returns (uint256 vaultTokens, uint256 vaultFunds) {
address vaultAddress = address(_vault);
vaultTokens = moon.balanceOf(vaultAddress);
vaultFunds = address(uint160(vaultAddress)).balance;
}
/**
* @dev Get reserved token by address.
*/
function getReservedByAddress(IERC20 token) public view onlyOwner returns (uint256) {
return token.balanceOf(address(_vault));
}
/**
* @dev Supply token for the vaults.
* @param amount Supply amount
*/
function supplyVault(uint256 amount)
public onlyOwner
returns (bool) {
moon.transferFrom(_msgSender(), address(_vault), amount);
return true;
}
/**
* @dev deprive tokens from vaults.
* @param vault Vault address
* @param amount The amount
*/
function depriveToken(address vault, IERC20 token, uint256 amount)
public onlyOwner returns (bool) {
_vault.transferToken(token, vault, amount);
return true;
}
/**
* @dev deprive funds from vaults.
* @param vault Vault address
* @param amount The amount
*/
function depriveFunds(address payable vault, uint256 amount)
public onlyOwner
returns (bool) {
_vault.transferFunds(vault, amount);
return true;
}
/**
* @dev Fallback function
*/
function () external payable {
address(uint160((address(_vault)))).transfer(msg.value);
}
/**
* @dev Extend parent behavior
* @param erc20Token ERC20 Token
* @param _value Amount contributed
*/
function _forwardFundsToken(IERC20 erc20Token, uint256 _value) internal {
erc20Token.transferFrom(_msgSender(), address(_vault), _value);
}
/**
* @dev Get earned reward.
*/
function _getEarned(uint256 rate, uint256 adapter, UserSp memory stakingPool) internal view returns (uint256) {
uint256 moonPerSec = stakingPool.staked.mul(rate).div(adapter);
return block.timestamp.sub(stakingPool.lastRewardTime).mul(moonPerSec).add(stakingPool.earned);
}
} | * @dev Supply token for the vaults. @param amount Supply amount/ | function supplyVault(uint256 amount)
public onlyOwner
returns (bool) {
moon.transferFrom(_msgSender(), address(_vault), amount);
return true;
}
| 6,159,430 | [
1,
3088,
1283,
1147,
364,
326,
9229,
87,
18,
225,
3844,
3425,
1283,
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,
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,
14467,
12003,
12,
11890,
5034,
3844,
13,
203,
3639,
1071,
1338,
5541,
203,
3639,
1135,
261,
6430,
13,
288,
203,
3639,
7344,
265,
18,
13866,
1265,
24899,
3576,
12021,
9334,
1758,
24899,
26983,
3631,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-04-16
*/
// SPDX-License-Identifier: AGPL-3.0-or-later
/// IlkRegistry.sol -- Publicly updatable ilk registry
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity ^0.6.12;
interface JoinLike {
function vat() external view returns (address);
function ilk() external view returns (bytes32);
function gem() external view returns (address);
function dec() external view returns (uint256);
function live() external view returns (uint256);
}
interface VatLike {
function wards(address) external view returns (uint256);
function live() external view returns (uint256);
}
interface DogLike {
function vat() external view returns (address);
function live() external view returns (uint256);
function ilks(bytes32) external view returns (address, uint256, uint256, uint256);
}
interface CatLike {
function vat() external view returns (address);
function live() external view returns (uint256);
function ilks(bytes32) external view returns (address, uint256, uint256);
}
interface FlipLike {
function vat() external view returns (address);
function cat() external view returns (address);
}
interface ClipLike {
function vat() external view returns (address);
function dog() external view returns (address);
}
interface SpotLike {
function live() external view returns (uint256);
function vat() external view returns (address);
function ilks(bytes32) external view returns (address, uint256);
}
interface TokenLike {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
contract GemInfo {
function name(address token) external view returns (string memory) {
return TokenLike(token).name();
}
function symbol(address token) external view returns (string memory) {
return TokenLike(token).symbol();
}
}
contract IlkRegistry {
event Rely(address usr);
event Deny(address usr);
event File(bytes32 what, address data);
event File(bytes32 ilk, bytes32 what, address data);
event File(bytes32 ilk, bytes32 what, uint256 data);
event File(bytes32 ilk, bytes32 what, string data);
event AddIlk(bytes32 ilk);
event RemoveIlk(bytes32 ilk);
event UpdateIlk(bytes32 ilk);
event NameError(bytes32 ilk);
event SymbolError(bytes32 ilk);
// --- Auth ---
mapping (address => uint) public wards;
function rely(address usr) external auth { wards[usr] = 1; emit Rely(usr); }
function deny(address usr) external auth { wards[usr] = 0; emit Deny(usr); }
modifier auth {
require(wards[msg.sender] == 1, "IlkRegistry/not-authorized");
_;
}
VatLike public immutable vat;
GemInfo private immutable gemInfo;
DogLike public dog;
CatLike public cat;
SpotLike public spot;
struct Ilk {
uint96 pos; // Index in ilks array
address join; // DSS GemJoin adapter
address gem; // The token contract
uint8 dec; // Token decimals
uint96 class; // Classification code (1 - clip, 2 - flip, 3+ - other)
address pip; // Token price
address xlip; // Auction contract
string name; // Token name
string symbol; // Token symbol
}
mapping (bytes32 => Ilk) public ilkData;
bytes32[] ilks;
// Initialize the registry
constructor(address vat_, address dog_, address cat_, address spot_) public {
VatLike _vat = vat = VatLike(vat_);
dog = DogLike(dog_);
cat = CatLike(cat_);
spot = SpotLike(spot_);
require(dog.vat() == vat_, "IlkRegistry/invalid-dog-vat");
require(cat.vat() == vat_, "IlkRegistry/invalid-cat-vat");
require(spot.vat() == vat_, "IlkRegistry/invalid-spotter-vat");
require(_vat.wards(cat_) == 1, "IlkRegistry/cat-not-authorized");
require(_vat.wards(spot_) == 1, "IlkRegistry/spot-not-authorized");
require(_vat.live() == 1, "IlkRegistry/vat-not-live");
require(cat.live() == 1, "IlkRegistry/cat-not-live");
require(spot.live() == 1, "IlkRegistry/spot-not-live");
gemInfo = new GemInfo();
wards[msg.sender] = 1;
}
// Pass an active join adapter to the registry to add it to the set
function add(address adapter) external {
JoinLike _join = JoinLike(adapter);
// Validate adapter
require(_join.vat() == address(vat), "IlkRegistry/invalid-join-adapter-vat");
require(vat.wards(address(_join)) == 1, "IlkRegistry/adapter-not-authorized");
// Validate ilk
bytes32 _ilk = _join.ilk();
require(_ilk != 0, "IlkRegistry/ilk-adapter-invalid");
require(ilkData[_ilk].join == address(0), "IlkRegistry/ilk-already-exists");
(address _pip,) = spot.ilks(_ilk);
require(_pip != address(0), "IlkRegistry/pip-invalid");
(address _xlip,,,) = dog.ilks(_ilk);
uint96 _class = 1;
if (_xlip == address(0)) {
(_xlip,,) = cat.ilks(_ilk);
require(_xlip != address(0), "IlkRegistry/invalid-auction-contract");
_class = 2;
}
string memory name = bytes32ToStr(_ilk);
try gemInfo.name(_join.gem()) returns (string memory _name) {
if (bytes(_name).length != 0) {
name = _name;
}
} catch {
emit NameError(_ilk);
}
string memory symbol = bytes32ToStr(_ilk);
try gemInfo.symbol(_join.gem()) returns (string memory _symbol) {
if (bytes(_symbol).length != 0) {
symbol = _symbol;
}
} catch {
emit SymbolError(_ilk);
}
require(ilks.length < uint96(-1), "IlkRegistry/too-many-ilks");
ilks.push(_ilk);
ilkData[ilks[ilks.length - 1]] = Ilk({
pos: uint96(ilks.length - 1),
join: address(_join),
gem: _join.gem(),
dec: uint8(_join.dec()),
class: _class,
pip: _pip,
xlip: _xlip,
name: name,
symbol: symbol
});
emit AddIlk(_ilk);
}
// Anyone can remove an ilk if the adapter has been caged
function remove(bytes32 ilk) external {
JoinLike _join = JoinLike(ilkData[ilk].join);
require(address(_join) != address(0), "IlkRegistry/invalid-ilk");
uint96 _class = ilkData[ilk].class;
require(_class == 1 || _class == 2, "IlkRegistry/invalid-class");
require(_join.live() == 0, "IlkRegistry/ilk-live");
_remove(ilk);
emit RemoveIlk(ilk);
}
// Admin can remove an ilk without any precheck
function removeAuth(bytes32 ilk) external auth {
_remove(ilk);
emit RemoveIlk(ilk);
}
// Authed edit function
function file(bytes32 what, address data) external auth {
if (what == "dog") dog = DogLike(data);
else if (what == "cat") cat = CatLike(data);
else if (what == "spot") spot = SpotLike(data);
else revert("IlkRegistry/file-unrecognized-param-address");
emit File(what, data);
}
// Authed edit function
function file(bytes32 ilk, bytes32 what, address data) external auth {
if (what == "gem") ilkData[ilk].gem = data;
else if (what == "join") ilkData[ilk].join = data;
else if (what == "pip") ilkData[ilk].pip = data;
else if (what == "xlip") ilkData[ilk].xlip = data;
else revert("IlkRegistry/file-unrecognized-param-address");
emit File(ilk, what, data);
}
// Authed edit function
function file(bytes32 ilk, bytes32 what, uint256 data) external auth {
if (what == "class") { require(data <= uint96(-1) && data != 0); ilkData[ilk].class = uint96(data); }
else if (what == "dec") { require(data <= uint8(-1)); ilkData[ilk].dec = uint8(data); }
else revert("IlkRegistry/file-unrecognized-param-uint256");
emit File(ilk, what, data);
}
// Authed edit function
function file(bytes32 ilk, bytes32 what, string calldata data) external auth {
if (what == "name") ilkData[ilk].name = data;
else if (what == "symbol") ilkData[ilk].symbol = data;
else revert("IlkRegistry/file-unrecognized-param-string");
emit File(ilk, what, data);
}
// Remove ilk from the ilks array by replacing the ilk with the
// last in the array and then trimming the end.
function _remove(bytes32 ilk) internal {
// Get the position in the array
uint256 _index = ilkData[ilk].pos;
// Get the last ilk in the array
bytes32 _moveIlk = ilks[ilks.length - 1];
// Replace the ilk we are removing
ilks[_index] = _moveIlk;
// Update the array position for the moved ilk
ilkData[_moveIlk].pos = uint96(_index);
// Trim off the end of the ilks array
ilks.pop();
// Delete struct data
delete ilkData[ilk];
}
// The number of active ilks
function count() external view returns (uint256) {
return ilks.length;
}
// Return an array of the available ilks
function list() external view returns (bytes32[] memory) {
return ilks;
}
// Get a splice of the available ilks, useful when ilks array is large.
function list(uint256 start, uint256 end) external view returns (bytes32[] memory) {
require(start <= end && end < ilks.length, "IlkRegistry/invalid-input");
bytes32[] memory _ilks = new bytes32[]((end - start) + 1);
uint256 _count = 0;
for (uint256 i = start; i <= end; i++) {
_ilks[_count] = ilks[i];
_count++;
}
return _ilks;
}
// Get the ilk at a specific position in the array
function get(uint256 pos) external view returns (bytes32) {
require(pos < ilks.length, "IlkRegistry/index-out-of-range");
return ilks[pos];
}
// Get information about an ilk, including name and symbol
function info(bytes32 ilk) external view returns (
string memory name,
string memory symbol,
uint256 class,
uint256 dec,
address gem,
address pip,
address join,
address xlip
) {
Ilk memory _ilk = ilkData[ilk];
return (
_ilk.name,
_ilk.symbol,
_ilk.class,
_ilk.dec,
_ilk.gem,
_ilk.pip,
_ilk.join,
_ilk.xlip
);
}
// The location of the ilk in the ilks array
function pos(bytes32 ilk) external view returns (uint256) {
return ilkData[ilk].pos;
}
// The classification code of the ilk
// 1 - Flipper
// 2 - Clipper
// 3+ - RWA or custom adapter
function class(bytes32 ilk) external view returns (uint256) {
return ilkData[ilk].class;
}
// The token address
function gem(bytes32 ilk) external view returns (address) {
return ilkData[ilk].gem;
}
// The ilk's price feed
function pip(bytes32 ilk) external view returns (address) {
return ilkData[ilk].pip;
}
// The ilk's join adapter
function join(bytes32 ilk) external view returns (address) {
return ilkData[ilk].join;
}
// The auction contract for the ilk
function xlip(bytes32 ilk) external view returns (address) {
return ilkData[ilk].xlip;
}
// The number of decimals on the ilk
function dec(bytes32 ilk) external view returns (uint256) {
return ilkData[ilk].dec;
}
// Return the symbol of the token, if available
function symbol(bytes32 ilk) external view returns (string memory) {
return ilkData[ilk].symbol;
}
// Return the name of the token, if available
function name(bytes32 ilk) external view returns (string memory) {
return ilkData[ilk].name;
}
// Public function to update an ilk's pip and flip if the ilk has been updated.
function update(bytes32 ilk) external {
require(JoinLike(ilkData[ilk].join).vat() == address(vat), "IlkRegistry/invalid-ilk");
require(JoinLike(ilkData[ilk].join).live() == 1, "IlkRegistry/ilk-not-live-use-remove-instead");
uint96 _class = ilkData[ilk].class;
require(_class == 1 || _class == 2, "IlkRegistry/invalid-class");
(address _pip,) = spot.ilks(ilk);
require(_pip != address(0), "IlkRegistry/pip-invalid");
ilkData[ilk].pip = _pip;
emit UpdateIlk(ilk);
}
// Force addition or update of a collateral type. (i.e. for RWA, etc.)
// Governance managed
function put(
bytes32 _ilk,
address _join,
address _gem,
uint256 _dec,
uint256 _class,
address _pip,
address _xlip,
string calldata _name,
string calldata _symbol
)
external auth {
require(_class != 0 && _class <= uint96(-1), "IlkRegistry/invalid-class");
require(_dec <= uint8(-1), "IlkRegistry/invalid-dec");
uint96 _pos;
if (ilkData[_ilk].class == 0) {
require(ilks.length < uint96(-1), "IlkRegistry/too-many-ilks");
ilks.push(_ilk);
_pos = uint96(ilks.length - 1);
emit AddIlk(_ilk);
} else {
_pos = ilkData[_ilk].pos;
emit UpdateIlk(_ilk);
}
ilkData[ilks[_pos]] = Ilk({
pos: _pos,
join: _join,
gem: _gem,
dec: uint8(_dec),
class: uint96(_class),
pip: _pip,
xlip: _xlip,
name: _name,
symbol: _symbol
});
}
function bytes32ToStr(bytes32 _bytes32) internal pure returns (string memory) {
bytes memory _bytesArray = new bytes(32);
for (uint256 i; i < 32; i++) {
_bytesArray[i] = _bytes32[i];
}
return string(_bytesArray);
}
} | Initialize the registry | constructor(address vat_, address dog_, address cat_, address spot_) public {
VatLike _vat = vat = VatLike(vat_);
dog = DogLike(dog_);
cat = CatLike(cat_);
spot = SpotLike(spot_);
require(dog.vat() == vat_, "IlkRegistry/invalid-dog-vat");
require(cat.vat() == vat_, "IlkRegistry/invalid-cat-vat");
require(spot.vat() == vat_, "IlkRegistry/invalid-spotter-vat");
require(_vat.wards(cat_) == 1, "IlkRegistry/cat-not-authorized");
require(_vat.wards(spot_) == 1, "IlkRegistry/spot-not-authorized");
require(_vat.live() == 1, "IlkRegistry/vat-not-live");
require(cat.live() == 1, "IlkRegistry/cat-not-live");
require(spot.live() == 1, "IlkRegistry/spot-not-live");
gemInfo = new GemInfo();
wards[msg.sender] = 1;
}
| 2,102,115 | [
1,
7520,
326,
4023,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
2867,
17359,
67,
16,
1758,
302,
717,
67,
16,
1758,
6573,
67,
16,
1758,
16463,
67,
13,
1071,
288,
203,
203,
3639,
25299,
8804,
389,
25012,
273,
17359,
273,
25299,
8804,
12,
25012,
67,
1769,
203,
3639,
302,
717,
273,
463,
717,
8804,
12,
20330,
67,
1769,
203,
3639,
6573,
273,
385,
270,
8804,
12,
2574,
67,
1769,
203,
3639,
16463,
273,
26523,
8804,
12,
19032,
67,
1769,
203,
203,
3639,
2583,
12,
20330,
18,
25012,
1435,
422,
17359,
67,
16,
1377,
315,
45,
80,
79,
4243,
19,
5387,
17,
20330,
17,
25012,
8863,
203,
3639,
2583,
12,
2574,
18,
25012,
1435,
422,
17359,
67,
16,
1377,
315,
45,
80,
79,
4243,
19,
5387,
17,
2574,
17,
25012,
8863,
203,
3639,
2583,
12,
19032,
18,
25012,
1435,
422,
17359,
67,
16,
377,
315,
45,
80,
79,
4243,
19,
5387,
17,
19032,
387,
17,
25012,
8863,
203,
3639,
2583,
24899,
25012,
18,
6397,
12,
2574,
67,
13,
422,
404,
16,
225,
315,
45,
80,
79,
4243,
19,
2574,
17,
902,
17,
8434,
8863,
203,
3639,
2583,
24899,
25012,
18,
6397,
12,
19032,
67,
13,
422,
404,
16,
315,
45,
80,
79,
4243,
19,
19032,
17,
902,
17,
8434,
8863,
203,
3639,
2583,
24899,
25012,
18,
16472,
1435,
422,
404,
16,
4202,
315,
45,
80,
79,
4243,
19,
25012,
17,
902,
17,
16472,
8863,
203,
3639,
2583,
12,
2574,
18,
16472,
1435,
422,
404,
16,
3639,
315,
45,
80,
79,
4243,
19,
2574,
17,
902,
17,
16472,
8863,
203,
3639,
2583,
12,
19032,
2
] |
./full_match/5/0xBe86f238d01455e07da5df6e60d879bF72Ed6995/sources/contracts/Counter.sol | import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; | import { Owned } from "solmate/src/auth/Owned.sol";
| 1,894,722 | [
1,
5666,
288,
14223,
6914,
289,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
3860,
19,
5460,
429,
18,
18281,
14432,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5666,
288,
14223,
11748,
289,
628,
315,
18281,
81,
340,
19,
4816,
19,
1944,
19,
5460,
329,
18,
18281,
14432,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Eliptic curve signature operations
*
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using his signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
}
/// @title Unidirectional Ether payment channels contract.
contract Unidirectional {
using SafeMath for uint256;
struct PaymentChannel {
address sender;
address receiver;
uint256 value; // Total amount of money deposited to the channel.
uint32 settlingPeriod; // How many blocks to wait for the receiver to claim her funds, after sender starts settling.
uint256 settlingUntil; // Starting with this block number, anyone can settle the channel.
}
mapping (bytes32 => PaymentChannel) public channels;
event DidOpen(bytes32 indexed channelId, address indexed sender, address indexed receiver, uint256 value);
event DidDeposit(bytes32 indexed channelId, uint256 deposit);
event DidClaim(bytes32 indexed channelId);
event DidStartSettling(bytes32 indexed channelId);
event DidSettle(bytes32 indexed channelId);
/*** ACTIONS AND CONSTRAINTS ***/
/// @notice Open a new channel between `msg.sender` and `receiver`, and do an initial deposit to the channel.
/// @param channelId Unique identifier of the channel to be created.
/// @param receiver Receiver of the funds, counter-party of `msg.sender`.
/// @param settlingPeriod Number of blocks to wait for receiver to `claim` her funds after the sender starts settling period (see `startSettling`).
/// After that period is over anyone could call `settle`, and move all the channel funds to the sender.
function open(bytes32 channelId, address receiver, uint32 settlingPeriod) public payable {
require(isAbsent(channelId));
channels[channelId] = PaymentChannel({
sender: msg.sender,
receiver: receiver,
value: msg.value,
settlingPeriod: settlingPeriod,
settlingUntil: 0
});
DidOpen(channelId, msg.sender, receiver, msg.value);
}
/// @notice Ensure `origin` address can deposit money into the channel identified by `channelId`.
/// @dev Constraint `deposit` call.
/// @param channelId Identifier of the channel.
/// @param origin Caller of `deposit` function.
function canDeposit(bytes32 channelId, address origin) public view returns(bool) {
PaymentChannel memory channel = channels[channelId];
bool isSender = channel.sender == origin;
return isOpen(channelId) && isSender;
}
/// @notice Add more money to the contract.
/// @param channelId Identifier of the channel.
function deposit(bytes32 channelId) public payable {
require(canDeposit(channelId, msg.sender));
channels[channelId].value += msg.value;
DidDeposit(channelId, msg.value);
}
/// @notice Ensure `origin` address can start settling the channel identified by `channelId`.
/// @dev Constraint `startSettling` call.
/// @param channelId Identifier of the channel.
/// @param origin Caller of `startSettling` function.
function canStartSettling(bytes32 channelId, address origin) public view returns(bool) {
PaymentChannel memory channel = channels[channelId];
bool isSender = channel.sender == origin;
return isOpen(channelId) && isSender;
}
/// @notice Sender initiates settling of the contract.
/// @dev Actually set `settlingUntil` field of the PaymentChannel structure.
/// @param channelId Identifier of the channel.
function startSettling(bytes32 channelId) public {
require(canStartSettling(channelId, msg.sender));
PaymentChannel storage channel = channels[channelId];
channel.settlingUntil = block.number + channel.settlingPeriod;
DidStartSettling(channelId);
}
/// @notice Ensure one can settle the channel identified by `channelId`.
/// @dev Check if settling period is over by comparing `settlingUntil` to a current block number.
/// @param channelId Identifier of the channel.
function canSettle(bytes32 channelId) public view returns(bool) {
PaymentChannel memory channel = channels[channelId];
bool isWaitingOver = isSettling(channelId) && block.number >= channel.settlingUntil;
return isSettling(channelId) && isWaitingOver;
}
/// @notice Move the money to sender, and close the channel.
/// After the settling period is over, and receiver has not claimed the funds, anyone could call that.
/// @param channelId Identifier of the channel.
function settle(bytes32 channelId) public {
require(canSettle(channelId));
PaymentChannel storage channel = channels[channelId];
channel.sender.transfer(channel.value);
delete channels[channelId];
DidSettle(channelId);
}
/// @notice Ensure `origin` address can claim `payment` amount on channel identified by `channelId`.
/// @dev Check if `signature` is made by sender part of the channel, and is for payment promise (see `paymentDigest`).
/// @param channelId Identifier of the channel.
/// @param payment Amount claimed.
/// @param origin Caller of `claim` function.
/// @param signature Signature for the payment promise.
function canClaim(bytes32 channelId, uint256 payment, address origin, bytes signature) public view returns(bool) {
PaymentChannel memory channel = channels[channelId];
bool isReceiver = origin == channel.receiver;
bytes32 hash = recoveryPaymentDigest(channelId, payment);
bool isSigned = channel.sender == ECRecovery.recover(hash, signature);
return isReceiver && isSigned;
}
/// @notice Claim the funds, and close the channel.
/// @dev Can be claimed by channel receiver only. Guarded by `canClaim`.
/// @param channelId Identifier of the channel.
/// @param payment Amount claimed.
/// @param signature Signature for the payment promise.
function claim(bytes32 channelId, uint256 payment, bytes signature) public {
require(canClaim(channelId, payment, msg.sender, signature));
PaymentChannel memory channel = channels[channelId];
if (payment >= channel.value) {
channel.receiver.transfer(channel.value);
} else {
channel.receiver.transfer(payment);
channel.sender.transfer(channel.value.sub(payment));
}
delete channels[channelId];
DidClaim(channelId);
}
/*** CHANNEL STATE ***/
/// @notice Check if the channel is present: in open or settling state.
/// @param channelId Identifier of the channel.
function isPresent(bytes32 channelId) public view returns(bool) {
return !isAbsent(channelId);
}
/// @notice Check if the channel is not present.
/// @param channelId Identifier of the channel.
function isAbsent(bytes32 channelId) public view returns(bool) {
PaymentChannel memory channel = channels[channelId];
return channel.sender == 0;
}
/// @notice Check if the channel is in settling state: waits till the settling period is over.
/// @dev It is settling, if `settlingUntil` is set to non-zero.
/// @param channelId Identifier of the channel.
function isSettling(bytes32 channelId) public view returns(bool) {
PaymentChannel memory channel = channels[channelId];
return channel.settlingUntil != 0;
}
/// @notice Check if the channel is open: present and not settling.
/// @param channelId Identifier of the channel.
function isOpen(bytes32 channelId) public view returns(bool) {
return isPresent(channelId) && !isSettling(channelId);
}
/*** PAYMENT DIGEST ***/
/// @return Hash of the payment promise to sign.
/// @param channelId Identifier of the channel.
/// @param payment Amount to send, and to claim later.
function paymentDigest(bytes32 channelId, uint256 payment) public view returns(bytes32) {
return keccak256(address(this), channelId, payment);
}
/// @return Actually signed hash of the payment promise, considering "Ethereum Signed Message" prefix.
/// @param channelId Identifier of the channel.
/// @param payment Amount to send, and to claim later.
function recoveryPaymentDigest(bytes32 channelId, uint256 payment) internal view returns(bytes32) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
return keccak256(prefix, paymentDigest(channelId, payment));
}
} | @return Actually signed hash of the payment promise, considering "Ethereum Signed Message" prefix. @param channelId Identifier of the channel. @param payment Amount to send, and to claim later. | function recoveryPaymentDigest(bytes32 channelId, uint256 payment) internal view returns(bytes32) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
return keccak256(prefix, paymentDigest(channelId, payment));
}
| 7,780,617 | [
1,
2463,
4603,
3452,
6726,
1651,
434,
326,
5184,
5109,
16,
24453,
315,
41,
18664,
379,
16724,
2350,
6,
1633,
18,
225,
27709,
10333,
434,
326,
1904,
18,
225,
5184,
16811,
358,
1366,
16,
471,
358,
7516,
5137,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
11044,
6032,
9568,
12,
3890,
1578,
27709,
16,
2254,
5034,
5184,
13,
2713,
1476,
1135,
12,
3890,
1578,
13,
288,
203,
3639,
1731,
3778,
1633,
273,
1548,
92,
3657,
41,
18664,
379,
16724,
2350,
5581,
82,
1578,
14432,
203,
3639,
327,
417,
24410,
581,
5034,
12,
3239,
16,
5184,
9568,
12,
4327,
548,
16,
5184,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.0;
import "./FundToken.sol";
// questões em aberto:
// * este contrato é que cria a carteira dos operadores?
// * já viram https://github.com/TokenMarketNet/ico/blob/master/contracts/GnosisWallet.sol ?
// * operadores
// * eventos
// * que poderes o owner teria aqui? Um setState?
/**
* Manages the funds of a group of investors, following a simple workflow.
*
* This contract emits ERC20 tokens (FUND) for the ethers deposited. These
* FUNDs can be exchanged between the investors or eventually redeemed for the
* returns on the investment.
*/
contract Funds is FundToken {
address private owner;
address private operatingWallet;
uint private investingDate;
uint private totalInvested;
uint private totalReceived;
uint private minimumInvestment;
/**
* The states of this contract. Each enables a certain set of operations
*
* * `Open` means that this contract is taking investors.
* * `Investing` is when the investors' money is in the operating wallet,
* and this contract is awaiting the returns.
* * `Finished` means that the returns have been paid, and now the investors
* can get their share.
*/
enum State { Open, Investing, Finished }
State private state;
/** Fired when the state changes from `from` to `to`. */
event StateChanged(State from, State to);
/** Fired when the operating wallet deposits `value` weis back. */
event ReturnsReceived(uint value);
/** Fired when the operating wallet changes. */
event OperatingWalletChanged(address oldWallet, address newWallet);
/** Creates this contract, with `msg.sender` as the `owner`. */
function Funds(uint _minimumInvestment, uint openDurationInDays) public {
owner = msg.sender;
minimumInvestment = _minimumInvestment;
investingDate = now + (openDurationInDays * 1 days);
state = State.Open;
}
/*
* Modifiers
*/
/** Checks if this contract is in state `_state`. */
modifier onlyDuring(State _state) {
require(state == _state);
_;
}
/** Checks if the function is being called by `_address`. */
modifier onlyBy(address _address) {
require(msg.sender == _address);
_;
}
/** Verifies if the function is called after `date`. */
modifier onlyAfter(uint date) {
require(now >= date);
_;
}
/*
* Properties
*/
/** Returns this contract's owner. */
function getOwner() public view returns (address) {
return owner;
}
/** Returns when `State.Investing` is available. */
function getInvestingDate() public view returns (uint) {
return investingDate;
}
/**
* Returns the current operating wallet, which is where the funds will be
* sent and where the returns will come from.
*/
function getOperatingWallet() public view returns (address) {
return operatingWallet;
}
/**
* Changes the operating wallet. Can be called only by the owner.
*
* @param wallet The new wallet.
*/
function setOperatingWallet(address wallet) public onlyBy(owner) {
address old = operatingWallet;
operatingWallet = wallet;
OperatingWalletChanged(old, wallet);
}
/** Returns the current state. */
function getState() public view returns (State) {
return state;
}
/** Changes the current state to `to`, and fires `StateChanged`. */
function setState(State to) internal {
State from = state;
state = to;
StateChanged(from, to);
}
function getMinimumInvestment() public view returns (uint) {
return minimumInvestment;
}
/**
* The total amount invested in this contract, in weis. This value should
* be set in stone after State.Open.
*
* This value is useful because the contract's balance and `totalSupply()`
* can change after `State.Open`, which would distort the ROI.
*/
function getTotalInvested() public view returns (uint) {
if (state == State.Open) {
return totalSupply();
} else {
return totalInvested;
}
}
/**
* The total amount returned after the investment, in weis.
*/
function getTotalReceived() public view returns (uint) {
return totalReceived;
}
/*
* OPEN operations
*/
/**
* Stores and registers the amount paid by `msg.sender`, who gets in
* return a number of FUND tokens equal to the amount paid.
*
* After `State.Open`, this contract is closed for further investments,
* although FUND owners can still exchange FUND tokens afterwards :)
*/
function invest() public payable onlyDuring(State.Open) {
require(balances[msg.sender] + msg.value >= minimumInvestment);
mint(msg.sender, msg.value);
}
/**
* Exchanges `value` FUND tokens (which are subsequently burned) from
* `msg.sender` for `value` weis.
*
* `msg.sender` can't return more tokens than they actually own.
*
* @param value The amount of FUND tokens to exchange.
*/
function divest(uint value) public onlyDuring(State.Open) {
require(balances[msg.sender] == value || balances[msg.sender] - value >= minimumInvestment);
burn(msg.sender, value);
msg.sender.transfer(value);
}
/**
* Transfers all the ethers in this contract to the operating wallet, and
* changes the state to `State.Investing`.
*
* Fires `StateChanged`.
*/
function start()
public
onlyDuring(State.Open)
onlyAfter(investingDate)
{
require(operatingWallet > 0); // operatingWallet must be set by now
require(this.balance >= minimumInvestment); // no point in investing nothing
totalInvested = this.balance;
operatingWallet.transfer(totalInvested);
setState(State.Investing);
}
/*
* INVESTING operations
*/
/**
* Stores any early returns from the investments.
*
* Fires `ReturnsReceived`.
*/
function receive()
public
payable
onlyDuring(State.Investing)
onlyBy(operatingWallet)
{
require(this.balance + msg.value > this.balance); // overflow
ReturnsReceived(msg.value);
}
/**
* Ends `State.Investing`, and transitions to `State.Finished`. After calling
* this function, no more funds can be `receive`d.
*
* Fires `StateChanged`.
*/
function finish()
public
onlyDuring(State.Investing)
onlyBy(operatingWallet)
{
totalReceived = this.balance;
setState(State.Finished);
}
/*
* FINISHED operations
*/
/**
* Exchanges all `msg.sender`'s FUND tokens for their returns.
*
* Errors if `msg.sender` has no FUNDs to exchange.
*/
function withdraw() public onlyDuring(State.Finished) {
require(balances[msg.sender] > 0);
uint result = (balances[msg.sender] * totalReceived) / totalInvested;
burn(msg.sender, balances[msg.sender]);
msg.sender.transfer(result);
}
/**
* Sends the last weis in this contract to the owner. These weis come from
* the imprecision in the ROI integer division, and would be otherwise stuck
* in this contract.
*
* Can be called only after all FUNDs have been redeemed.
*/
function drain()
public
onlyDuring(State.Finished)
onlyBy(owner)
{
require(totalSupply() == 0);
uint debris = this.balance;
owner.transfer(debris);
}
} | * The states of this contract. Each enables a certain set of operations `Open` means that this contract is taking investors. `Investing` is when the investors' money is in the operating wallet, and this contract is awaiting the returns. `Finished` means that the returns have been paid, and now the investors can get their share./ | enum State { Open, Investing, Finished }
| 12,741,561 | [
1,
1986,
5493,
434,
333,
6835,
18,
8315,
19808,
279,
8626,
444,
434,
5295,
225,
1375,
3678,
68,
4696,
716,
333,
6835,
353,
13763,
2198,
395,
1383,
18,
225,
1375,
3605,
10100,
68,
353,
1347,
326,
2198,
395,
1383,
11,
15601,
353,
316,
326,
16929,
9230,
16,
565,
471,
333,
6835,
353,
4273,
310,
326,
1135,
18,
225,
1375,
10577,
68,
4696,
716,
326,
1135,
1240,
2118,
30591,
16,
471,
2037,
326,
2198,
395,
1383,
565,
848,
336,
3675,
7433,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2792,
3287,
288,
3502,
16,
5454,
10100,
16,
29745,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY344() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF995(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER795(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE796(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE408(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM856(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function DECIMALS615() external view returns (uint); //inject NONSTANDARD NAMING
event TRANSFER370(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL858(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD697(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB109(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB109(a, b, "SafeMath: subtraction overflow");
}
function SUB109(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL960(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV581(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV581(a, b, "SafeMath: division by zero");
}
function DIV581(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD970(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD970(a, b, "SafeMath: modulo by zero");
}
function MOD970(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT908(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE655(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE370(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER212(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN170(token, abi.encodeWithSelector(token.TRANSFER795.selector, to, value));
}
function SAFETRANSFERFROM22(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN170(token, abi.encodeWithSelector(token.TRANSFERFROM856.selector, from, to, value));
}
function SAFEAPPROVE493(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE796(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN170(token, abi.encodeWithSelector(token.APPROVE408.selector, spender, value));
}
function CALLOPTIONALRETURN170(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT908(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface Controller {
function VAULTS291(address) external view returns (address); //inject NONSTANDARD NAMING
}
interface Balancer {
function JOINPOOL849(uint,uint[] calldata) external; //inject NONSTANDARD NAMING
function EXITPOOL804(uint,uint[] calldata) external; //inject NONSTANDARD NAMING
}
interface MStable {
function MINT666(address, uint) external; //inject NONSTANDARD NAMING
function REDEEM500(address, uint) external; //inject NONSTANDARD NAMING
}
contract StrategyBalancerMTA {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address constant public want295 = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); //inject NONSTANDARD NAMING
address constant public musd674 = address(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5); //inject NONSTANDARD NAMING
address constant public balancer837 = address(0x72Cd8f4504941Bf8c5a21d1Fd83A96499FD71d2C); //inject NONSTANDARD NAMING
address public governance;
address public controller;
bool public breaker = false;
// Supply tracks the number of `want` that we have lent out of other distro's
uint public supply = 0;
constructor(address _controller) public {
governance = msg.sender;
controller = _controller;
}
function SETBREAKER384(bool _breaker) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
breaker = _breaker;
}
function DEPOSIT98() external { //inject NONSTANDARD NAMING
require(breaker == false, "!breaker");
uint _balance = IERC20(want295).BALANCEOF995(address(this));
uint _want = _balance.DIV581(2);
IERC20(want295).SAFEAPPROVE493(musd674, 0);
IERC20(want295).SAFEAPPROVE493(musd674, _want);
uint _before = _balance;
MStable(musd674).MINT666(want295, _want);
uint _after = IERC20(want295).BALANCEOF995(address(this));
supply = supply.ADD697(_before.SUB109(_after));
uint _musd = IERC20(musd674).BALANCEOF995(address(this));
uint _total = IERC20(balancer837).TOTALSUPPLY344();
uint _balancerMUSD = IERC20(musd674).BALANCEOF995(balancer837);
uint _poolAmountMUSD = _musd.MUL960(_total).DIV581(_balancerMUSD);
uint _balancerUSDC = IERC20(want295).BALANCEOF995(balancer837);
uint _poolAmountUSDC = _want.MUL960(_total).DIV581(_balancerUSDC);
uint _poolAmountOut = _poolAmountMUSD;
if (_poolAmountUSDC < _poolAmountOut) {
_poolAmountOut = _poolAmountUSDC;
}
IERC20(want295).SAFEAPPROVE493(balancer837, 0);
IERC20(want295).SAFEAPPROVE493(balancer837, _want);
IERC20(musd674).SAFEAPPROVE493(balancer837, 0);
IERC20(musd674).SAFEAPPROVE493(balancer837, _musd);
uint[] memory _maxAmountIn = new uint[](2);
_maxAmountIn[0] = _musd;
_maxAmountIn[1] = _want;
_before = IERC20(want295).BALANCEOF995(address(this));
Balancer(balancer837).JOINPOOL849(_poolAmountOut, _maxAmountIn);
_after = IERC20(want295).BALANCEOF995(address(this));
supply = supply.ADD697(_before.SUB109(_after));
}
// Controller only function for creating additional rewards from dust
function WITHDRAW505(IERC20 _asset) external returns (uint balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
require(address(_asset) != want295, "!c");
require(address(_asset) != musd674, "!c");
require(address(_asset) != balancer837, "!c");
balance = _asset.BALANCEOF995(address(this));
_asset.SAFETRANSFER212(controller, balance);
}
function WITHDRAWM660(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING
if (_amount > supply) {
// Pool made too much profit, so we reset to 0 to avoid revert
supply = 0;
} else {
supply = supply.SUB109(_amount);
}
uint _before = IERC20(want295).BALANCEOF995(address(this));
MStable(musd674).REDEEM500(want295, _amount);
uint _after = IERC20(want295).BALANCEOF995(address(this));
return _after.SUB109(_before);
}
function WITHDRAWBPT914(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING
uint _calc = CALCULATERATIO430(_amount);
_amount = _amount.SUB109(_amount.MUL960(10).DIV581(10000));
return _WITHDRAWSOME884(_calc, _amount);
}
// Withdraw partial funds, normally used with a vault withdrawal
function WITHDRAW505(uint _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
uint _balance = IERC20(want295).BALANCEOF995(address(this));
if (_balance < _amount) {
uint _musd = NORMALIZE117(IERC20(musd674).BALANCEOF995(address(this)));
uint _remainder = _amount.SUB109(_balance);
if (_musd > 0) {
if (_musd > _remainder) {
_amount = WITHDRAWM660(_remainder);
_amount = _amount.ADD697(_balance);
} else {
_remainder = _remainder.SUB109(_musd);
uint _withdrew = WITHDRAWM660(_musd);
_amount = _withdrew.ADD697(_balance);
_withdrew = WITHDRAWBPT914(_remainder);
_amount = _amount.ADD697(_withdrew);
}
} else {
_amount = WITHDRAWBPT914(_remainder);
_amount = _amount.ADD697(_balance);
}
}
IERC20(want295).SAFETRANSFER212(controller, _amount);
}
function REDEEM500() external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
uint _balance = NORMALIZE117(IERC20(musd674).BALANCEOF995(address(this)));
if (_balance > supply) {
// Pool made too much profit, so we reset to 0 to avoid revert
supply = 0;
} else {
supply = supply.SUB109(_balance);
}
MStable(musd674).REDEEM500(want295, _balance);
}
// Withdraw all funds, normally used when migrating strategies
function WITHDRAWALL744() external returns (uint balance) { //inject NONSTANDARD NAMING
require(msg.sender == controller, "!controller");
_WITHDRAWALL952();
balance = IERC20(want295).BALANCEOF995(address(this));
IERC20(want295).SAFETRANSFER212(controller, balance);
}
function _WITHDRAWALL952() internal { //inject NONSTANDARD NAMING
uint _bpt = IERC20(balancer837).BALANCEOF995(address(this));
uint[] memory _minAmountOut = new uint[](2);
_minAmountOut[0] = 0;
_minAmountOut[1] = 0;
uint _before = IERC20(want295).BALANCEOF995(address(this));
Balancer(balancer837).EXITPOOL804(_bpt, _minAmountOut);
uint _after = IERC20(want295).BALANCEOF995(address(this));
uint _diff = _after.SUB109(_before);
if (_diff > supply) {
// Pool made too much profit, so we reset to 0 to avoid revert
supply = 0;
} else {
supply = supply.SUB109(_after.SUB109(_before));
}
uint _musd = IERC20(musd674).BALANCEOF995(address(this));
// This one is the exception because it assumes we can redeem 1 USDC
_diff = NORMALIZE117(_musd);
if (_diff > supply) {
// Pool made too much profit, so we reset to 0 to avoid revert
supply = 0;
} else {
supply = supply.SUB109(_diff);
}
MStable(musd674).REDEEM500(want295, _diff);
}
function CALCULATERATIO430(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING
uint _musd = NORMALIZE117(IERC20(musd674).BALANCEOF995(balancer837));
uint _want = IERC20(want295).BALANCEOF995(balancer837);
uint _total = _musd.ADD697(_want);
uint _ratio = _amount.MUL960(_want).DIV581(_total);
return _ratio;
}
function _WITHDRAWSOME884(uint256 _amount, uint _max) internal returns (uint) { //inject NONSTANDARD NAMING
uint _redeem = IERC20(balancer837).TOTALSUPPLY344().MUL960(_amount).DIV581(IERC20(want295).BALANCEOF995(balancer837));
if (_redeem > IERC20(balancer837).BALANCEOF995(address(this))) {
_redeem = IERC20(balancer837).BALANCEOF995(address(this));
}
uint[] memory _minAmountOut = new uint[](2);
_minAmountOut[0] = 0;
_minAmountOut[1] = 0;
uint _before = IERC20(want295).BALANCEOF995(address(this));
uint _mBefore = IERC20(musd674).BALANCEOF995(address(this));
Balancer(balancer837).EXITPOOL804(_redeem, _minAmountOut);
uint _mAfter = IERC20(musd674).BALANCEOF995(address(this));
uint _after = IERC20(want295).BALANCEOF995(address(this));
uint _musd = _mAfter.SUB109(_mBefore);
uint _withdrew = _after.SUB109(_before);
if (_withdrew > supply) {
// Pool made too much profit, so we reset to 0 to avoid revert
supply = 0;
} else {
supply = supply.SUB109(_withdrew);
}
_musd = NORMALIZE117(_musd);
if (_musd > supply) {
// Pool made too much profit, so we reset to 0 to avoid revert
supply = 0;
} else {
supply = supply.SUB109(_musd);
}
_before = IERC20(want295).BALANCEOF995(address(this));
MStable(musd674).REDEEM500(want295, _musd);
_after = IERC20(want295).BALANCEOF995(address(this));
_withdrew = _withdrew.ADD697(_after.SUB109(_before));
// Apply the fee as a difference
_withdrew = _withdrew.SUB109(_musd.SUB109(_after.SUB109(_before)));
if (_withdrew > _max) {
_withdrew = _max;
}
return _withdrew;
}
function NORMALIZE117(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING
return _amount.MUL960(10**IERC20(want295).DECIMALS615()).DIV581(10**IERC20(musd674).DECIMALS615());
}
function BALANCEOF995() public view returns (uint) { //inject NONSTANDARD NAMING
return IERC20(want295).BALANCEOF995(address(this))
.ADD697(supply);
}
function SETGOVERNANCE741(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function SETCONTROLLER847(address _controller) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
} | inject NONSTANDARD NAMING
| event APPROVAL858(address indexed owner, address indexed spender, uint256 value); | 5,414,246 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
14410,
3373,
2669,
7140,
28,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-05-05
*/
/*
.'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''..
.;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,.
';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,.
';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,.
...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''..
.,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. .....
.;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,..
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. ....
..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,.
..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'.
...'.. .';;;;;;;;;;;;;;,,,'.
...............
*/
// https://github.com/trusttoken/smart-contracts
// 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;
}
}
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
/**
* @dev Return true if and only if the contract has been initialized
* @return whether the contract has been initialized
*/
function isInitialized() public view returns (bool) {
return initialized;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
/**
* @title UpgradeableClaimable
* @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. Since
* this contract combines Claimable and UpgradableOwnable contracts, ownership
* can be later change via 2 step method {transferOwnership} and {claimOwnership}
*
* 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 UpgradeableClaimable is Initializable, Context {
address private _owner;
address private _pendingOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting a custom initial owner of choice.
* @param __owner Initial owner of contract to be set.
*/
function initialize(address __owner) internal initializer {
_owner = __owner;
emit OwnershipTransferred(address(0), __owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view returns (address) {
return _pendingOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == _pendingOwner, "Ownable: caller is not the pending owner");
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(_owner, _pendingOwner);
_owner = _pendingOwner;
_pendingOwner = address(0);
}
}
/**
* @title ImplementationReference
* @dev This contract is made to serve a simple purpose only.
* To hold the address of the implementation contract to be used by proxy.
* The implementation address, is changeable anytime by the owner of this contract.
*/
contract ImplementationReference is UpgradeableClaimable {
address public implementation;
/**
* @dev Event to show that implementation address has been changed
* @param newImplementation New address of the implementation
*/
event ImplementationChanged(address newImplementation);
/**
* @dev Set initial ownership and implementation address
* @param _implementation Initial address of the implementation
*/
constructor(address _implementation) public {
UpgradeableClaimable.initialize(msg.sender);
implementation = _implementation;
}
/**
* @dev Function to change the implementation address, which can be called only by the owner
* @param newImplementation New address of the implementation
*/
function setImplementation(address newImplementation) external onlyOwner {
implementation = newImplementation;
emit ImplementationChanged(newImplementation);
}
}
/**
* @title OwnedProxyWithReference
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
* Its structure makes it easy for a group of contracts alike, to share an implementation and to change it easily for all of them at once
*/
contract OwnedProxyWithReference {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Event to show ownership transfer is pending
* @param currentOwner representing the address of the current owner
* @param pendingOwner representing the address of the pending owner
*/
event NewPendingOwner(address currentOwner, address pendingOwner);
/**
* @dev Event to show implementation reference has been changed
* @param implementationReference address of the new implementation reference contract
*/
event ImplementationReferenceChanged(address implementationReference);
// Storage position of the owner and pendingOwner and implementationReference of the contract
// This is made to ensure, that memory spaces do not interfere with each other
bytes32 private constant proxyOwnerPosition = 0x6279e8199720cf3557ecd8b58d667c8edc486bd1cf3ad59ea9ebdfcae0d0dfac; //keccak256("trueUSD.proxy.owner");
bytes32 private constant pendingProxyOwnerPosition = 0x8ddbac328deee8d986ec3a7b933a196f96986cb4ee030d86cc56431c728b83f4; //keccak256("trueUSD.pending.proxy.owner");
bytes32 private constant implementationReferencePosition = keccak256("trueFiPool.implementation.reference"); //keccak256("trueFiPool.implementation.reference");
/**
* @dev the constructor sets the original owner of the contract to the sender account.
* @param _owner Initial owner of the proxy
* @param _implementationReference initial ImplementationReference address
*/
constructor(address _owner, address _implementationReference) public {
_setUpgradeabilityOwner(_owner);
_changeImplementationReference(_implementationReference);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner(), "only Proxy Owner");
_;
}
/**
* @dev Throws if called by any account other than the pending owner.
*/
modifier onlyPendingProxyOwner() {
require(msg.sender == pendingProxyOwner(), "only pending Proxy Owner");
_;
}
/**
* @dev Tells the address of the owner
* @return owner the address of the owner
*/
function proxyOwner() public view returns (address owner) {
bytes32 position = proxyOwnerPosition;
assembly {
owner := sload(position)
}
}
/**
* @dev Tells the address of the owner
* @return pendingOwner the address of the pending owner
*/
function pendingProxyOwner() public view returns (address pendingOwner) {
bytes32 position = pendingProxyOwnerPosition;
assembly {
pendingOwner := sload(position)
}
}
/**
* @dev Sets the address of the owner
* @param newProxyOwner New owner to be set
*/
function _setUpgradeabilityOwner(address newProxyOwner) internal {
bytes32 position = proxyOwnerPosition;
assembly {
sstore(position, newProxyOwner)
}
}
/**
* @dev Sets the address of the owner
* @param newPendingProxyOwner New pending owner address
*/
function _setPendingUpgradeabilityOwner(address newPendingProxyOwner) internal {
bytes32 position = pendingProxyOwnerPosition;
assembly {
sstore(position, newPendingProxyOwner)
}
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* changes the pending owner to newOwner. But doesn't actually transfer
* @param newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address newOwner) external onlyProxyOwner {
require(newOwner != address(0));
_setPendingUpgradeabilityOwner(newOwner);
emit NewPendingOwner(proxyOwner(), newOwner);
}
/**
* @dev Allows the pendingOwner to claim ownership of the proxy
*/
function claimProxyOwnership() external onlyPendingProxyOwner {
emit ProxyOwnershipTransferred(proxyOwner(), pendingProxyOwner());
_setUpgradeabilityOwner(pendingProxyOwner());
_setPendingUpgradeabilityOwner(address(0));
}
/**
* @dev Allows the proxy owner to change the contract holding address of implementation.
* @param _implementationReference representing the address contract, which holds implementation.
*/
function changeImplementationReference(address _implementationReference) public virtual onlyProxyOwner {
_changeImplementationReference(_implementationReference);
}
/**
* @dev Get the address of current implementation.
* @return Returns address of implementation contract
*/
function implementation() public view returns (address) {
bytes32 position = implementationReferencePosition;
address implementationReference;
assembly {
implementationReference := sload(position)
}
return ImplementationReference(implementationReference).implementation();
}
/**
* @dev Fallback functions allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
fallback() external payable {
proxyCall();
}
/**
* @dev This fallback function gets called only when this contract is called without any calldata e.g. send(), transfer()
* This would also trigger receive() function on called implementation
*/
receive() external payable {
proxyCall();
}
/**
* @dev Performs a low level call, to the contract holding all the logic, changing state on this contract at the same time
*/
function proxyCall() internal {
address impl = implementation();
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), impl, ptr, calldatasize(), 0, 0)
returndatacopy(ptr, 0, returndatasize())
switch result
case 0 {
revert(ptr, returndatasize())
}
default {
return(ptr, returndatasize())
}
}
}
/**
* @dev Function to internally change the contract holding address of implementation.
* @param _implementationReference representing the address contract, which holds implementation.
*/
function _changeImplementationReference(address _implementationReference) internal virtual {
bytes32 position = implementationReferencePosition;
assembly {
sstore(position, _implementationReference)
}
emit ImplementationReferenceChanged(address(_implementationReference));
}
} | * @dev Allows the current owner to transfer control of the contract to a newOwner. changes the pending owner to newOwner. But doesn't actually transfer @param newOwner The address to transfer ownership to./ | function transferProxyOwnership(address newOwner) external onlyProxyOwner {
require(newOwner != address(0));
_setPendingUpgradeabilityOwner(newOwner);
emit NewPendingOwner(proxyOwner(), newOwner);
}
| 21,605 | [
1,
19132,
326,
783,
3410,
358,
7412,
3325,
434,
326,
6835,
358,
279,
394,
5541,
18,
3478,
326,
4634,
3410,
358,
394,
5541,
18,
12484,
3302,
1404,
6013,
7412,
225,
394,
5541,
1021,
1758,
358,
7412,
23178,
358,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
7412,
3886,
5460,
12565,
12,
2867,
394,
5541,
13,
3903,
1338,
3886,
5541,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
10019,
203,
3639,
389,
542,
8579,
10784,
2967,
5541,
12,
2704,
5541,
1769,
203,
3639,
3626,
1166,
8579,
5541,
12,
5656,
5541,
9334,
394,
5541,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xf045Ab73c8b99E14180a513fAC4Ef4f717f0E6fd/sources/ERC20.sol | * @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide 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 ATP is Context, IERC20 {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual returns (string memory) {
return _name;
}
function symbol() public view virtual returns (string memory) {
return _symbol;
}
function decimals() public view virtual returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
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);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | 14,193,433 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
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,
16351,
432,
11130,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
203,
203,
565,
3885,
261,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
5024,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
5024,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
5024,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
6549,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
70,
26488,
63,
4631,
15533,
203,
565,
289,
203,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
1071,
5024,
3849,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {IERC20Ext} from '@kyber.network/utils-sc/contracts/IERC20Ext.sol';
contract MockSimpleKyberProxy {
IERC20Ext public knc;
// swap ether to knc
// 1 ETH = 1 KNC
function swapEtherToToken(IERC20Ext token, uint256 minConversionRate)
external
payable
returns (uint256)
{
token;
minConversionRate;
knc.transfer(msg.sender, msg.value);
return msg.value;
}
// swap token to knc
// approval should be given to proxy
function swapTokenToToken(
IERC20Ext src,
uint256 srcAmount,
IERC20Ext dest,
uint256 minConversionRate
) external returns (uint256) {
dest;
minConversionRate;
src.transferFrom(msg.sender, address(this), srcAmount);
knc.transfer(msg.sender, srcAmount);
return srcAmount;
}
function setKncAddress(IERC20Ext _knc) public {
knc = _knc;
}
}
| swap token to knc approval should be given to proxy | function swapTokenToToken(
IERC20Ext src,
uint256 srcAmount,
IERC20Ext dest,
uint256 minConversionRate
) external returns (uint256) {
dest;
minConversionRate;
src.transferFrom(msg.sender, address(this), srcAmount);
knc.transfer(msg.sender, srcAmount);
return srcAmount;
}
| 13,044,880 | [
1,
22270,
1147,
358,
417,
14202,
23556,
1410,
506,
864,
358,
2889,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
7720,
1345,
774,
1345,
12,
203,
565,
467,
654,
39,
3462,
2482,
1705,
16,
203,
565,
2254,
5034,
1705,
6275,
16,
203,
565,
467,
654,
39,
3462,
2482,
1570,
16,
203,
565,
2254,
5034,
1131,
6814,
4727,
203,
225,
262,
3903,
1135,
261,
11890,
5034,
13,
288,
203,
565,
1570,
31,
203,
565,
1131,
6814,
4727,
31,
203,
565,
1705,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
1705,
6275,
1769,
203,
565,
417,
14202,
18,
13866,
12,
3576,
18,
15330,
16,
1705,
6275,
1769,
203,
565,
327,
1705,
6275,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/84531/0x91Ac29cb37E56C222852DBa1d8486956cCb1FE8a/sources/contracts/LinearUnlock.sol | * @notice Locks tokens into the claimable pool @param _amount Amount of tokens to be locked/ | function _lockTokens(uint256 _amount) internal {
(bool transferSuccess, ) = tokenAddress.call(
abi.encodeWithSignature(
"transferFrom(address,address,uint256)",
msg.sender,
address(this),
_amount
)
);
require(transferSuccess, "Cannot transfer ERC20");
}
| 16,683,778 | [
1,
19159,
2430,
1368,
326,
7516,
429,
2845,
225,
389,
8949,
16811,
434,
2430,
358,
506,
8586,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
739,
5157,
12,
11890,
5034,
389,
8949,
13,
2713,
288,
203,
3639,
261,
6430,
7412,
4510,
16,
262,
273,
1147,
1887,
18,
1991,
12,
203,
5411,
24126,
18,
3015,
1190,
5374,
12,
203,
7734,
315,
13866,
1265,
12,
2867,
16,
2867,
16,
11890,
5034,
2225,
16,
203,
7734,
1234,
18,
15330,
16,
203,
7734,
1758,
12,
2211,
3631,
203,
7734,
389,
8949,
203,
5411,
262,
203,
3639,
11272,
203,
3639,
2583,
12,
13866,
4510,
16,
315,
4515,
7412,
4232,
39,
3462,
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
] |
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "./FomajPrizePool.sol";
/**
* @title Fomaj
*/
contract Fomaj is Ownable, Pausable, ReentrancyGuard {
using SafeERC20 for IERC20;
Config public config;
uint256 public currentRoundNumber;
bool public genesisStartOnce = false;
uint256 public oracleLatestRoundId; // converted from uint80 (Chainlink)
uint256 public oracleUpdateAllowance; // seconds
mapping (address => UserInfo) public userInfo;
mapping(uint256 => mapping(address => BetInfo)) public ledger;
mapping(uint256 => Round) public rounds;
struct Config {
IERC20 fmjToken;
FomajPrizePool prizePool;
uint256 minPrizeAmount;
int256 betRange;
uint256 closeTimeMultiplier;
AggregatorV3Interface oracle;
uint256 minStakeAmount;
uint256 stakeLockDuration;
uint256 minBetAmount;
uint256 intervalSeconds;
uint256 bufferSeconds;
}
enum RoundStatus {
Invalid,
Live,
Expired,
Cancelled
}
struct UserInfo {
uint256 stakedAmount;
uint256 unlockTimestamp;
uint256[] userRounds;
}
struct BetInfo {
Position position;
uint256 amount;
bool betAmountClaimed;
bool winningsClaimed;
}
enum Position {
None,
Bull,
Bear,
Flat
}
struct RoundAmounts {
uint256 bullAmount;
uint256 bearAmount;
uint256 flatAmount;
uint256 totalAmount;
}
struct RoundPrices {
int256 closePrice;
int256 flatMinPrice;
int256 flatMaxPrice;
}
struct RoundTimestamps {
uint256 startTimestamp;
uint256 lockTimestamp;
uint256 closeTimestamp;
}
struct RoundOracleIds {
uint256 startOracleId;
uint256 lockOracleId;
uint256 closeOracleId;
}
enum RewardStatus {
NotCalculated,
Calculated,
NoWinners,
Cancelled
}
struct RoundRewards {
RewardStatus status;
Position winner;
uint256 amount;
}
struct Round {
uint256 roundNumber;
RoundStatus status;
RoundPrices prices;
RoundOracleIds oracleIds;
RoundTimestamps timestamps;
RoundAmounts amounts;
RoundRewards rewards;
}
event KickOff(
Config _config
);
event ChangeOwner(address indexed newOwner);
event Staked(address indexed staker, uint256 amount, uint256 totalStaked);
event UnStaked(address indexed staker, uint256 amount);
event BetBear(address indexed sender, uint256 indexed epoch, uint256 amount);
event BetBull(address indexed sender, uint256 indexed epoch, uint256 amount);
event BetFlat(address indexed sender, uint256 indexed epoch, uint256 amount);
event EndRound(uint256 indexed roundNumber, uint256 indexed roundId, int256 price);
event StartRound(uint256 indexed roundNumber, uint256 indexed roundId, int256 price);
modifier notContract() {
require(!_isContract(msg.sender), "Contract not allowed");
require(msg.sender == tx.origin, "Proxy contract not allowed");
_;
}
modifier hasStakedEnough() {
require(userInfo[msg.sender].stakedAmount >= config.minStakeAmount, "Stake requirments not met.");
_;
}
constructor() {
// Deployment doesn't take any params.
// An admin has to call `kickOff` with required config to kick off :).
_pause();
}
/**
* @notice called by the admin upause
* @dev Callable by admin or operator
*/
function kickOff(
Config memory _config
) external onlyOwner {
require(_config.minStakeAmount != 0, "Minimum stake ammount cannot be zero.");
require(_config.betRange <= 10 && _config.betRange > 0, "Invalid bet range.");
require(_config.stakeLockDuration != 0, "Stake duration cannot be zero.");
require(_config.minBetAmount != 0, "Minimum bet cannot be zero.");
require(_config.intervalSeconds != 0, "Invalid interval seconds.");
require(_config.closeTimeMultiplier != 0, "Invalid lock time");
require(_config.bufferSeconds != 0, "Invalid buffer seconds.");
require(_config.intervalSeconds > _config.bufferSeconds, "Interval must be higher than buffer.");
config.fmjToken = _config.fmjToken;
config.minStakeAmount = _config.minStakeAmount;
config.stakeLockDuration = _config.stakeLockDuration;
config.oracle = _config.oracle;
// dummy oracle call
_config.oracle.latestRoundData();
config.minBetAmount = _config.minBetAmount;
config.betRange = _config.betRange;
config.intervalSeconds = _config.intervalSeconds;
config.bufferSeconds = _config.bufferSeconds;
config.prizePool = _config.prizePool;
config.minPrizeAmount = _config.minPrizeAmount;
config.closeTimeMultiplier = _config.closeTimeMultiplier;
_unpause();
emit KickOff(_config);
}
/**
* @notice called by the owner to pause, triggers stopped state
* @dev Callable by owner
*/
function pause() external whenNotPaused onlyOwner {
_pause();
}
/**
* @notice When the system is matured enough to govern on its own,
this function will be called to transfer ownership to a
governance contract.
* @dev Callable by admin or operator
*/
function changeOwnership(address newOwner) external whenPaused onlyOwner {
require(newOwner != address(0), "Invalid address provided");
transferOwnership(newOwner);
emit ChangeOwner(newOwner);
}
function stake(uint256 value) external whenNotPaused {
UserInfo storage user = userInfo[msg.sender];
uint256 currentStake = user.stakedAmount;
require(currentStake < config.minStakeAmount, "Already staking required amount.");
uint256 requiredAmount = config.minStakeAmount - currentStake;
IERC20 token = config.fmjToken; // gas savings
if (requiredAmount == value) {
token.safeTransferFrom(msg.sender, address(this), requiredAmount);
user.unlockTimestamp = block.timestamp + config.stakeLockDuration;
user.stakedAmount = config.minStakeAmount;
} else if (value > requiredAmount) {
token.safeTransferFrom(msg.sender, address(this), requiredAmount);
token.safeTransfer(msg.sender, (value - requiredAmount));
user.unlockTimestamp = block.timestamp + config.stakeLockDuration;
user.stakedAmount = config.minStakeAmount;
} else {
token.safeTransferFrom(msg.sender, address(this), value);
user.stakedAmount = currentStake + value;
}
emit Staked(msg.sender, value, user.stakedAmount);
}
function unstake() external {
UserInfo storage user = userInfo[msg.sender];
uint256 currentStake = user.stakedAmount;
require(currentStake != 0, "Not staking!");
if (currentStake >= config.minStakeAmount) {
require(block.timestamp > user.unlockTimestamp, "Cannot unlock stake yet");
}
config.fmjToken.safeTransfer(msg.sender, currentStake);
emit UnStaked(msg.sender, user.stakedAmount);
user.stakedAmount = 0;
}
/**
* @notice Bet bull position
* @param roundNumber: roundNumber
* @param value: amount
*/
function betBull(uint256 roundNumber, uint256 value) external whenNotPaused nonReentrant notContract hasStakedEnough {
require(roundNumber == currentRoundNumber, "Bet is too late");
Round storage round = rounds[roundNumber];
require(round.status == RoundStatus.Live, "Round not bettable");
require(block.timestamp < round.timestamps.lockTimestamp, "Round locked");
require(value >= config.minBetAmount, "Bet amount must be greater than minBetAmount");
require(ledger[roundNumber][msg.sender].amount == 0, "Can only bet once per round");
config.fmjToken.safeTransferFrom(msg.sender, address(this), value);
// Update round data
round.amounts.bullAmount = round.amounts.bullAmount + value;
round.amounts.totalAmount = round.amounts.totalAmount + value;
// Update user data
BetInfo storage betInfo = ledger[roundNumber][msg.sender];
betInfo.position = Position.Bull;
betInfo.amount = value;
userInfo[msg.sender].userRounds.push(roundNumber);
emit BetBull(msg.sender, roundNumber, value);
}
/**
* @notice Bet bear position
* @param roundNumber: roundNumber
* @param value: amount to bet
*/
function betBear(uint256 roundNumber, uint256 value) external payable whenNotPaused nonReentrant notContract {
require(roundNumber == currentRoundNumber, "Bet is too early/late");
Round storage round = rounds[roundNumber];
require(round.status == RoundStatus.Live, "Round not bettable");
require(block.timestamp < round.timestamps.lockTimestamp, "Round locked");
require(value >= config.minBetAmount, "Bet amount must be greater than minBetAmount");
require(ledger[roundNumber][msg.sender].amount == 0, "Can only bet once per round");
config.fmjToken.safeTransferFrom(msg.sender, address(this), value);
// Update round data
round.amounts.bearAmount = round.amounts.bearAmount + value;
round.amounts.totalAmount = round.amounts.totalAmount + value;
// Update user data
BetInfo storage betInfo = ledger[roundNumber][msg.sender];
betInfo.position = Position.Bear;
betInfo.amount = value;
userInfo[msg.sender].userRounds.push(roundNumber);
emit BetBear(msg.sender, roundNumber, value);
}
/**
* @notice Bet bear position
* @param roundNumber: roundNumber
* @param value: amount to bet
*/
function betFlat(uint256 roundNumber, uint256 value) external payable whenNotPaused nonReentrant notContract {
require(roundNumber == currentRoundNumber, "Bet is too late");
Round storage round = rounds[roundNumber];
require(round.status == RoundStatus.Live, "Round not bettable");
require(value >= config.minBetAmount, "Bet amount must be greater than minBetAmount");
require(ledger[roundNumber][msg.sender].amount == 0, "Can only bet once per round");
config.fmjToken.safeTransferFrom(msg.sender, address(this), value);
// Update round data
round.amounts.flatAmount = round.amounts.flatAmount + value;
round.amounts.totalAmount = round.amounts.totalAmount + value;
// Update user data
BetInfo storage betInfo = ledger[roundNumber][msg.sender];
betInfo.position = Position.Flat;
betInfo.amount = value;
userInfo[msg.sender].userRounds.push(roundNumber);
emit BetFlat(msg.sender, roundNumber, value);
}
/**
* @notice Start the next round n, lock price for round n-1, end round n-2
* @dev Callable by operator
*/
function executeRound() external whenNotPaused onlyOwner {
require(genesisStartOnce, "Can only run after genesisStartRound is triggered");
(uint80 currentRoundId, int256 currentPrice) = _getPriceFromOracle();
oracleLatestRoundId = uint256(currentRoundId);
// end old round
_safeEndRound(currentRoundNumber, currentRoundId, currentPrice);
_calculateRewards(currentRoundNumber);
// start new round
currentRoundNumber = currentRoundNumber + 1;
_safeStartRound(currentRoundNumber, currentRoundId, currentPrice);
}
/**
* @notice Start genesis round
* @dev Callable by admin or operator
*/
function genesisStartRound() external whenNotPaused onlyOwner {
require(!genesisStartOnce, "Can only run genesisStartRound once");
(uint80 currentRoundId, int256 currentPrice) = _getPriceFromOracle();
oracleLatestRoundId = uint256(currentRoundId);
currentRoundNumber = currentRoundNumber + 1;
_startRound(currentRoundNumber, currentRoundId, currentPrice);
genesisStartOnce = true;
}
/**
* @notice Claim winnings
* @param roundNumbers: roundNumbers
*/
function claimWinnings(uint256[] calldata roundNumbers) external nonReentrant notContract {
uint256 reward;
for (uint256 i = 0; i < roundNumbers.length; i++) {
uint256 roundNumber = roundNumbers[i];
Round memory round = rounds[roundNumber];
if(hasWinnings(roundNumber, msg.sender)) {
BetInfo storage betInfo = ledger[roundNumber][msg.sender];
betInfo.winningsClaimed = true;
uint256 q = round.amounts.flatAmount;
if(round.rewards.winner == Position.Bull) {
q = round.amounts.bullAmount;
} else if(round.rewards.winner == Position.Bear) {
q = round.amounts.bearAmount;
}
reward = reward + (round.rewards.amount * betInfo.amount)/q;
}
}
if(reward > 0) {
config.fmjToken.transferFrom(address(config.prizePool), msg.sender, reward);
config.prizePool.markPrizeSent(reward);
}
}
/**
* @notice Claim locked funds
* @param roundNumbers: roundNumbers
*/
function claimLockedFunds(uint256[] calldata roundNumbers) external nonReentrant notContract {
uint256 fund;
for (uint256 i = 0; i < roundNumbers.length; i++) {
uint256 roundNumber = roundNumbers[i];
if(hasLockedFunds(roundNumber, msg.sender)) {
BetInfo storage betInfo = ledger[roundNumber][msg.sender];
betInfo.betAmountClaimed = true;
fund = fund + betInfo.amount;
}
}
if(fund > 0) {
config.fmjToken.transfer(msg.sender, fund);
}
}
/**
* @notice Get the claimable stats of specific round and user account
* @param roundNumber: roundNumber
* @param user: user address
*/
function hasWinnings(uint256 roundNumber, address user) public view returns (bool) {
BetInfo memory betInfo = ledger[roundNumber][user];
Round memory round = rounds[roundNumber];
if (round.rewards.status != RewardStatus.Calculated) {
// no winners, not calculated
return false;
}
if (betInfo.amount == 0) {
// user didn't bet on the outcome
return false;
}
if (betInfo.winningsClaimed) {
// winnings already claimed
return false;
}
return round.rewards.winner == betInfo.position;
}
/**
* @notice Get the claimable state of locked funds of a specific user
* @param roundNumber: roundNumber
* @param user: user address
*/
function hasLockedFunds(uint256 roundNumber, address user) public view returns (bool) {
BetInfo memory betInfo = ledger[roundNumber][user];
Round memory round = rounds[roundNumber];
if (!((round.status == RoundStatus.Expired) || (round.status == RoundStatus.Cancelled))) {
// no winners, not calculated
return false;
}
if (betInfo.amount == 0) {
// user didn't bet on the outcome
return false;
}
if (betInfo.betAmountClaimed) {
// already claimed
return false;
}
return true;
}
/**
* @notice It allows the owner to recover tokens sent to the contract by mistake
* @param _token: token address
* @param _amount: token amount
* @dev Callable by owner
*/
function recoverToken(address _token, uint256 _amount) external onlyOwner {
IERC20(_token).safeTransfer(address(msg.sender), _amount);
}
function userRounds(address user) view external returns(uint256[] memory){
return userInfo[user].userRounds;
}
/**
* @notice Calculate rewards for round
* @param roundNumber: roundNumber
*/
function _calculateRewards(uint256 roundNumber) internal {
Round storage round = rounds[roundNumber];
require(round.status == RoundStatus.Expired, "Too early");
require(round.rewards.status == RewardStatus.NotCalculated, "Cannot calculate rewards");
// not enough funds to calculate prize
uint256 prizePool = config.prizePool.prizePoolAmount();
bool bullWins = round.prices.closePrice > round.prices.flatMaxPrice;
bool bearWins = round.prices.closePrice < round.prices.flatMinPrice;
bool flatWins = !(bullWins || bearWins);
bool hasPrize = prizePool > config.minPrizeAmount;
if(bullWins) {
round.rewards.winner = Position.Bull;
if(hasPrize && round.amounts.bullAmount != 0) {
round.rewards.amount = prizePool;
config.prizePool.reservePrizeAmount(prizePool);
}
}
if(bearWins) {
round.rewards.winner = Position.Bear;
if(hasPrize && round.amounts.bearAmount != 0) {
round.rewards.amount = prizePool;
config.prizePool.reservePrizeAmount(prizePool);
}
}
if(flatWins) {
round.rewards.winner = Position.Flat;
if(hasPrize && round.amounts.flatAmount != 0) {
round.rewards.amount = prizePool;
config.prizePool.reservePrizeAmount(prizePool);
}
}
if(!hasPrize) {
round.rewards.status = RewardStatus.Cancelled;
} else {
round.rewards.status = RewardStatus.Calculated;
}
}
/**
* @notice Start round
* Previous round n-1 must end
* @param roundNumber: roundNumber
*/
function _safeStartRound(uint256 roundNumber, uint256 roundId,
int256 price) internal {
require(genesisStartOnce, "Can only run after genesisStartRound is triggered");
require(rounds[roundNumber - 1].status == RoundStatus.Expired, "Can only start round after round n-1 has ended");
_startRound(roundNumber, roundId, price);
}
/**
* @notice Start round
* @param roundNumber: roundNumber
*/
function _startRound(uint256 roundNumber, uint256 roundId,
int256 price) internal {
Round storage round = rounds[roundNumber];
round.timestamps.startTimestamp = block.timestamp;
/**
* If interval is 30 minutes, and closeTimeMultiplier is 4.
* Users have 30 minutes to place bets.
* After 4 * 30 = 120 minutes the round is closed.
*/
round.timestamps.lockTimestamp = block.timestamp + config.intervalSeconds;
round.timestamps.closeTimestamp = block.timestamp + (config.closeTimeMultiplier * config.intervalSeconds);
round.roundNumber = roundNumber;
int difference = (price * config.betRange)/200;
round.prices.flatMinPrice = price - difference;
round.prices.flatMaxPrice = price + difference;
round.oracleIds.startOracleId = roundId;
round.status = RoundStatus.Live;
emit StartRound(roundNumber, roundId, price);
}
/**
* @notice End round
* @param roundNumber: epoch
* @param roundId: roundId
* @param price: price of the round
*/
function _safeEndRound(
uint256 roundNumber,
uint256 roundId,
int256 price
) internal {
// TODO: Enable/Remove these once blocktime in polyjuice is finalized (nodes, mining etc)
// require(block.timestamp >= rounds[roundNumber].timestamps.closeTimestamp, "Can only end round after closeTimestamp");
// require(
// block.timestamp <= rounds[roundNumber].timestamps.closeTimestamp + config.bufferSeconds,
// "Can only end round within bufferSeconds"
// );
Round storage round = rounds[roundNumber];
round.prices.closePrice = price;
round.oracleIds.closeOracleId = roundId;
round.status = RoundStatus.Expired;
emit EndRound(roundNumber, roundId, price);
}
function _getPriceFromOracle() internal view returns (uint80, int256) {
(uint80 roundId, int256 price,,,) = config.oracle.latestRoundData();
// TODO: stricly check oracle timestamp allowance
// once polyjuice has a proper oracle
return (roundId, price);
}
/**
* @notice Returns true if `account` is a contract.
* @param account: account address
*/
function _isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
} | * @notice Start the next round n, lock price for round n-1, end round n-2 @dev Callable by operator/ end old round start new round | function executeRound() external whenNotPaused onlyOwner {
require(genesisStartOnce, "Can only run after genesisStartRound is triggered");
(uint80 currentRoundId, int256 currentPrice) = _getPriceFromOracle();
oracleLatestRoundId = uint256(currentRoundId);
_safeEndRound(currentRoundNumber, currentRoundId, currentPrice);
_calculateRewards(currentRoundNumber);
currentRoundNumber = currentRoundNumber + 1;
_safeStartRound(currentRoundNumber, currentRoundId, currentPrice);
}
| 13,011,099 | [
1,
1685,
326,
1024,
3643,
290,
16,
2176,
6205,
364,
3643,
290,
17,
21,
16,
679,
3643,
290,
17,
22,
225,
10464,
635,
3726,
19,
679,
1592,
3643,
787,
394,
3643,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1836,
11066,
1435,
3903,
1347,
1248,
28590,
1338,
5541,
288,
203,
3639,
2583,
12,
4507,
16786,
1685,
12212,
16,
315,
2568,
1338,
1086,
1839,
21906,
1685,
11066,
353,
10861,
8863,
203,
203,
3639,
261,
11890,
3672,
783,
11066,
548,
16,
509,
5034,
783,
5147,
13,
273,
389,
588,
5147,
1265,
23601,
5621,
203,
203,
3639,
20865,
18650,
11066,
548,
273,
2254,
5034,
12,
2972,
11066,
548,
1769,
203,
203,
3639,
389,
4626,
1638,
11066,
12,
2972,
11066,
1854,
16,
783,
11066,
548,
16,
783,
5147,
1769,
203,
3639,
389,
11162,
17631,
14727,
12,
2972,
11066,
1854,
1769,
203,
203,
3639,
783,
11066,
1854,
273,
783,
11066,
1854,
397,
404,
31,
203,
3639,
389,
4626,
1685,
11066,
12,
2972,
11066,
1854,
16,
783,
11066,
548,
16,
783,
5147,
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
] |
pragma solidity ^0.4.15;
contract Reputation {
address public owner;
// keep track of whether one addr has already rated another addr
mapping(address => mapping(address => bool)) public outgoingRatings;
Rating[] public ratings;
struct Rating{
address from;
address to;
}
/*
* Events
*/
event RatingSuccessfullyAdded(bool success, address src, address target);
modifier ownerOnly() {
if (msg.sender == owner) {
_;
}
}
function Reputation() {
owner = msg.sender;
}
/*
* This function can be called by any public address to
* rate any other address.
*/
function rate(address toRate) public returns (bool) {
require(toRate != address(0));
if (msg.sender == toRate) {
RatingSuccessfullyAdded(false, address(0), address(0));
return false;
}
if (outgoingRatings[msg.sender][toRate] != true) {
outgoingRatings[msg.sender][toRate] = true;
Rating memory newRating;
newRating.from = msg.sender;
newRating.to = toRate;
ratings.push(newRating);
RatingSuccessfullyAdded(true, msg.sender, toRate);
return true;
}
RatingSuccessfullyAdded(false, address(0), address(0));
return false;
}
/*
* Constant getter functions
*/
function getNumRatings() public constant returns(uint) {
return ratings.length;
}
function getRating(uint index) public constant returns(address, address) {
return (ratings[index].from, ratings[index].to);
}
function getOwner() public constant returns(address) {
return owner;
}
}
| keep track of whether one addr has already rated another addr | contract Reputation {
address public owner;
mapping(address => mapping(address => bool)) public outgoingRatings;
Rating[] public ratings;
struct Rating{
address from;
address to;
}
event RatingSuccessfullyAdded(bool success, address src, address target);
modifier ownerOnly() {
if (msg.sender == owner) {
_;
}
}
modifier ownerOnly() {
if (msg.sender == owner) {
_;
}
}
function Reputation() {
owner = msg.sender;
}
function rate(address toRate) public returns (bool) {
require(toRate != address(0));
if (msg.sender == toRate) {
RatingSuccessfullyAdded(false, address(0), address(0));
return false;
}
if (outgoingRatings[msg.sender][toRate] != true) {
outgoingRatings[msg.sender][toRate] = true;
Rating memory newRating;
newRating.from = msg.sender;
newRating.to = toRate;
ratings.push(newRating);
RatingSuccessfullyAdded(true, msg.sender, toRate);
return true;
}
RatingSuccessfullyAdded(false, address(0), address(0));
return false;
}
function rate(address toRate) public returns (bool) {
require(toRate != address(0));
if (msg.sender == toRate) {
RatingSuccessfullyAdded(false, address(0), address(0));
return false;
}
if (outgoingRatings[msg.sender][toRate] != true) {
outgoingRatings[msg.sender][toRate] = true;
Rating memory newRating;
newRating.from = msg.sender;
newRating.to = toRate;
ratings.push(newRating);
RatingSuccessfullyAdded(true, msg.sender, toRate);
return true;
}
RatingSuccessfullyAdded(false, address(0), address(0));
return false;
}
function rate(address toRate) public returns (bool) {
require(toRate != address(0));
if (msg.sender == toRate) {
RatingSuccessfullyAdded(false, address(0), address(0));
return false;
}
if (outgoingRatings[msg.sender][toRate] != true) {
outgoingRatings[msg.sender][toRate] = true;
Rating memory newRating;
newRating.from = msg.sender;
newRating.to = toRate;
ratings.push(newRating);
RatingSuccessfullyAdded(true, msg.sender, toRate);
return true;
}
RatingSuccessfullyAdded(false, address(0), address(0));
return false;
}
function getNumRatings() public constant returns(uint) {
return ratings.length;
}
function getRating(uint index) public constant returns(address, address) {
return (ratings[index].from, ratings[index].to);
}
function getOwner() public constant returns(address) {
return owner;
}
}
| 12,545,517 | [
1,
10102,
3298,
434,
2856,
1245,
3091,
711,
1818,
436,
690,
4042,
3091,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
868,
458,
367,
288,
203,
203,
202,
2867,
1071,
3410,
31,
203,
202,
6770,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
1071,
12902,
29635,
899,
31,
203,
202,
20388,
8526,
1071,
15183,
899,
31,
203,
202,
1697,
534,
1776,
95,
203,
202,
565,
1758,
628,
31,
203,
202,
565,
1758,
358,
31,
203,
202,
97,
203,
203,
203,
202,
2575,
534,
1776,
18303,
8602,
12,
6430,
2216,
16,
1758,
1705,
16,
1758,
1018,
1769,
203,
202,
20597,
3410,
3386,
1435,
288,
203,
202,
202,
430,
261,
3576,
18,
15330,
422,
3410,
13,
288,
203,
1082,
202,
67,
31,
203,
202,
202,
97,
203,
202,
97,
203,
203,
202,
20597,
3410,
3386,
1435,
288,
203,
202,
202,
430,
261,
3576,
18,
15330,
422,
3410,
13,
288,
203,
1082,
202,
67,
31,
203,
202,
202,
97,
203,
202,
97,
203,
203,
202,
915,
868,
458,
367,
1435,
288,
203,
202,
202,
8443,
273,
1234,
18,
15330,
31,
203,
202,
97,
203,
203,
202,
915,
4993,
12,
2867,
358,
4727,
13,
1071,
1135,
261,
6430,
13,
288,
203,
202,
202,
6528,
12,
869,
4727,
480,
1758,
12,
20,
10019,
203,
202,
202,
430,
261,
3576,
18,
15330,
422,
358,
4727,
13,
288,
203,
1082,
202,
20388,
18303,
8602,
12,
5743,
16,
1758,
12,
20,
3631,
1758,
12,
20,
10019,
203,
1082,
202,
2463,
629,
31,
203,
202,
202,
97,
203,
203,
202,
202,
430,
261,
31891,
29635,
899,
63,
3576,
18,
15330,
6362,
869,
4727,
65,
480,
638,
13,
288,
203,
1082,
202,
31891,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "../interfaces/IDeFiPlaza.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title DeFi Plaza exchange controct, multi token DEX.
* @author Jazzer 9F
* @notice Trades between two tokens follow the local bonding curve x*y=k
* The number of tokens used is hard coded to 16 for efficiency reasons.
*/
contract DeFiPlaza is IDeFiPlaza, Ownable, ERC20 {
using SafeERC20 for IERC20;
// States that each token can be in
enum State {Unlisted, PreListing, Delisting, Listed}
// Configuration per token. Still some bits available if needed
struct TokenSettings {
State state; // What state the token is currently in
uint112 listingTarget; // Amount of tokens needed to activate listing
}
// Exchange configuration
struct Config {
bool unlocked; // Locked for trading to prevent re-entrancy misery
uint64 oneMinusTradingFee; // One minus the swap fee (0.64 fixed point integer)
uint64 delistingBonus; // Amount of additional tokens to encourage immediate delisting (0.64 fixed point)
}
// Keeps track of whether there is a listing change underway and if so between which tokens
struct ListingUpdate {
address tokenToDelist; // Token to be removed
address tokenToList; // Token to be listed
}
// Mapping to keep track of the listed tokens
mapping(address => TokenSettings) public listedTokens;
Config public DFPconfig;
ListingUpdate public listingUpdate;
address public admin;
/**
* Sets up default configuration
* Initialize with ordered list of 15 token addresses (ETH is always listed)
* Doesn't do any checks. Make sure you ONLY add well behaved ERC20s!!
*/
constructor(address[] memory tokensToList, uint256 mintAmount, string memory name_, string memory symbol_) ERC20(name_, symbol_) {
// Basic exchange configuration
Config memory config;
config.unlocked = false;
config.oneMinusTradingFee = 0xffbe76c8b4395800; // approximately 0.999
config.delistingBonus = 0;
DFPconfig = config;
// Configure the listed tokens as such
TokenSettings memory listed;
listed.state = State.Listed;
require(tokensToList.length == 15, "Incorrect number of tokens");
address previous = address(0);
address current = address(0);
for (uint256 i = 0; i < 15; i++) {
current = tokensToList[i];
require(current > previous, "Require ordered list");
listedTokens[current] = listed;
previous = current;
}
// Generate the LP tokens reflecting the initial liquidity (to be loaded externally)
_mint(msg.sender, mintAmount);
}
// For bootstrapping ETH liquidity
receive() external payable {}
// To safeguard some functionality is only applied to listed tokens
modifier onlyListedToken(address token) {
require(
token == address(0) || listedTokens[token].state > State.Delisting,
"DFP: Token not listed"
);
_;
}
modifier onlyAdmin() {
require(
msg.sender == admin || msg.sender == owner(),
"DFP: admin rights required"
);
_;
}
/**
* Allows users to swap between any two tokens listed on the DEX.
* Follows the x*y=k swap invariant hyperbole
* For ETH trades, send the ETH with the transaction and use the NULL address as inputToken.
*/
function swap(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 minOutputAmount
)
external
payable
onlyListedToken(inputToken)
onlyListedToken(outputToken)
override
returns (uint256 outputAmount)
{
// Check that the exchange is unlocked and thus open for business
Config memory _config = DFPconfig;
require(_config.unlocked, "DFP: Locked");
// Pull in input token and check the exchange balance for that token
uint256 initialInputBalance;
if (inputToken == address(0)) {
require(msg.value == inputAmount, "DFP: bad ETH amount");
initialInputBalance = address(this).balance - inputAmount;
} else {
initialInputBalance = IERC20(inputToken).balanceOf(address(this));
IERC20(inputToken).safeTransferFrom(msg.sender, address(this), inputAmount);
}
// Check dex balance of the output token
uint256 initialOutputBalance;
if (outputToken == address(0)) {
initialOutputBalance = address(this).balance;
} else {
initialOutputBalance = IERC20(outputToken).balanceOf(address(this));
}
// Calculate the output amount through the x*y=k invariant
// Can skip overflow/underflow checks on this calculation as they will always work against an attacker anyway.
uint256 netInputAmount = inputAmount * _config.oneMinusTradingFee;
outputAmount = netInputAmount * initialOutputBalance / ((initialInputBalance << 64) + netInputAmount);
require(outputAmount > minOutputAmount, "DFP: No deal");
// Send output tokens to whoever invoked the swap function
if (outputToken == address(0)) {
address payable sender = payable(msg.sender);
sender.transfer(outputAmount);
} else {
IERC20(outputToken).safeTransfer(msg.sender, outputAmount);
}
// Emit swap event to enable better governance decision making
emit Swapped(msg.sender, inputToken, outputToken, inputAmount, outputAmount);
}
/**
* Single sided liquidity add. More economic at low/moderate liquidity amounts.
* Mathematically works as adding all tokens and swapping back to 1 token at no fee.
*
* R = (1 + X_supplied/X_initial)^(1/N) - 1
* LP_minted = R * LP_total
*
* When adding ETH, the inputToken address to be used is the NULL address.
* A fee is applied to prevent zero fee swapping through liquidity add/remove.
*
* Note that this method suffers from two forms of slippage.
* 1. Slippage from single sided add which is modeled with 15 internal swaps
* 2. Slippage from the numerical approximation required for calculation.
*
* When adding a large amount of liquidity when compared with the existing
* liquidity for the selected token, the slippage can become quite significant.
* The smart contract limits the maximum input amount at 100% of the existing
* liquidity, at which point the slippage is 29.2% (due to 1) + 9.3% (due to 2)
*/
function addLiquidity(address inputToken, uint256 inputAmount, uint256 minLP)
external
payable
onlyListedToken(inputToken)
override
returns (uint256 actualLP)
{
// Check that the exchange is unlocked and thus open for business
Config memory _config = DFPconfig;
require(_config.unlocked, "DFP: Locked");
// Pull in input token and check the exchange balance for that token
uint256 initialBalance;
if (inputToken == address(0)) {
require(msg.value == inputAmount, "DFP: Incorrect amount of ETH");
initialBalance = address(this).balance - inputAmount;
} else {
initialBalance = IERC20(inputToken).balanceOf(address(this));
IERC20(inputToken).safeTransferFrom(msg.sender, address(this), inputAmount);
}
// Prevent excessive liquidity add which runs of the approximation curve
require(inputAmount < initialBalance, "DFP: Too much at once");
// See https://en.wikipedia.org/wiki/Binomial_approximation for the below
// Compute the 6th power binomial series approximation of R.
//
// X 15 X^2 155 X^3 7285 X^4 91791 X^5 2417163 X^6
// (1+X)^1/16 - 1 ≈ -- - ------ + ------- - -------- + --------- - -----------
// 16 512 8192 524288 8388608 268435456
//
// Note that we need to terminate at an even order to guarantee an underestimate
// for safety. The underestimation leads to slippage for higher amounts, but
// protects funds of those that are already invested.
uint256 X = (inputAmount * _config.oneMinusTradingFee) / initialBalance; // 0.64 bits
uint256 X_ = X * X; // X^2 0.128 bits
uint256 R_ = (X >> 4) - (X_ * 15 >> 73); // R2 0.64 bits
X_ = X_ * X; // X^3 0.192 bits
R_ = R_ + (X_ * 155 >> 141); // R3 0.64 bits
X_ = X_ * X >> 192; // X^4 0.64 bits
R_ = R_ - (X_ * 7285 >> 19); // R4 0.64 bits
X_ = X_ * X; // X^5 0.128 bits
R_ = R_ + (X_ * 91791 >> 87); // R5 0.64 bits
X_ = X_ * X; // X^6 0.192 bits
R_ = R_ - (X_ * 2417163 >> 156); // R6 0.64 bits
// Calculate and mint LPs to be awarded
actualLP = R_ * totalSupply() >> 64;
require(actualLP > minLP, "DFP: No deal");
_mint(msg.sender, actualLP);
// Emitting liquidity add event to enable better governance decisions
emit LiquidityAdded(msg.sender, inputToken, inputAmount, actualLP);
}
/**
* Multi-token liquidity add. More economic for large amounts of liquidity.
* Simply takes in all 16 listed tokens in ratio and mints the LPs accordingly.
* For ETH, the inputToken address to be used is the NULL address.
* A fee is applied to prevent zero fee swapping through liquidity add/remove.
*/
function addMultiple(address[] calldata tokens, uint256[] calldata maxAmounts)
external
payable
override
returns (uint256 actualLP)
{
// Perform basic checks
Config memory _config = DFPconfig;
require(_config.unlocked, "DFP: Locked");
require(tokens.length == 16, "DFP: Bad tokens array length");
require(maxAmounts.length == 16, "DFP: Bad maxAmount array length");
// Check ETH amount/ratio first
require(tokens[0] == address(0), "DFP: No ETH found");
require(maxAmounts[0] == msg.value, "DFP: Incorrect ETH amount");
uint256 dexBalance = address(this).balance - msg.value;
uint256 actualRatio = msg.value * (1<<128) / dexBalance;
// Check ERC20 amounts/ratios
uint256 currentRatio;
address previous;
address token;
for (uint256 i = 1; i < 16; i++) {
token = tokens[i];
require(token > previous, "DFP: Require ordered list");
require(
listedTokens[token].state > State.Delisting,
"DFP: Token not listed"
);
dexBalance = IERC20(token).balanceOf(address(this));
currentRatio = maxAmounts[i] * (1 << 128) / dexBalance;
if (currentRatio < actualRatio) {
actualRatio = currentRatio;
}
previous = token;
}
// Calculate how many LP will be generated
actualLP = (actualRatio * totalSupply() >> 64) * DFPconfig.oneMinusTradingFee >> 128;
// Collect ERC20 tokens
for (uint256 i = 1; i < 16; i++) {
token = tokens[i];
dexBalance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransferFrom(msg.sender, address(this), dexBalance * actualRatio >> 128);
}
// Mint the LP tokens
_mint(msg.sender, actualLP);
emit MultiLiquidityAdded(msg.sender, actualLP, totalSupply());
// Refund ETH change
dexBalance = address(this).balance - msg.value;
address payable sender = payable(msg.sender);
sender.transfer(msg.value - (dexBalance * actualRatio >> 128));
}
/**
* Single sided liquidity withdrawal. More efficient at lower liquidity amounts.
* Mathematically withdraws 16 tokens in ratio and then swaps 15 back in at no fees.
* Calculates the following:
*
* R = LP_burnt / LP_initial
* X_out = X_initial * (1 - (1 - R)^N)
*
* No fee is applied for withdrawals. For ETH output, use the NULL address as outputToken.
*/
function removeLiquidity(uint256 LPamount, address outputToken, uint256 minOutputAmount)
external
onlyListedToken(outputToken)
override
returns (uint256 actualOutput)
{
// Checks the initial balance of the token desired as output token
uint256 initialBalance;
if (outputToken == address(0)) {
initialBalance = address(this).balance;
} else {
initialBalance = IERC20(outputToken).balanceOf(address(this));
}
// Calculates intermediate variable F = (1-R)^16 and then the resulting output amount.
uint256 F_;
F_ = (1 << 64) - (LPamount << 64) / totalSupply(); // (1-R) (0.64 bits)
F_ = F_ * F_; // (1-R)^2 (0.128 bits)
F_ = F_ * F_ >> 192; // (1-R)^4 (0.64 bits)
F_ = F_ * F_; // (1-R)^8 (0.128 bits)
F_ = F_ * F_ >> 192; // (1-R)^16 (0.64 bits)
actualOutput = initialBalance * ((1 << 64) - F_) >> 64;
require(actualOutput > minOutputAmount, "DFP: No deal");
// Burns the LP tokens and sends the output tokens
_burn(msg.sender, LPamount);
if (outputToken == address(0)) {
address payable sender = payable(msg.sender);
sender.transfer(actualOutput);
} else {
IERC20(outputToken).safeTransfer(msg.sender, actualOutput);
}
// Emitting liquidity removal event to enable better governance decisions
emit LiquidityRemoved(msg.sender, outputToken, actualOutput, LPamount);
}
/**
* Multi-token liquidity removal. More economic for large amounts of liquidity.
* Returns all 16 listed tokens in ratio and burns the LPs accordingly.
*/
function removeMultiple(uint256 LPamount, address[] calldata tokens)
external
override
returns (bool success)
{
// Perform basic validation (no lock check here on purpose)
require(tokens.length == 16, "DFP: Bad tokens array length");
// Calculate fraction of total liquidity to be returned
uint256 fraction = (LPamount << 128) / totalSupply();
// Send the ETH first (use transfer to prevent reentrancy)
uint256 dexBalance = address(this).balance;
address payable sender = payable(msg.sender);
sender.transfer(fraction * dexBalance >> 128);
// Send the ERC20 tokens
address previous;
for (uint256 i = 1; i < 16; i++) {
address token = tokens[i];
require(token > previous, "DFP: Require ordered list");
require(
listedTokens[token].state > State.Delisting,
"DFP: Token not listed"
);
dexBalance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(msg.sender, fraction * dexBalance >> 128);
previous = token;
}
// Burn the LPs
_burn(msg.sender, LPamount);
emit MultiLiquidityRemoved(msg.sender, LPamount, totalSupply());
// That's all folks
return true;
}
/**
* When a token is delisted and another one gets listed in its place, the users can
* call this function to provide liquidity for the new token in exchange for the old
* token. The ratio should be set such that the users have a financial incentive to
* perform this transaction.
*/
function bootstrapNewToken(
address inputToken,
uint256 maxInputAmount,
address outputToken
) public override returns (uint64 fractionBootstrapped) {
// Check whether the valid token is being bootstrapped
TokenSettings memory tokenToList = listedTokens[inputToken];
require(
tokenToList.state == State.PreListing,
"DFP: Wrong token"
);
// Calculate how many tokens to actually take in (clamp at max available)
uint256 initialInputBalance = IERC20(inputToken).balanceOf(address(this));
uint256 availableAmount;
// Intentionally underflow (zero clamping) is the cheapest way to gracefully prevent failing when target is already met
unchecked { availableAmount = tokenToList.listingTarget - initialInputBalance; }
if (initialInputBalance >= tokenToList.listingTarget) { availableAmount = 1; }
uint256 actualInputAmount = maxInputAmount > availableAmount ? availableAmount : maxInputAmount;
// Actually pull the tokens in
IERC20(inputToken).safeTransferFrom(msg.sender, address(this), actualInputAmount);
// Check whether the output token requested is indeed being delisted
TokenSettings memory tokenToDelist = listedTokens[outputToken];
require(
tokenToDelist.state == State.Delisting,
"DFP: Wrong token"
);
// Check how many of the output tokens should be given out and transfer those
uint256 initialOutputBalance = IERC20(outputToken).balanceOf(address(this));
uint256 outputAmount = actualInputAmount * initialOutputBalance / availableAmount;
IERC20(outputToken).safeTransfer(msg.sender, outputAmount);
fractionBootstrapped = uint64((actualInputAmount << 64) / tokenToList.listingTarget);
// Emit event for better governance decisions
emit Bootstrapped(
msg.sender,
inputToken,
actualInputAmount,
outputToken,
outputAmount
);
// If the input token liquidity is now at the target we complete the (de)listing
if (actualInputAmount == availableAmount) {
tokenToList.state = State.Listed;
listedTokens[inputToken] = tokenToList;
delete listedTokens[outputToken];
delete listingUpdate;
DFPconfig.delistingBonus = 0;
emit BootstrapCompleted(outputToken, inputToken);
}
}
/**
* Emergency bonus withdrawal when bootstrapping is expected to remain incomplete
* A fraction is specified (for example 5%) that is then rewarded in bonus tokens
* on top of the regular bootstrapping output tokens.
*/
function bootstrapNewTokenWithBonus(
address inputToken,
uint256 maxInputAmount,
address outputToken,
address bonusToken
) external onlyListedToken(bonusToken) override returns (uint256 bonusAmount) {
// Check whether the output token requested is indeed being delisted
TokenSettings memory tokenToDelist = listedTokens[outputToken];
require(
tokenToDelist.state == State.Delisting,
"DFP: Wrong token"
);
// Collect parameters required to calculate bonus
uint256 bonusFactor = uint256(DFPconfig.delistingBonus);
uint64 fractionBootstrapped = bootstrapNewToken(inputToken, maxInputAmount, outputToken);
// Balance of selected bonus token
uint256 bonusBalance;
if (bonusToken == address(0)) {
bonusBalance = address(this).balance;
} else {
bonusBalance = IERC20(bonusToken).balanceOf(address(this));
}
// Calculate bonus amount
bonusAmount = uint256(fractionBootstrapped) * bonusFactor * bonusBalance >> 128;
// Payout bonus tokens
if (bonusToken == address(0)) {
address payable sender = payable(msg.sender);
sender.transfer(bonusAmount);
} else {
IERC20(bonusToken).safeTransfer(msg.sender, bonusAmount);
}
// Emit event to enable data driven governance
emit BootstrapBonus(
msg.sender,
bonusToken,
bonusAmount
);
}
/**
* Initiates process to delist one token and list another.
*/
function changeListing(
address tokenToDelist, // Address of token to be delisted
address tokenToList, // Address of token to be listed
uint112 listingTarget // Amount of tokens needed to activate listing
) external onlyListedToken(tokenToDelist) onlyOwner() {
// Basic validity checks. ETH cannot be delisted, only one delisting at a time.
require(tokenToDelist != address(0), "DFP: Cannot delist ETH");
ListingUpdate memory update = listingUpdate;
require(update.tokenToDelist == address(0), "DFP: Previous update incomplete");
// Can't list an already listed token
TokenSettings memory _token = listedTokens[tokenToList];
require(_token.state == State.Unlisted, "DFP: Token already listed");
// Set the delisting/listing struct.
update.tokenToDelist = tokenToDelist;
update.tokenToList = tokenToList;
listingUpdate = update;
// Configure the token states for incoming/outgoing tokens
_token.state = State.PreListing;
_token.listingTarget = listingTarget;
listedTokens[tokenToList] = _token;
listedTokens[tokenToDelist].state = State.Delisting;
}
/**
* Sets trading fee (actually calculates using 1-fee) as a 0.64 fixed point number.
*/
function setTradingFee(uint64 oneMinusFee) external onlyOwner() {
DFPconfig.oneMinusTradingFee = oneMinusFee;
}
/**
* Sets delisting bonus as emergency measure to complete a (de)listing when it gets stuck.
*/
function setDeListingBonus(uint64 delistingBonus) external onlyOwner() {
ListingUpdate memory update = listingUpdate;
require(update.tokenToDelist != address(0), "DFP: No active delisting");
DFPconfig.delistingBonus = delistingBonus;
}
/**
* Sets admin address for emergency exchange locking
*/
function setAdmin(address adminAddress) external onlyOwner() {
admin = adminAddress;
}
/**
* Sets exchange lock, under which swap and liquidity add (but not remove) are disabled
*/
function lockExchange() external onlyAdmin() {
DFPconfig.unlocked = false;
}
/**
* Resets exchange lock.
*/
function unlockExchange() external onlyAdmin() {
DFPconfig.unlocked = true;
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.6;
interface IDeFiPlaza {
function swap(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 minOutputAmount
) external payable returns (uint256 outputAmount);
function addLiquidity(
address inputToken,
uint256 inputAmount,
uint256 minLP
) external payable returns (uint256 deltaLP);
function addMultiple(
address[] calldata tokens,
uint256[] calldata maxAmounts
) external payable returns (uint256 actualLP);
function removeLiquidity(
uint256 LPamount,
address outputToken,
uint256 minOutputAmount
) external returns (uint256 actualOutput);
function removeMultiple(
uint256 LPamount,
address[] calldata tokens
) external returns (bool success);
function bootstrapNewToken(
address inputToken,
uint256 maxInputAmount,
address outputToken
) external returns (uint64 fractionBootstrapped);
function bootstrapNewTokenWithBonus(
address inputToken,
uint256 maxInputAmount,
address outputToken,
address bonusToken
) external returns (uint256 bonusAmount);
event Swapped(
address sender,
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount
);
event LiquidityAdded(
address sender,
address token,
uint256 tokenAmount,
uint256 LPs
);
event MultiLiquidityAdded(
address sender,
uint256 LPs,
uint256 totalLPafter
);
event LiquidityRemoved(
address recipient,
address token,
uint256 tokenAmount,
uint256 LPs
);
event MultiLiquidityRemoved(
address sender,
uint256 LPs,
uint256 totalLPafter
);
event Bootstrapped(
address sender,
address inputToken,
uint256 inputAmount,
address outputToken,
uint256 outputAmount
);
event BootstrapBonus(
address sender,
address bonusToken,
uint256 bonusAmount
);
event BootstrapCompleted(
address delistedToken,
address listedToken
);
}
// 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.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;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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;
}
}
| Calculate how many LP will be generated | actualLP = (actualRatio * totalSupply() >> 64) * DFPconfig.oneMinusTradingFee >> 128;
| 934,250 | [
1,
8695,
3661,
4906,
511,
52,
903,
506,
4374,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3214,
14461,
273,
261,
18672,
8541,
380,
2078,
3088,
1283,
1435,
1671,
5178,
13,
380,
463,
30246,
1425,
18,
476,
18434,
1609,
7459,
14667,
1671,
8038,
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
] |
./full_match/1/0xE100D280DEc73D47328D074A22e9bEa744DaF195/sources/browser/Treasury-flattened.sol | * @notice Withdraw entire balance to the owner./ | function withdraw() external onlyOwner() {
_token.safeTransfer(msg.sender, _token.balanceOf(address(this)));
}
| 8,391,804 | [
1,
1190,
9446,
7278,
11013,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
1435,
3903,
1338,
5541,
1435,
288,
203,
3639,
389,
2316,
18,
4626,
5912,
12,
3576,
18,
15330,
16,
389,
2316,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
contract GasConsumer {
// default fallback--consumes all allotted gas
function() external {
assembly {
invalid()
}
}
// Overhead for checking methodId etc in this function before the actual call()
// This was figured out empirically during testing--adding methods or changing compiler settings will require recalibration.
uint constant gasOverheadOfEOACall = 947;
/**
* Consumes the exact amount of gas specified by the input.
* Does not include the cost of calling this contract itself, so is best used for testing/entry point calls.
* @param _amount Amount of gas to consume.
*/
function consumeGasEOA(uint _amount) external {
require(_amount > gasOverheadOfEOACall, "Unable to consume an amount of gas this small.");
uint gasToAlloc = _amount - gasOverheadOfEOACall;
// call this contract's fallback which consumes all allocated gas
assembly {
pop(call(gasToAlloc, address, 0, 0, 0, 0, 0))
}
}
// Overhead for checking methodId, etc. in this function before the actual call()
// This was figured out empirically during testing--adding methods or changing compiler settings will require recalibration.
uint constant gasOverheadOfInternalCall = 2514;
/**
* Consumes the exact amount of gas specified by the input.
* Includes the additional cost of CALLing this contract itself, so is best used for cross-contract calls.
* @param _amount Amount of gas to consume.
*/
function consumeGasInternalCall(uint _amount) external {
require(_amount > gasOverheadOfInternalCall, "Unable to consume an amount of gas this small.");
uint gasToAlloc = _amount - gasOverheadOfInternalCall;
// call this contract's fallback which consumes all allocated gas
assembly {
pop(call(gasToAlloc, address, 0, 0, 0, 0, 0))
}
}
} | Overhead for checking methodId etc in this function before the actual call() This was figured out empirically during testing--adding methods or changing compiler settings will require recalibration. | uint constant gasOverheadOfEOACall = 947;
| 12,675,726 | [
1,
4851,
1978,
364,
6728,
707,
548,
5527,
316,
333,
445,
1865,
326,
3214,
745,
1435,
1220,
1703,
4291,
2862,
596,
801,
84,
481,
6478,
4982,
7769,
413,
3439,
2590,
578,
12770,
5274,
1947,
903,
2583,
283,
31573,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5381,
16189,
4851,
1978,
951,
41,
28202,
1477,
273,
2468,
9462,
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.4.18;
import './SafeMath.sol';
import './AssetRegistryStorage.sol';
import './IERC721Base.sol';
import './IERC721Receiver.sol';
import './ERC165.sol';
contract ERC721Base is AssetRegistryStorage, IERC721Base, ERC165 {
using SafeMath for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
bytes4 private constant InterfaceId_ERC165 = 0x01ffc9a7;
/*
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
bytes4 private constant Old_InterfaceId_ERC721 = 0x7c0633c6;
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
//
// Global Getters
//
/**
* @dev Gets the total amount of assets stored by the contract
* @return uint256 representing the total amount of assets
*/
function totalSupply() external view returns (uint256) {
return _totalSupply();
}
function _totalSupply() internal view returns (uint256) {
return _count;
}
//
// Asset-centric getter functions
//
/**
* @dev Queries what address owns an asset. This method does not throw.
* In order to check if the asset exists, use the `exists` function or check if the
* return value of this call is `0`.
* @return uint256 the assetId
*/
function ownerOf(uint256 assetId) external view returns (address) {
return _ownerOf(assetId);
}
function _ownerOf(uint256 assetId) internal view returns (address) {
return _holderOf[assetId];
}
//
// Holder-centric getter functions
//
/**
* @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) external view returns (uint256) {
return _balanceOf(owner);
}
function _balanceOf(address owner) internal view returns (uint256) {
return _assetsOf[owner].length;
}
//
// Authorization getters
//
/**
* @dev Query whether an address has been authorized to move any assets on behalf of someone else
* @param operator the address that might be authorized
* @param assetHolder the address that provided the authorization
* @return bool true if the operator has been authorized to move any assets
*/
function isApprovedForAll(address assetHolder, address operator)
external view returns (bool)
{
return _isApprovedForAll(assetHolder, operator);
}
function _isApprovedForAll(address assetHolder, address operator)
internal view returns (bool)
{
return _operators[assetHolder][operator];
}
/**
* @dev Query what address has been particularly authorized to move an asset
* @param assetId the asset to be queried for
* @return bool true if the asset has been approved by the holder
*/
function getApproved(uint256 assetId) external view returns (address) {
return _getApprovedAddress(assetId);
}
function getApprovedAddress(uint256 assetId) external view returns (address) {
return _getApprovedAddress(assetId);
}
function _getApprovedAddress(uint256 assetId) internal view returns (address) {
return _approval[assetId];
}
/**
* @dev Query if an operator can move an asset.
* @param operator the address that might be authorized
* @param assetId the asset that has been `approved` for transfer
* @return bool true if the asset has been approved by the holder
*/
function isAuthorized(address operator, uint256 assetId) external view returns (bool) {
return _isAuthorized(operator, assetId);
}
function _isAuthorized(address operator, uint256 assetId) internal view returns (bool)
{
require(operator != 0);
address owner = _ownerOf(assetId);
if (operator == owner) {
return true;
}
return _isApprovedForAll(owner, operator) || _getApprovedAddress(assetId) == operator;
}
//
// Authorization
//
/**
* @dev Authorize a third party operator to manage (send) msg.sender's asset
* @param operator address to be approved
* @param authorized bool set to true to authorize, false to withdraw authorization
*/
function setApprovalForAll(address operator, bool authorized) external {
return _setApprovalForAll(operator, authorized);
}
function _setApprovalForAll(address operator, bool authorized) internal {
if (authorized) {
require(!_isApprovedForAll(msg.sender, operator));
_addAuthorization(operator, msg.sender);
} else {
require(_isApprovedForAll(msg.sender, operator));
_clearAuthorization(operator, msg.sender);
}
emit ApprovalForAll(msg.sender, operator, authorized);
}
/**
* @dev Authorize a third party operator to manage one particular asset
* @param operator address to be approved
* @param assetId asset to approve
*/
function approve(address operator, uint256 assetId) external {
address holder = _ownerOf(assetId);
require(msg.sender == holder || _isApprovedForAll(msg.sender, holder));
require(operator != holder);
if (_getApprovedAddress(assetId) != operator) {
_approval[assetId] = operator;
emit Approval(holder, operator, assetId);
}
}
function _addAuthorization(address operator, address holder) private {
_operators[holder][operator] = true;
}
function _clearAuthorization(address operator, address holder) private {
_operators[holder][operator] = false;
}
//
// Internal Operations
//
function _addAssetTo(address to, uint256 assetId) internal {
_holderOf[assetId] = to;
uint256 length = _balanceOf(to);
_assetsOf[to].push(assetId);
_indexOfAsset[assetId] = length;
_count = _count.add(1);
}
function _removeAssetFrom(address from, uint256 assetId) internal {
uint256 assetIndex = _indexOfAsset[assetId];
uint256 lastAssetIndex = _balanceOf(from).sub(1);
uint256 lastAssetId = _assetsOf[from][lastAssetIndex];
_holderOf[assetId] = 0;
// Insert the last asset into the position previously occupied by the asset to be removed
_assetsOf[from][assetIndex] = lastAssetId;
// Resize the array
_assetsOf[from][lastAssetIndex] = 0;
_assetsOf[from].length--;
// Remove the array if no more assets are owned to prevent pollution
if (_assetsOf[from].length == 0) {
delete _assetsOf[from];
}
// Update the index of positions for the asset
_indexOfAsset[assetId] = 0;
_indexOfAsset[lastAssetId] = assetIndex;
_count = _count.sub(1);
}
function _clearApproval(address holder, uint256 assetId) internal {
if (_ownerOf(assetId) == holder && _approval[assetId] != 0) {
_approval[assetId] = 0;
emit Approval(holder, 0, assetId);
}
}
//
// Supply-altering functions
//
function _generate(uint256 assetId, address beneficiary) internal {
require(_holderOf[assetId] == 0);
_addAssetTo(beneficiary, assetId);
emit Transfer(0, beneficiary, assetId);
}
function _destroy(uint256 assetId) internal {
address holder = _holderOf[assetId];
require(holder != 0);
_removeAssetFrom(holder, assetId);
emit Transfer(holder, 0, assetId);
}
//
// Transaction related operations
//
modifier onlyHolder(uint256 assetId) {
require(_ownerOf(assetId) == msg.sender);
_;
}
modifier onlyAuthorized(uint256 assetId) {
require(_isAuthorized(msg.sender, assetId));
_;
}
modifier isCurrentOwner(address from, uint256 assetId) {
require(_ownerOf(assetId) == from);
_;
}
modifier isDestinataryDefined(address destinatary) {
require(destinatary != 0);
_;
}
modifier destinataryIsNotHolder(uint256 assetId, address to) {
require(_ownerOf(assetId) != to);
_;
}
/**
* @dev Alias of `safeTransferFrom(from, to, assetId, '')`
*
* @param from address that currently owns an asset
* @param to address to receive the ownership of the asset
* @param assetId uint256 ID of the asset to be transferred
*/
function safeTransferFrom(address from, address to, uint256 assetId) external {
return _doTransferFrom(from, to, assetId, '', true);
}
/**
* @dev Securely transfers the ownership of a given asset from one address to
* another address, calling the method `onNFTReceived` on the target address if
* there's code associated with it
*
* @param from address that currently owns an asset
* @param to address to receive the ownership of the asset
* @param assetId uint256 ID of the asset to be transferred
* @param userData bytes arbitrary user information to attach to this transfer
*/
function safeTransferFrom(address from, address to, uint256 assetId, bytes userData) external {
return _doTransferFrom(from, to, assetId, userData, true);
}
/**
* @dev Transfers the ownership of a given asset from one address to another address
* Warning! This function does not attempt to verify that the target address can send
* tokens.
*
* @param from address sending the asset
* @param to address to receive the ownership of the asset
* @param assetId uint256 ID of the asset to be transferred
*/
function transferFrom(address from, address to, uint256 assetId) external {
return _doTransferFrom(from, to, assetId, '', false);
}
function _doTransferFrom(
address from,
address to,
uint256 assetId,
bytes userData,
bool doCheck
)
onlyAuthorized(assetId)
internal
{
_moveToken(from, to, assetId, userData, doCheck);
}
function _moveToken(
address from,
address to,
uint256 assetId,
bytes userData,
bool doCheck
)
isDestinataryDefined(to)
destinataryIsNotHolder(assetId, to)
isCurrentOwner(from, assetId)
private
{
address holder = _holderOf[assetId];
_clearApproval(holder, assetId);
_removeAssetFrom(holder, assetId);
_addAssetTo(to, assetId);
emit Transfer(holder, to, assetId);
if (doCheck && _isContract(to)) {
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
require(
IERC721Receiver(to).onERC721Received(
msg.sender, holder, assetId, userData
) == ERC721_RECEIVED
);
}
}
/**
* Internal function that moves an asset from one holder to another
*/
/**
* @dev Returns `true` if the contract implements `interfaceID` and `interfaceID` is not 0xffffffff, `false` otherwise
* @param _interfaceID The interface identifier, as specified in ERC-165
*/
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
if (_interfaceID == 0xffffffff) {
return false;
}
return _interfaceID == InterfaceId_ERC165 || _interfaceID == Old_InterfaceId_ERC721 || _interfaceID == InterfaceId_ERC721;
}
//
// Utilities
//
function _isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
| * @dev Authorize a third party operator to manage (send) msg.sender's asset @param operator address to be approved @param authorized bool set to true to authorize, false to withdraw authorization/ | function setApprovalForAll(address operator, bool authorized) external {
return _setApprovalForAll(operator, authorized);
}
| 1,819,702 | [
1,
18987,
279,
12126,
18285,
3726,
358,
10680,
261,
4661,
13,
1234,
18,
15330,
1807,
3310,
225,
3726,
1758,
358,
506,
20412,
225,
10799,
1426,
444,
358,
638,
358,
12229,
16,
629,
358,
598,
9446,
6093,
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,
444,
23461,
1290,
1595,
12,
2867,
3726,
16,
1426,
10799,
13,
3903,
288,
203,
565,
327,
389,
542,
23461,
1290,
1595,
12,
9497,
16,
10799,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x34790dfca967661FDb429bE4C98c78a224E6a12d/sources/CR7.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Cristiano Ronaldo", "CR7") {
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 = 160;
uint256 _buyLiquidityFee = 40;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 320;
uint256 _sellLiquidityFee = 80;
uint256 _sellDevFee = 0;
uint256 totalSupply = 100000000 * 1e18;
maxTokensForSwapback = totalSupply;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
totalFeesBuy = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
totalFeesSell = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(0xB34A13046c002Aa9A04bb5d021c25E379DFc36B1);
devWallet = address(msg.sender);
lpWallet = msg.sender;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromFees(marketingWallet, true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
excludeFromMaxTransaction(marketingWallet, true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 9,147,544 | [
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,
12893,
376,
2779,
83,
534,
9528,
2896,
3113,
315,
5093,
27,
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,
25430,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
8063,
31,
203,
3639,
2254,
5034,
389,
2
] |
./full_match/1313161554/0xcDcfe4C20d69827890f436AfC9509CC6E5c0D037/sources/src/UniswapConfig.sol | @notice The max number of tokens this contract is hardcoded to support @dev Do not change this variable without updating all the fields throughout the contract. | uint256 public constant maxTokens = 25;
| 13,232,766 | [
1,
1986,
943,
1300,
434,
2430,
333,
6835,
353,
7877,
24808,
358,
2865,
225,
2256,
486,
2549,
333,
2190,
2887,
9702,
777,
326,
1466,
3059,
659,
326,
6835,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
5381,
943,
5157,
273,
6969,
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
] |
pragma solidity ^0.6.0;
contract initializable5 { //inject NONSTANDARD NAMING
bool private initialized;
bool private initializing;
modifier INITIALIZER65() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
}
function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING
}
function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING
address private _owner;
event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
__OWNABLE_INIT_UNCHAINED84();
}
function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER78();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED52(address(0), msgSender);
}
function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER81() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED52(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED52(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
library safemath14 { //inject NONSTANDARD NAMING
function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB60(a, b, "SafeMath: subtraction overflow");
}
function SUB60(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV54(a, b, "SafeMath: division by zero");
}
function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD56(a, b, "SafeMath: modulo by zero");
}
function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
interface ierc2086 { //inject NONSTANDARD NAMING
function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library console87 { //inject NONSTANDARD NAMING
address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address36;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG40() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log()"));
}
function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOG40(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
interface iuniswapv2factory11 { //inject NONSTANDARD NAMING
event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO47() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO7(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING
}
contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING
using safemath14 for uint256;
function INITIALIZE58( //inject NONSTANDARD NAMING
address _NANOCOREAddress,
address _WETHAddress,
address _uniswapFactory
) public INITIALIZER65 {
ownableupgradesafe25.__OWNABLE_INIT13();
nanocoreTokenAddress = _NANOCOREAddress;
WETHAddress = _WETHAddress;
tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress);
feePercentX100 = 15;
paused = false; // We start paused until sync post LGE happens.
}
address tokenUniswapPair;
iuniswapv2factory11 public uniswapFactory;
address internal WETHAddress;
address nanocoreTokenAddress;
address nanocoreVaultAddress;
uint8 public feePercentX100; // max 255 = 25.5% artificial clamp
uint256 public lastTotalSupplyOfLPTokens;
bool paused;
// Pausing transfers of the token
function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING
paused = _pause;
}
function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING
feePercentX100 = _feeMultiplier;
}
function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING
nanocoreVaultAddress = _nanocoreVaultAddress;
}
function SYNC99() public { //inject NONSTANDARD NAMING
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING
address sender,
address recipient, // unusued maybe use din future
uint256 amount
) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount)
{
require(paused == false, "FEE APPROVER: Transfers Paused");
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
// console.log("sender is " , sender);
// console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair);
// console.log("Old LP supply", lastTotalSupplyOfLPTokens);
// console.log("Current LP supply", _LPSupplyOfPairTotal);
if(sender == tokenUniswapPair)
require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden");
// console.log('Sender is pair' , sender == tokenUniswapPair);
// console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal);
if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop
console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it)
transferToFeeDistributorAmount = 0;
transferToAmount = amount;
}
else {
console87.LOG40("Normal fee transfer");
transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000);
transferToAmount = amount.SUB60(transferToFeeDistributorAmount);
}
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
} | inject NONSTANDARD NAMING
| function LOG40(uint p0, string memory p1, address p2, address p3) internal view { | 1,018,991 | [
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,
2018,
7132,
12,
11890,
293,
20,
16,
533,
3778,
293,
21,
16,
1758,
293,
22,
16,
1758,
293,
23,
13,
2713,
1476,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IUniswapV2Pair {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_transferOwnership(_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 {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// Hostilezone ERC-721 Contract
interface HostileZoneNft {
function walletOfOwner(address _owner) external view returns (uint256[] memory);
function ownerOf(uint256 tokenId) external view returns (address owner);
}
contract HostileZone is Ownable, IERC20{
// pairs in AMM
mapping (address => bool) public _isPool;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
// Fees wallets.
address public marketWallet;
address public developerWallet;
address public GameDevelopWallet;
address public liquidityWallet;
// token
string private _name = "HostileZoneOfficial";
string private _symbol = "Htz";
uint8 private _decimals = 18;
// supply
uint256 public _total = 500000000;
uint256 private _totalSupply;
// addresses
address public _uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public _pair = address(0);
// pause the contract at start
bool public paused = true;
bool public poolCreated;
// set time based limitation
bool public isLimited = true;
uint256 public maxTransactionAmount = 100000 * 10 ** 18;
uint256 public buyTotalFees;
uint256 public sellTotalFees;
// exclusions
mapping (address => bool) public _isExcludedFromBuyFees; // buy fees exclusion
mapping (address => bool) public _isExcludedFromSellFees; // sell fees exclusion
mapping (address => bool) public _isExcludedMaxTransactionAmount; // max amount per transactions (any time) exclusion
mapping (address => bool) public _isExcludedFromTimeTx; // max number of transactions in lower time scale exclusion
mapping (address => bool) public _isExcludedFromTimeAmount; // max amount traded in higher time scale exclusion
mapping (address => bool) public _isExcludedFromMaxWallet; // max wallet amount exclusion
// wallets metrics
mapping(address => uint256) public _previousFirstTradeTime; // first transaction in lower time scale
mapping(address => uint256) public _numberOfTrades; // number of trades in lower time scale
mapping(address => uint256) public _largerPreviousFirstTradeTime; // first transaction in larger time scale
mapping(address => uint256) public _largerCurrentAmountTraded; // amount traded in large time scale
// limitations values
uint256 public largerTimeLimitBetweenTx = 7 days; // larger time scale
uint256 public timeLimitBetweenTx = 1 hours; // lower time scale
uint256 public txLimitByTime = 3; // number limit of transactions (lower scale)
uint256 public largerAmountLimitByTime = 1500000 * 10 ** _decimals; // transaction amounts limits (larger scale)
uint256 public maxByWallet = 600000 * 10 ** 18; // max token in wallet
// Buy Fees
uint256 _buyMarketingFee;
uint256 _buyLiquidityFee;
uint256 _buyDevFee;
uint256 _buyGameDevelopingFee;
uint256 public buyDiscountLv1;
uint256 public buyDiscountLv2;
// Sell Fees
uint256 _sellMarketingFee;
uint256 _sellLiquidityFee;
uint256 _sellDevFee;
uint256 _sellGameDevelopingFee;
uint256 public sellDiscountLv1;
uint256 public sellDiscountLv2;
// Tokens routing
uint256 public tokensForMarketing;
uint256 public tokensForDev;
uint256 public tokensForGameDev;
uint256 public tokensForLiquidity;
// uniswap v2 interface
IUniswapV2Router02 private UniV2Router;
// nft address to check discount
address hostileZoneNftAddress;
//Legendary NFTs
uint256[] public legendaryNFTs;
constructor() {
// initial supply to mint
_totalSupply = 100000000 * 10 ** _decimals;
_balances[_msgSender()] += _totalSupply;
emit Transfer(address(0), _msgSender(), _totalSupply);
// set router v2
UniV2Router = IUniswapV2Router02(_uniRouter);
// wallets setting
marketWallet = 0x7F22B4D77EAa010C53Ad7383F93725Db405f44C7;
developerWallet = 0xaE859cc7FD075cBff43E2E659694fb1F7aeE0ecF;
GameDevelopWallet = 0xab9cc7E0E2B86d77bE6059bC69C4db3A9B53a6bf;
liquidityWallet = 0xCD01C9F709535FdfdB1cd943C7C01D58714a0Ca6;
// pair address
_pair = IUniswapV2Factory(UniV2Router.factory()).createPair(address(this), UniV2Router.WETH());
// pair is set as pair
_isPool[_pair] = true;
// basic exclusions
// buy fees exclusions
_isExcludedFromBuyFees[_msgSender()] = true;
_isExcludedFromBuyFees[address(this)] = true;
// sell fees exclusions
_isExcludedFromSellFees[_msgSender()] = true;
_isExcludedFromSellFees[address(this)] = true;
// max transaction amount any time
_isExcludedMaxTransactionAmount[_msgSender()] = true;
_isExcludedMaxTransactionAmount[_pair] = true;
_isExcludedMaxTransactionAmount[address(this)] = true;
// lower scale time number of transactions exclusions
_isExcludedFromTimeTx[_msgSender()] = true;
_isExcludedFromTimeTx[_pair] = true;
_isExcludedFromTimeTx[address(this)] = true;
// larger scale time amount exclusion
_isExcludedFromTimeAmount[_msgSender()] = true;
_isExcludedFromTimeAmount[_pair] = true;
_isExcludedFromTimeAmount[address(this)] = true;
// max wallet in exclusions
_isExcludedFromMaxWallet[_msgSender()] = true;
_isExcludedFromMaxWallet[_pair] = true;
_isExcludedFromMaxWallet[address(this)] = true;
// buy fees
_buyMarketingFee = 4;
_buyLiquidityFee = 5;
_buyDevFee = 2;
_buyGameDevelopingFee = 2;
buyTotalFees = _buyMarketingFee + _buyDevFee + _buyLiquidityFee + _buyGameDevelopingFee; // 13%
buyDiscountLv1 = 1;
buyDiscountLv2 = 4;
// Sell Fees
_sellMarketingFee = 5;
_sellLiquidityFee = 9;
_sellDevFee = 2;
_sellGameDevelopingFee = 3;
sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee + _sellGameDevelopingFee; // 19%
sellDiscountLv1 = 2;
sellDiscountLv2 = 5;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public 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) {
require (_allowances[sender][_msgSender()] >= amount, "ERC20: transfer amount exceeds allowance");
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount);
return true;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(_balances[sender] >= amount, "ERC20: transfer exceeds balance");
require(amount > 450 * 10 ** 18, "HostileZone: cannot transfer less than 450 tokens.");
require(!paused, "HostileZone: trading isn't enabled yet.");
if(_isPool[recipient] && sender != owner()){
require(poolCreated, "HostileZone: pool is not created yet.");
}
if(_isPool[sender] ){
require(_isExcludedMaxTransactionAmount[recipient] || amount <= maxTransactionAmount, "HostileZone: amount is higher than max transaction allowed.");
}
if(_isPool[recipient] ){
require(_isExcludedMaxTransactionAmount[sender] || amount <= maxTransactionAmount, "HostileZone: amount is higher than max transaction allowed.");
}
// amount limit
// check max transactions exclusion or max transaction amount limits
require(_isExcludedMaxTransactionAmount[sender] || amount <= maxTransactionAmount, "HostileZone: amount is higher than max transaction allowed.");
// check max wallet in exclusion or max transaction amount limits
require(_isExcludedFromMaxWallet[recipient] || amount + _balances[recipient] <= maxByWallet, "HostileZone: amount is higher than max wallet amount allowed.");
// time scales limitation
if(isLimited){
// check if it's a buy or sell transaction
// some limits only to apply on buy and sell
if( _isPool[recipient] ) {
checkTimeLimits(sender, amount);
} else if(_isPool[sender] ){
checkTimeLimits(recipient, amount);
}
}
uint256 fees = 0;
bool takeBuyFee;
bool takeSellFee;
// Should contract take buy fees
if( !_isExcludedFromBuyFees[recipient] && _isPool[sender] && buyTotalFees > 0 ) {
takeBuyFee = true;
}
// Should contract take sell fees
if( !_isExcludedFromSellFees[sender] && _isPool[recipient] && sellTotalFees > 0 ) {
takeSellFee = true;
}
if(takeBuyFee){
// check discount for buy fees
uint256 buyTotalFeesWithDiscount = calculateFeeBuyAmount(recipient);
if(buyTotalFeesWithDiscount > 0){
// add total buy fees to fees
fees += uint256(uint256(amount * buyTotalFeesWithDiscount) / 100);
// Buy: liquidity fees calculation
tokensForLiquidity = uint256(uint256(fees * _buyLiquidityFee) / buyTotalFeesWithDiscount);
_balances[liquidityWallet] += tokensForLiquidity;
emit Transfer(sender, liquidityWallet, tokensForLiquidity);
// Buy: dev fees calculation
tokensForDev = uint256(uint256(fees * _buyDevFee) / buyTotalFeesWithDiscount);
_balances[developerWallet] += tokensForDev;
emit Transfer(sender, developerWallet, tokensForDev);
// Buy: marketing fees calculation
tokensForMarketing = uint256(uint256(fees * _buyMarketingFee) / buyTotalFeesWithDiscount);
_balances[marketWallet] += tokensForMarketing;
emit Transfer(sender, marketWallet, tokensForMarketing);
// Buy: game development fees calculation
tokensForGameDev = uint256(uint256(fees * _buyGameDevelopingFee) / buyTotalFeesWithDiscount);
_balances[GameDevelopWallet] += tokensForGameDev;
emit Transfer(sender, GameDevelopWallet, tokensForGameDev);
// reset some splited fees values
resetTokenRouting();
}
}
if(takeSellFee) {
// check discounts for sell fees
uint256 sellTotalFeesWithDiscount = calculateFeeSellAmount(sender);
if(sellTotalFeesWithDiscount > 0){
// add total sell fees amount to fees
fees += uint256(uint256(amount * sellTotalFeesWithDiscount) / 100);
// Sell: liquidity fees calculation
tokensForLiquidity = uint256(uint256(fees * _sellLiquidityFee) / sellTotalFeesWithDiscount);
_balances[liquidityWallet] += tokensForLiquidity;
emit Transfer(sender, liquidityWallet, tokensForLiquidity);
// Sell: dev fees calculation
tokensForDev += uint256(uint256(fees * _sellDevFee) / sellTotalFeesWithDiscount);
_balances[developerWallet] += tokensForDev;
emit Transfer(sender, developerWallet, tokensForDev);
// Sell: marketing fees calculation
tokensForMarketing += uint256(uint256(fees * _sellMarketingFee) / sellTotalFeesWithDiscount);
_balances[marketWallet] += tokensForMarketing;
emit Transfer(sender, marketWallet, tokensForMarketing);
// Sell: game development fees calculation
tokensForGameDev += uint256(uint256(fees * _sellGameDevelopingFee) / sellTotalFeesWithDiscount);
_balances[GameDevelopWallet] += tokensForGameDev;
emit Transfer(sender, GameDevelopWallet, tokensForGameDev);
// reset some splited fees values
resetTokenRouting();
}
}
// amount to transfer minus fees
uint256 amountMinusFees = amount - fees;
// decrease sender balance
_balances[sender] -= amount;
// increase recipient balance
_balances[recipient] += amountMinusFees;
// if it's a sell
if( _isPool[recipient]) {
// add amount to larger time scale by user
_largerCurrentAmountTraded[sender] += amount;
// add 1 transaction to lower scale user count
_numberOfTrades[sender] += 1;
// it's a buy
} else if(_isPool[sender]){
// add amount to larger time scale by user
_largerCurrentAmountTraded[recipient] += amount;
// add 1 transaction to lower scale user count
_numberOfTrades[recipient] += 1;
}
// transfer event
emit Transfer(sender, recipient, amountMinusFees);
}
function checkTimeLimits(address _address, uint256 _amount) private {
// if higher than limit for lower time scale: reset all sender values
if( _previousFirstTradeTime[_address] == 0){
_previousFirstTradeTime[_address] = block.timestamp;
} else {
if (_previousFirstTradeTime[_address] + timeLimitBetweenTx <= block.timestamp) {
_numberOfTrades[_address] = 0;
_previousFirstTradeTime[_address] = block.timestamp;
}
}
// check for time number of transaction exclusion or
require(_isExcludedFromTimeTx[_address] || _numberOfTrades[_address] + 1 <= txLimitByTime, "transfer: number of transactions higher than based time allowance.");
// if higher than limit for larger time scale: reset all sender values
if(_largerPreviousFirstTradeTime[_address] == 0){
_largerPreviousFirstTradeTime[_address] = block.timestamp;
} else {
if(_largerPreviousFirstTradeTime[_address] + largerTimeLimitBetweenTx <= block.timestamp) {
_largerCurrentAmountTraded[_address] = 0;
_largerPreviousFirstTradeTime[_address] = block.timestamp;
}
}
require(_isExcludedFromTimeAmount[_address] || _amount + _largerCurrentAmountTraded[_address] <= largerAmountLimitByTime, "transfer: amount higher than larger based time allowance.");
}
// Calculate amount of buy discount .
function calculateFeeBuyAmount(address _address) public view returns (uint256) {
uint256 discountLvl = checkForDiscount(_address);
if(discountLvl == 1){
return buyTotalFees - buyDiscountLv1;
}else if(discountLvl == 2){
return buyTotalFees - buyDiscountLv2;
}
else if(discountLvl == 3){
return 0;
}
return buyTotalFees;
}
// Calculate amount of sell discount .
function calculateFeeSellAmount(address _address) public view returns (uint256) {
uint256 discountLvl = checkForDiscount(_address);
if(discountLvl == 1){
return sellTotalFees - sellDiscountLv1;
} else if(discountLvl == 2){
return sellTotalFees - sellDiscountLv2;
} else if(discountLvl == 3){
return 0;
}
return sellTotalFees;
}
// enable fees discounts by checking the number of nfts in HostileZone nft contract
function checkForDiscount(address _address) public view returns (uint256) {
if(hostileZoneNftAddress != address(0)) {
uint256 NFTAmount = HostileZoneNft(hostileZoneNftAddress).walletOfOwner(_address).length;
if(checkForNFTDiscount(_address)){
return 3;
}
else if(NFTAmount > 0 && NFTAmount <= 3){
return 1;
} else if (NFTAmount > 3 && NFTAmount <= 9){
return 2;
} else if (NFTAmount >= 10 ){
return 3;
}
}
return 0;
}
// mint
function mint(uint256 amount) external onlyOwner {
require (_totalSupply + amount <= _total * 10 ** _decimals, "HostileZone: amount higher than max.");
_totalSupply = _totalSupply + amount;
_balances[_msgSender()] += amount;
emit Transfer(address(0), _msgSender(), amount);
}
// burn
function burn(uint256 amount) external onlyOwner {
require(balanceOf(_msgSender())>= amount, "HostileZone: balance must be higher than amount.");
_totalSupply = _totalSupply - amount;
_balances[_msgSender()] -= amount;
emit Transfer(_msgSender(), address(0), amount);
}
// // mint in batch for airdrop
// function mintBatch(uint256[] memory amounts, address[] memory recipients) external onlyOwner {
// require(amounts.length > 0, "HostileZone: amounts list length should size higher than 0.");
// require(amounts.length == recipients.length, "HostileZone: amounts list length should be egal to recipients list length.");
// uint256 totalAmount;
// for(uint256 i = 0; i < amounts.length; i++){
// require(amounts[i] > 0, "HostileZone: amount should be higher than 0." );
// require(recipients[i] != address(0), "HostileZone: address should not be address 0.");
// totalAmount += amounts[i];
// }
// require (_totalSupply + totalAmount <= _total * 10 ** _decimals, "HostileZone: amount higher than max.");
// for(uint256 i = 0; i < amounts.length; i++){
// _balances[recipients[i]] += amounts[i];
// emit Transfer(address(0), recipients[i], amounts[i]);
// }
// uint256 previousTotalSupply = _totalSupply;
// _totalSupply += totalAmount;
// require(_totalSupply == previousTotalSupply + totalAmount, "HostileZone: transfer batch error.");
// }
// Disable fees.
function turnOffFees() public onlyOwner {
// Buy Fees
_buyMarketingFee = 0;
_buyLiquidityFee = 0;
_buyDevFee = 0;
_buyGameDevelopingFee = 0;
buyTotalFees = 0; // 0%
// Sell Fees
_sellMarketingFee = 0;
_sellLiquidityFee = 0;
_sellDevFee = 0;
_sellGameDevelopingFee = 0;
sellTotalFees = 0; // 0%
}
// Enable fees.
function turnOnFees() public onlyOwner {
// Buy Fees
_buyMarketingFee = 4;
_buyLiquidityFee = 5;
_buyDevFee = 2;
_buyGameDevelopingFee = 2;
buyTotalFees = _buyMarketingFee + _buyDevFee + _buyLiquidityFee + _buyGameDevelopingFee; // 13%
// Sell Fees
_sellMarketingFee = 5;
_sellLiquidityFee = 9;
_sellDevFee = 2;
_sellGameDevelopingFee = 3;
sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee + _sellGameDevelopingFee; // 19%
}
// to reset token routing values
// in order to calculate fees properly
function resetTokenRouting() private {
tokensForMarketing = 0;
tokensForDev = 0;
tokensForGameDev = 0;
tokensForLiquidity = 0;
}
// to add liquidity to uniswap once
function addLiquidity(uint256 _tokenAmountWithoutDecimals) external payable onlyOwner {
uint256 tokenAmount = _tokenAmountWithoutDecimals * 10 ** _decimals;
require(_pair != address(0), "addLiquidity: pair isn't create yet.");
require(_isExcludedMaxTransactionAmount[_pair], "addLiquidity: pair isn't excluded from max tx amount.");
(uint112 reserve0, uint112 reserve1,) = IUniswapV2Pair(_pair).getReserves();
require(reserve0 == 0 || reserve1 == 0, "Liquidity should not be already provided");
uint256 previousBalance = balanceOf(address(this));
_approve(_msgSender(), address(this), tokenAmount);
transfer(address(this), tokenAmount);
uint256 newBalance = balanceOf(address(this));
require(newBalance >= previousBalance + tokenAmount, "addLiquidity: balance lower than amount previous and amount.");
_approve(address(this), address(UniV2Router), tokenAmount);
UniV2Router.addLiquidityETH{value: msg.value}(
address(this),
tokenAmount,
0,
0,
owner(),
block.timestamp + 60
);
}
// excluder
// exclude any wallet for contact buy fees
function excludeFromBuyFees(address _address, bool _exclude) external onlyOwner {
_isExcludedFromBuyFees[_address] = _exclude;
}
// exclude any wallet for contact sell fees
function excludeFromSellFees(address _address, bool _exclude) external onlyOwner {
_isExcludedFromSellFees[_address] = _exclude;
}
// exclude any wallet for max transaction amount any time
function excludedMaxTransactionAmount(address _address, bool _exclude) external onlyOwner {
_isExcludedMaxTransactionAmount[_address] = _exclude;
}
// exclude any wallet for limited number of transactions in lower time scale
function excludedFromTimeTx(address _address, bool _exclude) external onlyOwner {
_isExcludedFromTimeTx[_address] = _exclude;
}
// exclude any wallet for limited amount to trade in larger time scale
function excludedFromTimeAmount(address _address, bool _exclude) external onlyOwner {
_isExcludedFromTimeAmount[_address] = _exclude;
}
// exclude any wallet from max amount in
function excludedFromMaxWallet(address _address, bool _exclude) external onlyOwner {
_isExcludedFromMaxWallet[_address] = _exclude;
}
// setter
// set a pair in any automated market maker
function setPool(address _addr, bool _enable) external onlyOwner {
_isPool[_addr] = _enable;
_isExcludedMaxTransactionAmount[_addr] = _enable;
_isExcludedFromTimeTx[_addr] = _enable;
_isExcludedFromTimeAmount[_addr] = _enable;
_isExcludedFromMaxWallet[_addr] = _enable;
}
// set max transcation amount any times
function setMaxTransactionAmount(uint256 _maxTransactionAmount) external onlyOwner {
require(_maxTransactionAmount >= 100000 * 10 ** _decimals, "HostileZone: amount should be higher than 0.1% of totalSupply.");
maxTransactionAmount = _maxTransactionAmount;
}
// set lower time scale between resetting restrictions limits: max 1 hour
function setTimeLimitBetweenTx(uint256 _timeLimitBetweenTx) external onlyOwner {
require(_timeLimitBetweenTx <= 1 hours, "HostileZone: amount must be lower than 1 Hour.");
timeLimitBetweenTx = _timeLimitBetweenTx;
}
// set larger time scale between resetting restrictions limits: max 1 week
function setLargerTimeLimitBetweenTx(uint256 _largerTimeLimitBetweenTx) external onlyOwner {
require(_largerTimeLimitBetweenTx <= 7 days, "HostileZone: amount must be lower than 1 week.");
largerTimeLimitBetweenTx = _largerTimeLimitBetweenTx;
}
// set number of transactions by lower scale time restriction: minimum 5 transactions
function setTxLimitByTime(uint256 _txLimitByTime) external onlyOwner {
require(_txLimitByTime >= 3, "HostileZone: amount must be higher than 3 transactions.");
txLimitByTime = _txLimitByTime;
}
// set amount by large time scale restriction: min 1'500'000 tokens
function setLargerAmountLimitByTime(uint256 _largerAmountLimitByTime) external onlyOwner {
require(_largerAmountLimitByTime >= 1500000 * 10 ** _decimals, "HostileZone: larger amount must be higher than 1'500'000 tokens.");
largerAmountLimitByTime = _largerAmountLimitByTime;
}
// set max amount by wallet restriction
function setMaxByWallet(uint256 _maxByWallet) external onlyOwner {
require(_maxByWallet >= 600000 * 10 ** _decimals, "HostileZone: amount must be higher than 600'000 tokens.");
maxByWallet = _maxByWallet;
}
// could only be set once
function setPause() external onlyOwner {
paused = false;
}
// set time restrict limit
function setLimited(bool _isLimited) external onlyOwner {
isLimited = _isLimited;
}
function setNftAddress(address _hostileZoneNftAddress) external onlyOwner {
hostileZoneNftAddress = _hostileZoneNftAddress;
}
function setMarketWallet(address _marketWallet) external onlyOwner {
_isExcludedMaxTransactionAmount[_marketWallet] = true;
_isExcludedFromTimeTx[_marketWallet] = true;
_isExcludedFromTimeAmount[_marketWallet] = true;
_isExcludedFromMaxWallet[_marketWallet] = true;
_isExcludedFromBuyFees[_marketWallet] = true;
_isExcludedFromSellFees[_marketWallet] = true;
}
function setDeveloperWallet(address _developerWallet) external onlyOwner {
developerWallet = _developerWallet;
_isExcludedMaxTransactionAmount[_developerWallet] = true;
_isExcludedFromTimeTx[_developerWallet] = true;
_isExcludedFromTimeAmount[_developerWallet] = true;
_isExcludedFromMaxWallet[_developerWallet] = true;
_isExcludedFromBuyFees[_developerWallet] = true;
_isExcludedFromSellFees[_developerWallet] = true;
}
function setGameDevelopWallet(address _GameDevelopWallet) external onlyOwner {
GameDevelopWallet = _GameDevelopWallet;
_isExcludedMaxTransactionAmount[_GameDevelopWallet] = true;
_isExcludedFromTimeTx[_GameDevelopWallet] = true;
_isExcludedFromTimeAmount[_GameDevelopWallet] = true;
_isExcludedFromMaxWallet[_GameDevelopWallet] = true;
_isExcludedFromBuyFees[_GameDevelopWallet] = true;
_isExcludedFromSellFees[_GameDevelopWallet] = true;
}
function setLiquidityWallet(address _liquidityWallet) external onlyOwner {
liquidityWallet = _liquidityWallet;
_isExcludedMaxTransactionAmount[_liquidityWallet] = true;
_isExcludedFromTimeTx[_liquidityWallet] = true;
_isExcludedFromTimeAmount[_liquidityWallet] = true;
_isExcludedFromMaxWallet[_liquidityWallet] = true;
_isExcludedFromBuyFees[_liquidityWallet] = true;
_isExcludedFromSellFees[_liquidityWallet] = true;
}
// set buy fees: max 33%
function setBuyFees(
uint256 buyMarketingFee,
uint256 buyLiquidityFee,
uint256 buyDevFee,
uint256 buyGameDevelopingFee,
uint256 _buyDiscountLv1,
uint256 _buyDiscountLv2
) external onlyOwner {
require(buyMarketingFee <= 20 && buyLiquidityFee <= 20 && buyDevFee <= 20 && buyGameDevelopingFee <= 20);
_buyMarketingFee = buyMarketingFee;
_buyLiquidityFee = buyLiquidityFee;
_buyDevFee = buyDevFee;
_buyGameDevelopingFee = buyGameDevelopingFee;
buyTotalFees = _buyMarketingFee + _buyDevFee + _buyLiquidityFee + _buyGameDevelopingFee;
buyDiscountLv1 = _buyDiscountLv1;
buyDiscountLv2 = _buyDiscountLv2;
require(buyTotalFees <= 33, "total fees cannot be higher than 33%.");
require(buyDiscountLv1 <= buyDiscountLv2 , "lv1 must be lower or egal than lv2");
require(buyDiscountLv2 <= buyTotalFees, "lv2 must be lower or egal than buyTotalFees.");
}
// set sell fees: max 33%
function setSellFees(
uint256 sellMarketingFee,
uint256 sellLiquidityFee,
uint256 sellDevFee,
uint256 sellGameDevelopingFee,
uint256 _sellDiscountLv1,
uint256 _sellDiscountLv2
) external onlyOwner {
require(sellMarketingFee <= 20 && sellLiquidityFee <= 20 && sellDevFee <= 20 && sellGameDevelopingFee <= 20);
_sellMarketingFee = sellMarketingFee;
_sellLiquidityFee = sellLiquidityFee;
_sellDevFee = sellDevFee;
_sellGameDevelopingFee = sellGameDevelopingFee;
sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee + _sellGameDevelopingFee;
sellDiscountLv1 = _sellDiscountLv1;
sellDiscountLv2 = _sellDiscountLv2;
require(sellTotalFees <= 33, "total fees cannot be higher than 33%.");
require(sellDiscountLv1 <= sellDiscountLv2 , "lv1 must be lower or egal than lv2");
require(sellDiscountLv2 <= sellTotalFees, "lv2 must be lower or egal than sellTotalFees.");
}
// pool created for the first time.
function setPoolCreated() external onlyOwner {
poolCreated = true;
}
// withdraw any ERC20 just in case
function tokenWithdraw(IERC20 _tokenAddress, uint256 _tokenAmount, bool _withdrawAll) external onlyOwner returns(bool){
uint256 tokenBalance = _tokenAddress.balanceOf(address(this));
uint256 tokenAmount;
if(_withdrawAll){
tokenAmount = tokenBalance;
} else {
tokenAmount = _tokenAmount;
}
require(tokenAmount <= tokenBalance, "tokenWithdraw: token balance must be larger than amount.");
_tokenAddress.transfer(owner(), tokenAmount);
return true;
}
// withdraw eth just in case
function withdrawEth(uint256 _ethAmount, bool _withdrawAll) external onlyOwner returns(bool){
uint256 ethBalance = address(this).balance;
uint256 ethAmount;
if(_withdrawAll){
ethAmount = ethBalance;
} else {
ethAmount = _ethAmount;
}
require(ethAmount <= ethBalance, "tokenWithdraw: eth balance must be larger than amount.");
(bool success,) = payable(owner()).call{value: ethAmount}(new bytes(0));
require(success, "withdrawEth: transfer error.");
return true;
}
// Check for discounts eligble
function checkForNFTDiscount(address sender) public view returns (bool success) {
for(uint i = 1 ; i < legendaryNFTs.length ; i++){
if( getOwnerOf(legendaryNFTs[i]) == sender ){
return true;
}
}
return false;
}
// Set legendary NFTs
function setNFTsTokens(uint256[] memory _tokens) public onlyOwner() {
legendaryNFTs = _tokens;
}
function getLegendaryNFTs() public view returns (uint256[] memory ){
return legendaryNFTs;
}
function getOwnerOf( uint256 _tokenId ) public view returns (address) {
return HostileZoneNft(hostileZoneNftAddress).ownerOf(_tokenId);
}
// Batch Transfer for multiple wallets.
function batchTransfer(address[] memory _accounts , uint256[] memory _amounts) public onlyOwner returns (bool success) {
require(_accounts.length == _amounts.length);
uint256 _totalTransfer = 0;
for(uint256 i = 0; i < _amounts.length ; i++ ) {
_totalTransfer += _amounts[i] * 10 ** 18;
}
require( balanceOf(msg.sender) >= _totalTransfer );
for(uint256 i = 0; i < _amounts.length ; i++ ) {
_balances[_accounts[i]] += _amounts[i] * 10 ** 18;
_balances[msg.sender] -= _amounts[i] * 10 ** 18;
emit Transfer(msg.sender , _accounts[i], _amounts[i] * 10 ** 18);
}
return true;
}
receive() external payable {}
fallback() external payable {}
} | excluder exclude any wallet for contact buy fees | function excludeFromBuyFees(address _address, bool _exclude) external onlyOwner {
_isExcludedFromBuyFees[_address] = _exclude;
}
| 5,850,894 | [
1,
338,
830,
89,
765,
4433,
1281,
9230,
364,
5388,
30143,
1656,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4433,
1265,
38,
9835,
2954,
281,
12,
2867,
389,
2867,
16,
1426,
389,
10157,
13,
3903,
1338,
5541,
288,
203,
3639,
389,
291,
16461,
1265,
38,
9835,
2954,
281,
63,
67,
2867,
65,
273,
389,
10157,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
import "./EtherFairyBase.sol";
// 요정의 랭킹을 제공하는 계약
contract FairyRank is EtherFairyBase {
// 최근에 태어난 순서대로 요정의 ID 목록을 가져옵니다.
function getFairyIdsByBirthTime() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 birthTime = fairies[i].birthTime;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].birthTime < birthTime) {
fairyIds[j] = fairyIds[j - 1];
} else {
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
// 소유주에 의해 추가된 레벨이 높은 순서대로 요정의 ID 목록을 가져옵니다.
function getFairyIdsByAppendedLevel() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 appendedLevel = fairies[i].appendedLevel;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].appendedLevel < appendedLevel) {
fairyIds[j] = fairyIds[j - 1];
} else {
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
// 레벨 당 HP 증가 포인트가 높은 순서대로 요정의 ID 목록을 가져옵니다.
function getFairyIdsByHPPointPerLevel() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 hpPointPerLevel = fairies[i].hpPointPerLevel;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].hpPointPerLevel < hpPointPerLevel) {
fairyIds[j] = fairyIds[j - 1];
} else {
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
// 레벨 당 공격 증가 포인트가 높은 순서대로 요정의 ID 목록을 가져옵니다.
function getFairyIdsByAttackPointPerLevel() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 attackPointPerLevel = fairies[i].attackPointPerLevel;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].attackPointPerLevel < attackPointPerLevel) {
fairyIds[j] = fairyIds[j - 1];
} else {
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
// 레벨 당 방어 증가 포인트가 높은 순서대로 요정의 ID 목록을 가져옵니다.
function getFairyIdsByDefencePointPerLevel() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 defencePointPerLevel = fairies[i].defencePointPerLevel;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].defencePointPerLevel < defencePointPerLevel) {
fairyIds[j] = fairyIds[j - 1];
} else {
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
// 레벨 당 민첩 증가 포인트가 높은 순서대로 요정의 ID 목록을 가져옵니다.
function getFairyIdsByAgilityPointPerLevel() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 agilityPointPerLevel = fairies[i].agilityPointPerLevel;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].agilityPointPerLevel < agilityPointPerLevel) {
fairyIds[j] = fairyIds[j - 1];
} else {
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
// 레벨 당 재치 증가 포인트가 높은 순서대로 요정의 ID 목록을 가져옵니다.
function getFairyIdsByDexterityPointPerLevel() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 dexterityPointPerLevel = fairies[i].dexterityPointPerLevel;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].dexterityPointPerLevel < dexterityPointPerLevel) {
fairyIds[j] = fairyIds[j - 1];
} else {
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
// 레벨 당 불 속성 증가 포인트가 높은 순서대로 요정의 ID 목록을 가져옵니다.
function getFairyIdsByFirePointPerLevel() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 firePointPerLevel = fairies[i].firePointPerLevel;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].firePointPerLevel < firePointPerLevel) {
fairyIds[j] = fairyIds[j - 1];
} else {
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
// 레벨 당 물 속성 증가 포인트가 높은 순서대로 요정의 ID 목록을 가져옵니다.
function getFairyIdsByWaterPointPerLevel() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 waterPointPerLevel = fairies[i].waterPointPerLevel;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].waterPointPerLevel < waterPointPerLevel) {
fairyIds[j] = fairyIds[j - 1];
} else {
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
// 레벨 당 바람 속성 증가 포인트가 높은 순서대로 요정의 ID 목록을 가져옵니다.
function getFairyIdsByWindPointPerLevel() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 windPointPerLevel = fairies[i].windPointPerLevel;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].windPointPerLevel < windPointPerLevel) {
fairyIds[j] = fairyIds[j - 1];
} else {
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
// 레벨 당 대지 속성 증가 포인트가 높은 순서대로 요정의 ID 목록을 가져옵니다.
function getFairyIdsByEarthPointPerLevel() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 earthPointPerLevel = fairies[i].earthPointPerLevel;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].earthPointPerLevel < earthPointPerLevel) {
fairyIds[j] = fairyIds[j - 1];
} else {
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
// 레벨 당 빛 속성 증가 포인트가 높은 순서대로 요정의 ID 목록을 가져옵니다.
function getFairyIdsByLightPointPerLevel() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 lightPointPerLevel = fairies[i].lightPointPerLevel;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].lightPointPerLevel < lightPointPerLevel) {
fairyIds[j] = fairyIds[j - 1];
} else {
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
// 레벨 당 어둠 속성 증가 포인트가 높은 순서대로 요정의 ID 목록을 가져옵니다.
function getFairyIdsByDarkPointPerLevel() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 darkPointPerLevel = fairies[i].darkPointPerLevel;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].darkPointPerLevel < darkPointPerLevel) {
fairyIds[j] = fairyIds[j - 1];
} else {
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
} | 레벨 당 바람 속성 증가 포인트가 높은 순서대로 요정의 ID 목록을 가져옵니다. | function getFairyIdsByWindPointPerLevel() view public returns (uint256[]) {
uint256[] memory fairyIds = new uint256[](fairies.length);
for (uint256 i = 0; i < fairies.length; i += 1) {
uint256 windPointPerLevel = fairies[i].windPointPerLevel;
for (uint256 j = i; j > 0; j -= 1) {
if (fairies[fairyIds[j - 1]].windPointPerLevel < windPointPerLevel) {
fairyIds[j] = fairyIds[j - 1];
break;
}
}
fairyIds[j] = i;
}
return fairyIds;
}
| 12,685,951 | [
1,
172,
259,
235,
172,
115,
106,
225,
172,
238,
122,
225,
172,
113,
247,
172,
257,
239,
225,
173,
233,
240,
173,
231,
114,
225,
173,
104,
256,
171,
113,
227,
225,
174,
242,
110,
173,
256,
121,
174,
237,
121,
171,
113,
227,
225,
172,
233,
245,
173,
256,
227,
225,
173,
235,
255,
173,
231,
255,
172,
239,
227,
172,
99,
255,
225,
173,
253,
247,
173,
259,
248,
173,
256,
251,
1599,
225,
172,
108,
107,
172,
99,
256,
173,
256,
231,
225,
171,
113,
227,
173,
259,
121,
173,
251,
118,
172,
238,
235,
172,
238,
102,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
2812,
1826,
93,
2673,
858,
59,
728,
2148,
2173,
2355,
1435,
1476,
1071,
1135,
261,
11890,
5034,
63,
5717,
288,
203,
202,
202,
11890,
5034,
8526,
3778,
284,
1826,
93,
2673,
273,
394,
2254,
5034,
8526,
12,
507,
481,
606,
18,
2469,
1769,
203,
1082,
203,
202,
202,
1884,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
284,
1826,
606,
18,
2469,
31,
277,
1011,
404,
13,
288,
203,
9506,
203,
1082,
202,
11890,
5034,
17064,
2148,
2173,
2355,
273,
284,
1826,
606,
63,
77,
8009,
10094,
2148,
2173,
2355,
31,
203,
9506,
203,
1082,
202,
1884,
261,
11890,
5034,
525,
273,
277,
31,
525,
405,
374,
31,
525,
3947,
404,
13,
288,
203,
9506,
202,
430,
261,
507,
481,
606,
63,
507,
6913,
2673,
63,
78,
300,
404,
65,
8009,
10094,
2148,
2173,
2355,
411,
17064,
2148,
2173,
2355,
13,
288,
203,
6862,
202,
507,
6913,
2673,
63,
78,
65,
273,
284,
1826,
93,
2673,
63,
78,
300,
404,
15533,
203,
6862,
202,
8820,
31,
203,
9506,
202,
97,
203,
1082,
202,
97,
203,
9506,
203,
1082,
202,
507,
6913,
2673,
63,
78,
65,
273,
277,
31,
203,
202,
202,
97,
203,
1082,
203,
202,
202,
2463,
284,
1826,
93,
2673,
31,
203,
202,
97,
203,
202,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/* SPDX-License-Identifier: LGPL-3.0-or-later */
pragma solidity ^0.7.0;
import "./Admin.sol";
import "./CarefulMath.sol";
import "./Erc20.sol";
import "./Erc20Interface.sol";
import "./Erc20Permit.sol";
import "./Erc20Recover.sol";
import "./ReentrancyGuard.sol";
import "./BalanceSheetInterface.sol";
import "./FintrollerInterface.sol";
import "./FyTokenInterface.sol";
import "./RedemptionPool.sol";
/**
* @title FyToken
* @author Hifi
* @notice Zero-coupon bond that tracks an Erc20 underlying asset.
*/
contract FyToken is
ReentrancyGuard, /* no depedency */
FyTokenInterface, /* one dependency */
Admin, /* two dependencies */
Exponential, /* two dependencies */
Erc20, /* three dependencies */
Erc20Permit, /* five dependencies */
Erc20Recover /* five dependencies */
{
modifier isVaultOpen(address account) {
require(balanceSheet.isVaultOpen(this, account), "ERR_VAULT_NOT_OPEN");
_;
}
/**
* @notice The fyToken always has 18 decimals.
* @dev Instantiates the Redemption Pool.
* @param name_ Erc20 name of this token.
* @param symbol_ Erc20 symbol of this token.
* @param expirationTime_ Unix timestamp in seconds for when this token expires.
* @param fintroller_ The address of the Fintroller contract.
* @param balanceSheet_ The address of the BalanceSheet contract.
* @param underlying_ The contract address of the underlying asset.
* @param collateral_ The contract address of the collateral asset.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 expirationTime_,
FintrollerInterface fintroller_,
BalanceSheetInterface balanceSheet_,
Erc20Interface underlying_,
Erc20Interface collateral_
) Erc20Permit(name_, symbol_, 18) Admin() {
uint8 defaultNumberOfDecimals = 18;
/* Set the underlying contract and calculate the decimal scalar offsets. */
uint256 underlyingDecimals = underlying_.decimals();
require(underlyingDecimals > 0, "ERR_FYTOKEN_CONSTRUCTOR_UNDERLYING_DECIMALS_ZERO");
require(underlyingDecimals <= defaultNumberOfDecimals, "ERR_FYTOKEN_CONSTRUCTOR_UNDERLYING_DECIMALS_OVERFLOW");
underlyingPrecisionScalar = 10**(defaultNumberOfDecimals - underlyingDecimals);
underlying = underlying_;
/* Set the collateral contract and calculate the decimal scalar offsets. */
uint256 collateralDecimals = collateral_.decimals();
require(collateralDecimals > 0, "ERR_FYTOKEN_CONSTRUCTOR_COLLATERAL_DECIMALS_ZERO");
require(defaultNumberOfDecimals >= collateralDecimals, "ERR_FYTOKEN_CONSTRUCTOR_COLLATERAL_DECIMALS_OVERFLOW");
collateralPrecisionScalar = 10**(defaultNumberOfDecimals - collateralDecimals);
collateral = collateral_;
/* Set the unix expiration time. */
require(expirationTime_ > block.timestamp, "ERR_FYTOKEN_CONSTRUCTOR_EXPIRATION_TIME_NOT_VALID");
expirationTime = expirationTime_;
/* Set the Fintroller contract and sanity check it. */
fintroller = fintroller_;
fintroller.isFintroller();
/* Set the Balance Sheet contract and sanity check it. */
balanceSheet = balanceSheet_;
balanceSheet.isBalanceSheet();
/* Create the Redemption Pool contract and transfer the owner from the fyToken itself to the current caller. */
redemptionPool = new RedemptionPool(fintroller_, this);
AdminInterface(address(redemptionPool))._transferAdmin(msg.sender);
}
/**
* CONSTANT FUNCTIONS
*/
/**
* @notice Checks if the bond matured.
* @return bool true = bond matured, otherwise it didn't.
*/
function isMatured() public view override returns (bool) {
return block.timestamp >= expirationTime;
}
/**
* NON-CONSTANT FUNCTIONS
*/
struct BorrowLocalVars {
MathError mathErr;
uint256 debt;
uint256 debtCeiling;
uint256 lockedCollateral;
uint256 hypotheticalCollateralizationRatioMantissa;
uint256 hypotheticalTotalSupply;
uint256 newDebt;
uint256 thresholdCollateralizationRatioMantissa;
}
/**
* @notice Increases the debt of the caller and mints new fyToken.
*
* @dev Emits a {Borrow}, {Mint} and {Transfer} event.
*
* Requirements:
*
* - The vault must be open.
* - Must be called prior to maturation.
* - The amount to borrow cannot be zero.
* - The Fintroller must allow this action to be performed.
* - The locked collateral cannot be zero.
* - The total supply of fyTokens cannot exceed the debt ceiling.
* - The caller must not fall below the threshold collateralization ratio.
*
* @param borrowAmount The amount of fyTokens to borrow and print into existence.
* @return bool true = success, otherwise it reverts.
*/
function borrow(uint256 borrowAmount) public override isVaultOpen(msg.sender) nonReentrant returns (bool) {
BorrowLocalVars memory vars;
/* Checks: bond not matured. */
require(isMatured() == false, "ERR_BOND_MATURED");
/* Checks: the zero edge case. */
require(borrowAmount > 0, "ERR_BORROW_ZERO");
/* Checks: the Fintroller allows this action to be performed. */
require(fintroller.getBorrowAllowed(this), "ERR_BORROW_NOT_ALLOWED");
/* Checks: debt ceiling. */
(vars.mathErr, vars.hypotheticalTotalSupply) = addUInt(totalSupply, borrowAmount);
require(vars.mathErr == MathError.NO_ERROR, "ERR_BORROW_MATH_ERROR");
vars.debtCeiling = fintroller.getBondDebtCeiling(this);
require(vars.hypotheticalTotalSupply <= vars.debtCeiling, "ERR_BORROW_DEBT_CEILING_OVERFLOW");
/* Add the borrow amount to the borrower account's current debt. */
(vars.debt, , vars.lockedCollateral, ) = balanceSheet.getVault(this, msg.sender);
require(vars.lockedCollateral > 0, "ERR_BORROW_LOCKED_COLLATERAL_ZERO");
(vars.mathErr, vars.newDebt) = addUInt(vars.debt, borrowAmount);
require(vars.mathErr == MathError.NO_ERROR, "ERR_BORROW_MATH_ERROR");
/* Checks: the hypothetical collateralization ratio is above the threshold. */
vars.hypotheticalCollateralizationRatioMantissa = balanceSheet.getHypotheticalCollateralizationRatio(
this,
msg.sender,
vars.lockedCollateral,
vars.newDebt
);
vars.thresholdCollateralizationRatioMantissa = fintroller.getBondCollateralizationRatio(this);
require(
vars.hypotheticalCollateralizationRatioMantissa >= vars.thresholdCollateralizationRatioMantissa,
"ERR_BELOW_COLLATERALIZATION_RATIO"
);
/* Effects: print the new fyTokens into existence. */
mintInternal(msg.sender, borrowAmount);
/* Emit a Transfer event. */
emit Transfer(address(this), msg.sender, borrowAmount);
/* Interactions: increase the debt of the borrower account. */
require(balanceSheet.setVaultDebt(this, msg.sender, vars.newDebt), "ERR_BORROW_CALL_SET_VAULT_DEBT");
/* Emit a Borrow event. */
emit Borrow(msg.sender, borrowAmount);
return true;
}
/**
* @notice Destroys `burnAmount` tokens from `holder`, reducing the token supply.
*
* @dev Emits a {Burn} and a {Transfer} event.
*
* Requirements:
*
* - Must be called prior to maturation.
* - Can only be called by the Redemption Pool.
* - The amount to burn cannot be zero.
*
* @param holder The account whose fyTokens to burn.
* @param burnAmount The amount of fyTokens to burn.
* @return bool true = success, otherwise it reverts.
*/
function burn(address holder, uint256 burnAmount) external override nonReentrant returns (bool) {
/* Checks: the caller is the Redemption Pool. */
require(msg.sender == address(redemptionPool), "ERR_BURN_NOT_AUTHORIZED");
/* Checks: the zero edge case. */
require(burnAmount > 0, "ERR_BURN_ZERO");
/* Effects: burns the fyTokens. */
burnInternal(holder, burnAmount);
/* Emit a Transfer event. */
emit Transfer(holder, address(this), burnAmount);
return true;
}
struct LiquidateBorrowsLocalVars {
MathError mathErr;
uint256 collateralizationRatioMantissa;
uint256 lockedCollateral;
bool isAccountUnderwater;
}
/**
* @notice Repays the debt of the borrower and rewards the caler with a surplus of collateral.
*
* @dev Emits a {RepayBorrow}, {Transfer}, {ClutchCollateral} and {LiquidateBorrow} event.
*
* Requirements:
*
* - The vault must be open.
* - The liquidator cannot liquidate themselves.
* - The amount to repay cannot be zero.
* - The Fintroller must allow this action to be performed.
* - The borrower must be underwater if the bond didn't mature.
* - The caller must have at least `repayAmount` fyTokens.
* - The borrower must have at least `repayAmount` debt.
* - The amount of clutched collateral cannot be more than what the borrower has in the vault.
*
* @param borrower The account to liquidate.
* @param repayAmount The amount of fyTokens to repay.
* @return bool true = success, otherwise it reverts.
*/
function liquidateBorrow(address borrower, uint256 repayAmount)
external
override
isVaultOpen(borrower)
nonReentrant
returns (bool)
{
LiquidateBorrowsLocalVars memory vars;
/* Checks: borrowers cannot self liquidate. */
require(msg.sender != borrower, "ERR_LIQUIDATE_BORROW_SELF");
/* Checks: the zero edge case. */
require(repayAmount > 0, "ERR_LIQUIDATE_BORROW_ZERO");
/* Checks: the Fintroller allows this action to be performed. */
require(fintroller.getLiquidateBorrowAllowed(this), "ERR_LIQUIDATE_BORROW_NOT_ALLOWED");
/* After maturation, any vault can be liquidated, irrespective of collateralization ratio. */
if (isMatured() == false) {
/* Checks: the borrower fell below the threshold collateralization ratio. */
vars.isAccountUnderwater = balanceSheet.isAccountUnderwater(this, borrower);
require(vars.isAccountUnderwater, "ERR_ACCOUNT_NOT_UNDERWATER");
}
/* Effects & Interactions: repay the borrower's debt. */
repayBorrowInternal(msg.sender, borrower, repayAmount);
/* Interactions: clutch the collateral. */
uint256 clutchableCollateralAmount = balanceSheet.getClutchableCollateral(this, repayAmount);
require(
balanceSheet.clutchCollateral(this, msg.sender, borrower, clutchableCollateralAmount),
"ERR_LIQUIDATE_BORROW_CALL_CLUTCH_COLLATERAL"
);
emit LiquidateBorrow(msg.sender, borrower, repayAmount, clutchableCollateralAmount);
return true;
}
/**
/** @notice Prints new tokens into existence and assigns them to `beneficiary`,
* increasing the total supply.
*
* @dev Emits a {Mint} and a {Transfer} event.
*
* Requirements:
*
* - Can only be called by the Redemption Pool.
* - The amount to mint cannot be zero.
*
* @param beneficiary The borrower account for which to mint the tokens.
* @param mintAmount The amount of fyTokens to print into existence.
* @return bool true = success, otherwise it reverts.
*/
function mint(address beneficiary, uint256 mintAmount) external override nonReentrant returns (bool) {
/* Checks: the caller is the Redemption Pool. */
require(msg.sender == address(redemptionPool), "ERR_MINT_NOT_AUTHORIZED");
/* Checks: the zero edge case. */
require(mintAmount > 0, "ERR_MINT_ZERO");
/* Effects: print the new fyTokens into existence. */
mintInternal(beneficiary, mintAmount);
/* Emit a Transfer event. */
emit Transfer(address(this), beneficiary, mintAmount);
return true;
}
/**
* @notice Deletes the borrower account's debt from the registry and take the fyTokens
* out of circulation.
*
* @dev Emits a {Burn}, {Transfer} and {RepayBorrow} event.
*
* Requirements:
*
* - The vault must be open.
* - The amount to repay cannot be zero.
* - The Fintroller must allow this action to be performed.
* - The caller must have at least `repayAmount` fyTokens.
* - The caller must have at least `repayAmount` debt.
*
* @param repayAmount The amount of fyTokens to repay.
* @return bool true = success, otherwise it reverts.
*/
function repayBorrow(uint256 repayAmount) external override isVaultOpen(msg.sender) nonReentrant returns (bool) {
repayBorrowInternal(msg.sender, msg.sender, repayAmount);
return true;
}
/**
* @notice Clears the borrower account's debt from the registry and take the fyTokens
* out of circulation.
*
* @dev Emits a {Burn}, {Transfer} and {RepayBorrow} event.
*
* Requirements: same as the `repayBorrow` function, but here `borrower` is the account that must
* have at least `repayAmount` fyTokens to repay the borrow.
*
* @param borrower The borrower account for which to repay the borrow.
* @param repayAmount The amount of fyTokens to repay.
* @return bool true = success, otherwise it reverts.
*/
function repayBorrowBehalf(address borrower, uint256 repayAmount)
external
override
isVaultOpen(borrower)
nonReentrant
returns (bool)
{
repayBorrowInternal(msg.sender, borrower, repayAmount);
return true;
}
/**
* @notice Updates the Fintroller contract's address saved in storage.
*
* @dev Throws a {SetFintroller} event.
*
* Requirements:
*
* - The caller must be the admin.
* - The new Fintroller must pass the inspection.
*
* @param newFintroller The address of the new Fintroller contract.
* @return bool true = success, otherwise it reverts.
*/
function _setFintroller(FintrollerInterface newFintroller) external override onlyAdmin returns (bool) {
/* Checks: sanity check the new Fintroller contract. */
require(newFintroller.isFintroller(), "ERR_SET_FINTROLLER_INSPECTION");
/* Effects: update storage. */
FintrollerInterface oldFintroller = fintroller;
fintroller = newFintroller;
emit SetFintroller(admin, oldFintroller, newFintroller);
return true;
}
/**
* INTERNAL FUNCTIONS
*/
/**
* @dev See the documentation for the public functions that call this internal function.
*/
function repayBorrowInternal(
address payer,
address borrower,
uint256 repayAmount
) internal {
/* Checks: the zero edge case. */
require(repayAmount > 0, "ERR_REPAY_BORROW_ZERO");
/* Checks: the Fintroller allows this action to be performed. */
require(fintroller.getRepayBorrowAllowed(this), "ERR_REPAY_BORROW_NOT_ALLOWED");
/* Checks: borrower has a debt to pay. */
uint256 debt = balanceSheet.getVaultDebt(this, borrower);
require(debt >= repayAmount, "ERR_REPAY_BORROW_INSUFFICIENT_DEBT");
/* Checks: the payer has enough fyTokens. */
require(balanceOf(payer) >= repayAmount, "ERR_REPAY_BORROW_INSUFFICIENT_BALANCE");
/* Effects: burn the fyTokens. */
burnInternal(payer, repayAmount);
/* Emit a Transfer event. */
emit Transfer(payer, address(this), repayAmount);
/* Calculate the new debt of the borrower. */
MathError mathErr;
uint256 newDebt;
(mathErr, newDebt) = subUInt(debt, repayAmount);
/* This operation can't fail because of the previous `require`. */
assert(mathErr == MathError.NO_ERROR);
/* Interactions: reduce the debt of the borrower . */
require(balanceSheet.setVaultDebt(this, borrower, newDebt), "ERR_REPAY_BORROW_CALL_SET_VAULT_DEBT");
/* Emit both a RepayBorrow event. */
emit RepayBorrow(payer, borrower, repayAmount, newDebt);
}
} | * @notice Updates the Fintroller contract's address saved in storage. @dev Throws a {SetFintroller} event. Requirements: - The caller must be the admin. - The new Fintroller must pass the inspection. @param newFintroller The address of the new Fintroller contract. @return bool true = success, otherwise it reverts./ | function _setFintroller(FintrollerInterface newFintroller) external override onlyAdmin returns (bool) {
require(newFintroller.isFintroller(), "ERR_SET_FINTROLLER_INSPECTION");
FintrollerInterface oldFintroller = fintroller;
fintroller = newFintroller;
emit SetFintroller(admin, oldFintroller, newFintroller);
return true;
| 14,900,293 | [
1,
5121,
326,
478,
474,
1539,
6835,
1807,
1758,
5198,
316,
2502,
18,
225,
22435,
279,
288,
694,
42,
474,
1539,
97,
871,
18,
29076,
30,
300,
1021,
4894,
1297,
506,
326,
3981,
18,
300,
1021,
394,
478,
474,
1539,
1297,
1342,
326,
2763,
7017,
18,
225,
394,
42,
474,
1539,
1021,
1758,
434,
326,
394,
478,
474,
1539,
6835,
18,
327,
1426,
638,
273,
2216,
16,
3541,
518,
15226,
87,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
389,
542,
42,
474,
1539,
12,
42,
474,
1539,
1358,
394,
42,
474,
1539,
13,
3903,
3849,
1338,
4446,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
2704,
42,
474,
1539,
18,
291,
42,
474,
1539,
9334,
315,
9712,
67,
4043,
67,
42,
3217,
25353,
67,
706,
23810,
3106,
8863,
203,
203,
3639,
478,
474,
1539,
1358,
1592,
42,
474,
1539,
273,
284,
474,
1539,
31,
203,
3639,
284,
474,
1539,
273,
394,
42,
474,
1539,
31,
203,
203,
3639,
3626,
1000,
42,
474,
1539,
12,
3666,
16,
1592,
42,
474,
1539,
16,
394,
42,
474,
1539,
1769,
203,
203,
3639,
327,
638,
31,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-07-06
*/
// File: contracts/sol6/IERC20.sol
pragma solidity 0.6.6;
interface IERC20 {
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function approve(address _spender, uint256 _value) external returns (bool success);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function balanceOf(address _owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 digits);
function totalSupply() external view returns (uint256 supply);
}
// to support backward compatible contract name -- so function signature remains same
abstract contract ERC20 is IERC20 {
}
// File: contracts/sol6/utils/zeppelin/ReentrancyGuard.sol
pragma solidity 0.6.6;
/**
* @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 {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// File: contracts/sol6/Dao/IEpochUtils.sol
pragma solidity 0.6.6;
interface IEpochUtils {
function epochPeriodInSeconds() external view returns (uint256);
function firstEpochStartTimestamp() external view returns (uint256);
function getCurrentEpochNumber() external view returns (uint256);
function getEpochNumber(uint256 timestamp) external view returns (uint256);
}
// File: contracts/sol6/Dao/IKyberStaking.sol
pragma solidity 0.6.6;
interface IKyberStaking is IEpochUtils {
event Delegated(
address indexed staker,
address indexed representative,
uint256 indexed epoch,
bool isDelegated
);
event Deposited(uint256 curEpoch, address indexed staker, uint256 amount);
event Withdraw(uint256 indexed curEpoch, address indexed staker, uint256 amount);
function initAndReturnStakerDataForCurrentEpoch(address staker)
external
returns (
uint256 stake,
uint256 delegatedStake,
address representative
);
function deposit(uint256 amount) external;
function delegate(address dAddr) external;
function withdraw(uint256 amount) external;
/**
* @notice return combine data (stake, delegatedStake, representative) of a staker
* @dev allow to get staker data up to current epoch + 1
*/
function getStakerData(address staker, uint256 epoch)
external
view
returns (
uint256 stake,
uint256 delegatedStake,
address representative
);
function getLatestStakerData(address staker)
external
view
returns (
uint256 stake,
uint256 delegatedStake,
address representative
);
/**
* @notice return raw data of a staker for an epoch
* WARN: should be used only for initialized data
* if data has not been initialized, it will return all 0
* pool master shouldn't use this function to compute/distribute rewards of pool members
*/
function getStakerRawData(address staker, uint256 epoch)
external
view
returns (
uint256 stake,
uint256 delegatedStake,
address representative
);
}
// File: contracts/sol6/IKyberDao.sol
pragma solidity 0.6.6;
interface IKyberDao is IEpochUtils {
event Voted(address indexed staker, uint indexed epoch, uint indexed campaignID, uint option);
function getLatestNetworkFeeDataWithCache()
external
returns (uint256 feeInBps, uint256 expiryTimestamp);
function getLatestBRRDataWithCache()
external
returns (
uint256 burnInBps,
uint256 rewardInBps,
uint256 rebateInBps,
uint256 epoch,
uint256 expiryTimestamp
);
function handleWithdrawal(address staker, uint256 penaltyAmount) external;
function vote(uint256 campaignID, uint256 option) external;
function getLatestNetworkFeeData()
external
view
returns (uint256 feeInBps, uint256 expiryTimestamp);
function shouldBurnRewardForEpoch(uint256 epoch) external view returns (bool);
/**
* @dev return staker's reward percentage in precision for a past epoch only
* fee handler should call this function when a staker wants to claim reward
* return 0 if staker has no votes or stakes
*/
function getPastEpochRewardPercentageInPrecision(address staker, uint256 epoch)
external
view
returns (uint256);
/**
* @dev return staker's reward percentage in precision for the current epoch
* reward percentage is not finalized until the current epoch is ended
*/
function getCurrentEpochRewardPercentageInPrecision(address staker)
external
view
returns (uint256);
}
// File: contracts/sol6/utils/zeppelin/SafeMath.sol
pragma solidity 0.6.6;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
// File: contracts/sol6/Dao/EpochUtils.sol
pragma solidity 0.6.6;
contract EpochUtils is IEpochUtils {
using SafeMath for uint256;
uint256 public override epochPeriodInSeconds;
uint256 public override firstEpochStartTimestamp;
function getCurrentEpochNumber() public view override returns (uint256) {
return getEpochNumber(now);
}
function getEpochNumber(uint256 timestamp) public view override returns (uint256) {
if (timestamp < firstEpochStartTimestamp || epochPeriodInSeconds == 0) {
return 0;
}
// ((timestamp - firstEpochStartTimestamp) / epochPeriodInSeconds) + 1;
return ((timestamp.sub(firstEpochStartTimestamp)).div(epochPeriodInSeconds)).add(1);
}
}
// File: contracts/sol6/Dao/KyberStaking.sol
pragma solidity 0.6.6;
/**
* @notice This contract is using SafeMath for uint, which is inherited from EpochUtils
* Some events are moved to interface, easier for public uses
* Staking contract will be deployed by KyberDao's contract
*/
contract KyberStaking is IKyberStaking, EpochUtils, ReentrancyGuard {
struct StakerData {
uint256 stake;
uint256 delegatedStake;
address representative;
}
IERC20 public immutable kncToken;
IKyberDao public immutable kyberDao;
// staker data per epoch, including stake, delegated stake and representative
mapping(uint256 => mapping(address => StakerData)) internal stakerPerEpochData;
// latest data of a staker, including stake, delegated stake, representative
mapping(address => StakerData) internal stakerLatestData;
// true/false: if data has been initialized at an epoch for a staker
mapping(uint256 => mapping(address => bool)) internal hasInited;
// event is fired if something is wrong with withdrawal
// even though the withdrawal is still successful
event WithdrawDataUpdateFailed(uint256 curEpoch, address staker, uint256 amount);
constructor(
IERC20 _kncToken,
uint256 _epochPeriod,
uint256 _startTimestamp,
IKyberDao _kyberDao
) public {
require(_epochPeriod > 0, "ctor: epoch period is 0");
require(_startTimestamp >= now, "ctor: start in the past");
require(_kncToken != IERC20(0), "ctor: kncToken 0");
require(_kyberDao != IKyberDao(0), "ctor: kyberDao 0");
epochPeriodInSeconds = _epochPeriod;
firstEpochStartTimestamp = _startTimestamp;
kncToken = _kncToken;
kyberDao = _kyberDao;
}
/**
* @dev calls to set delegation for msg.sender, will take effect from the next epoch
* @param newRepresentative address to delegate to
*/
function delegate(address newRepresentative) external override {
require(newRepresentative != address(0), "delegate: representative 0");
address staker = msg.sender;
uint256 curEpoch = getCurrentEpochNumber();
initDataIfNeeded(staker, curEpoch);
address curRepresentative = stakerPerEpochData[curEpoch + 1][staker].representative;
// nothing changes here
if (newRepresentative == curRepresentative) {
return;
}
uint256 updatedStake = stakerPerEpochData[curEpoch + 1][staker].stake;
// reduce delegatedStake for curRepresentative if needed
if (curRepresentative != staker) {
initDataIfNeeded(curRepresentative, curEpoch);
stakerPerEpochData[curEpoch + 1][curRepresentative].delegatedStake =
stakerPerEpochData[curEpoch + 1][curRepresentative].delegatedStake.sub(updatedStake);
stakerLatestData[curRepresentative].delegatedStake =
stakerLatestData[curRepresentative].delegatedStake.sub(updatedStake);
emit Delegated(staker, curRepresentative, curEpoch, false);
}
stakerLatestData[staker].representative = newRepresentative;
stakerPerEpochData[curEpoch + 1][staker].representative = newRepresentative;
// ignore if staker is delegating back to himself
if (newRepresentative != staker) {
initDataIfNeeded(newRepresentative, curEpoch);
stakerPerEpochData[curEpoch + 1][newRepresentative].delegatedStake =
stakerPerEpochData[curEpoch + 1][newRepresentative].delegatedStake.add(updatedStake);
stakerLatestData[newRepresentative].delegatedStake =
stakerLatestData[newRepresentative].delegatedStake.add(updatedStake);
emit Delegated(staker, newRepresentative, curEpoch, true);
}
}
/**
* @dev call to stake more KNC for msg.sender
* @param amount amount of KNC to stake
*/
function deposit(uint256 amount) external override {
require(amount > 0, "deposit: amount is 0");
uint256 curEpoch = getCurrentEpochNumber();
address staker = msg.sender;
// collect KNC token from staker
require(
kncToken.transferFrom(staker, address(this), amount),
"deposit: can not get token"
);
initDataIfNeeded(staker, curEpoch);
stakerPerEpochData[curEpoch + 1][staker].stake =
stakerPerEpochData[curEpoch + 1][staker].stake.add(amount);
stakerLatestData[staker].stake =
stakerLatestData[staker].stake.add(amount);
// increase delegated stake for address that staker has delegated to (if it is not staker)
address representative = stakerPerEpochData[curEpoch + 1][staker].representative;
if (representative != staker) {
initDataIfNeeded(representative, curEpoch);
stakerPerEpochData[curEpoch + 1][representative].delegatedStake =
stakerPerEpochData[curEpoch + 1][representative].delegatedStake.add(amount);
stakerLatestData[representative].delegatedStake =
stakerLatestData[representative].delegatedStake.add(amount);
}
emit Deposited(curEpoch, staker, amount);
}
/**
* @dev call to withdraw KNC from staking, it could affect reward when calling KyberDao handleWithdrawal
* @param amount amount of KNC to withdraw
*/
function withdraw(uint256 amount) external override nonReentrant {
require(amount > 0, "withdraw: amount is 0");
uint256 curEpoch = getCurrentEpochNumber();
address staker = msg.sender;
require(
stakerLatestData[staker].stake >= amount,
"withdraw: latest amount staked < withdrawal amount"
);
(bool success, ) = address(this).call(
abi.encodeWithSignature(
"handleWithdrawal(address,uint256,uint256)",
staker,
amount,
curEpoch
)
);
if (!success) {
// Note: should catch this event to check if something went wrong
emit WithdrawDataUpdateFailed(curEpoch, staker, amount);
}
stakerLatestData[staker].stake = stakerLatestData[staker].stake.sub(amount);
// transfer KNC back to staker
require(kncToken.transfer(staker, amount), "withdraw: can not transfer knc");
emit Withdraw(curEpoch, staker, amount);
}
/**
* @dev initialize data if needed, then return staker's data for current epoch
* @dev for safe, only allow calling this func from KyberDao address
* @param staker - staker's address to initialize and get data for
*/
function initAndReturnStakerDataForCurrentEpoch(address staker)
external
override
returns (
uint256 stake,
uint256 delegatedStake,
address representative
)
{
require(
msg.sender == address(kyberDao),
"initAndReturnData: only kyberDao"
);
uint256 curEpoch = getCurrentEpochNumber();
initDataIfNeeded(staker, curEpoch);
StakerData memory stakerData = stakerPerEpochData[curEpoch][staker];
stake = stakerData.stake;
delegatedStake = stakerData.delegatedStake;
representative = stakerData.representative;
}
/**
* @notice return raw data of a staker for an epoch
* WARN: should be used only for initialized data
* if data has not been initialized, it will return all 0
* pool master shouldn't use this function to compute/distribute rewards of pool members
* @dev in KyberDao contract, if staker wants to claim reward for past epoch,
* we must know the staker's data for that epoch
* if the data has not been initialized, it means staker hasn't done any action -> no reward
*/
function getStakerRawData(address staker, uint256 epoch)
external
view
override
returns (
uint256 stake,
uint256 delegatedStake,
address representative
)
{
StakerData memory stakerData = stakerPerEpochData[epoch][staker];
stake = stakerData.stake;
delegatedStake = stakerData.delegatedStake;
representative = stakerData.representative;
}
/**
* @dev allow to get data up to current epoch + 1
*/
function getStake(address staker, uint256 epoch) external view returns (uint256) {
uint256 curEpoch = getCurrentEpochNumber();
if (epoch > curEpoch + 1) {
return 0;
}
uint256 i = epoch;
while (true) {
if (hasInited[i][staker]) {
return stakerPerEpochData[i][staker].stake;
}
if (address(this).balance == 0) { //inject PRESENT ETHER
break;
}
i--;
}
return 0;
}
/**
* @dev allow to get data up to current epoch + 1
*/
function getDelegatedStake(address staker, uint256 epoch) external view returns (uint256) {
uint256 curEpoch = getCurrentEpochNumber();
if (epoch > curEpoch + 1) {
return 0;
}
uint256 i = epoch;
while (true) {
if (hasInited[i][staker]) {
return stakerPerEpochData[i][staker].delegatedStake;
}
if (address(this).balance == 0) { //inject PRESENT ETHER
break;
}
i--;
}
return 0;
}
/**
* @dev allow to get data up to current epoch + 1
*/
function getRepresentative(address staker, uint256 epoch) external view returns (address) {
uint256 curEpoch = getCurrentEpochNumber();
if (epoch > curEpoch + 1) {
return address(0);
}
uint256 i = epoch;
while (true) {
if (hasInited[i][staker]) {
return stakerPerEpochData[i][staker].representative;
}
if (address(this).balance == 0) { //inject PRESENT ETHER
break;
}
i--;
}
// not delegated to anyone, default to yourself
return staker;
}
/**
* @notice return combine data (stake, delegatedStake, representative) of a staker
* @dev allow to get staker data up to current epoch + 1
*/
function getStakerData(address staker, uint256 epoch)
external view override
returns (
uint256 stake,
uint256 delegatedStake,
address representative
)
{
stake = 0;
delegatedStake = 0;
representative = address(0);
uint256 curEpoch = getCurrentEpochNumber();
if (epoch > curEpoch + 1) {
return (stake, delegatedStake, representative);
}
uint256 i = epoch;
while (true) {
if (hasInited[i][staker]) {
stake = stakerPerEpochData[i][staker].stake;
delegatedStake = stakerPerEpochData[i][staker].delegatedStake;
representative = stakerPerEpochData[i][staker].representative;
return (stake, delegatedStake, representative);
}
if (address(this).balance == 0) { //inject PRESENT ETHER
break;
}
i--;
}
// not delegated to anyone, default to yourself
representative = staker;
}
function getLatestRepresentative(address staker) external view returns (address) {
return
stakerLatestData[staker].representative == address(0)
? staker
: stakerLatestData[staker].representative;
}
function getLatestDelegatedStake(address staker) external view returns (uint256) {
return stakerLatestData[staker].delegatedStake;
}
function getLatestStakeBalance(address staker) external view returns (uint256) {
return stakerLatestData[staker].stake;
}
function getLatestStakerData(address staker)
external view override
returns (
uint256 stake,
uint256 delegatedStake,
address representative
)
{
stake = stakerLatestData[staker].stake;
delegatedStake = stakerLatestData[staker].delegatedStake;
representative = stakerLatestData[staker].representative == address(0)
? staker
: stakerLatestData[staker].representative;
}
/**
* @dev separate logics from withdraw, so staker can withdraw as long as amount <= staker's deposit amount
calling this function from withdraw function, ignore reverting
* @param staker staker that is withdrawing
* @param amount amount to withdraw
* @param curEpoch current epoch
*/
function handleWithdrawal(
address staker,
uint256 amount,
uint256 curEpoch
) external {
require(msg.sender == address(this), "only staking contract");
initDataIfNeeded(staker, curEpoch);
// Note: update latest stake will be done after this function
// update staker's data for next epoch
stakerPerEpochData[curEpoch + 1][staker].stake =
stakerPerEpochData[curEpoch + 1][staker].stake.sub(amount);
address representative = stakerPerEpochData[curEpoch][staker].representative;
uint256 curStake = stakerPerEpochData[curEpoch][staker].stake;
uint256 lStakeBal = stakerLatestData[staker].stake.sub(amount);
uint256 newStake = curStake.min(lStakeBal);
uint256 reduceAmount = curStake.sub(newStake); // newStake is always <= curStake
if (reduceAmount > 0) {
if (representative != staker) {
initDataIfNeeded(representative, curEpoch);
// staker has delegated to representative, withdraw will affect representative's delegated stakes
stakerPerEpochData[curEpoch][representative].delegatedStake =
stakerPerEpochData[curEpoch][representative].delegatedStake.sub(reduceAmount);
}
stakerPerEpochData[curEpoch][staker].stake = newStake;
// call KyberDao to reduce reward, if staker has delegated, then pass his representative
if (address(kyberDao) != address(0)) {
// don't revert if KyberDao revert so data will be updated correctly
(bool success, ) = address(kyberDao).call(
abi.encodeWithSignature(
"handleWithdrawal(address,uint256)",
representative,
reduceAmount
)
);
if (!success) {
emit WithdrawDataUpdateFailed(curEpoch, staker, amount);
}
}
}
representative = stakerPerEpochData[curEpoch + 1][staker].representative;
if (representative != staker) {
initDataIfNeeded(representative, curEpoch);
stakerPerEpochData[curEpoch + 1][representative].delegatedStake =
stakerPerEpochData[curEpoch + 1][representative].delegatedStake.sub(amount);
stakerLatestData[representative].delegatedStake =
stakerLatestData[representative].delegatedStake.sub(amount);
}
}
/**
* @dev initialize data if it has not been initialized yet
* @param staker staker's address to initialize
* @param epoch should be current epoch
*/
function initDataIfNeeded(address staker, uint256 epoch) internal {
address representative = stakerLatestData[staker].representative;
if (representative == address(0)) {
// not delegate to anyone, consider as delegate to yourself
stakerLatestData[staker].representative = staker;
representative = staker;
}
uint256 ldStake = stakerLatestData[staker].delegatedStake;
uint256 lStakeBal = stakerLatestData[staker].stake;
if (!hasInited[epoch][staker]) {
hasInited[epoch][staker] = true;
StakerData storage stakerData = stakerPerEpochData[epoch][staker];
stakerData.representative = representative;
stakerData.delegatedStake = ldStake;
stakerData.stake = lStakeBal;
}
// whenever stakers deposit/withdraw/delegate, the current and next epoch data need to be updated
// as the result, we will also initialize data for staker at the next epoch
if (!hasInited[epoch + 1][staker]) {
hasInited[epoch + 1][staker] = true;
StakerData storage nextEpochStakerData = stakerPerEpochData[epoch + 1][staker];
nextEpochStakerData.representative = representative;
nextEpochStakerData.delegatedStake = ldStake;
nextEpochStakerData.stake = lStakeBal;
}
}
} | staker has delegated to representative, withdraw will affect representative's delegated stakes call KyberDao to reduce reward, if staker has delegated, then pass his representative don't revert if KyberDao revert so data will be updated correctly | function getLatestStakerData(address staker)
external view override
returns (
uint256 stake,
uint256 delegatedStake,
address representative
)
}
calling this function from withdraw function, ignore reverting
function handleWithdrawal(
address staker,
uint256 amount,
uint256 curEpoch
if (reduceAmount > 0) {
if (representative != staker) {
initDataIfNeeded(representative, curEpoch);
stakerPerEpochData[curEpoch][representative].delegatedStake =
stakerPerEpochData[curEpoch][representative].delegatedStake.sub(reduceAmount);
}
stakerPerEpochData[curEpoch][staker].stake = newStake;
if (address(kyberDao) != address(0)) {
(bool success, ) = address(kyberDao).call(
abi.encodeWithSignature(
"handleWithdrawal(address,uint256)",
representative,
reduceAmount
)
);
if (!success) {
emit WithdrawDataUpdateFailed(curEpoch, staker, amount);
}
}
}
representative = stakerPerEpochData[curEpoch + 1][staker].representative;
| 12,888,147 | [
1,
334,
6388,
711,
30055,
358,
23174,
16,
598,
9446,
903,
13418,
23174,
1807,
30055,
384,
3223,
745,
1475,
93,
744,
11412,
358,
5459,
19890,
16,
309,
384,
6388,
711,
30055,
16,
1508,
1342,
18423,
23174,
2727,
1404,
15226,
309,
1475,
93,
744,
11412,
15226,
1427,
501,
903,
506,
3526,
8783,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
336,
18650,
510,
6388,
751,
12,
2867,
384,
6388,
13,
203,
3639,
3903,
1476,
3849,
203,
3639,
1135,
261,
203,
5411,
2254,
5034,
384,
911,
16,
203,
5411,
2254,
5034,
30055,
510,
911,
16,
203,
5411,
1758,
23174,
203,
3639,
262,
203,
565,
289,
203,
203,
5411,
4440,
333,
445,
628,
598,
9446,
445,
16,
2305,
15226,
310,
203,
565,
445,
1640,
1190,
9446,
287,
12,
203,
3639,
1758,
384,
6388,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
2254,
5034,
662,
14638,
203,
3639,
309,
261,
12498,
6275,
405,
374,
13,
288,
203,
5411,
309,
261,
28205,
1535,
480,
384,
6388,
13,
288,
203,
7734,
1208,
751,
18299,
12,
28205,
1535,
16,
662,
14638,
1769,
203,
7734,
384,
6388,
2173,
14638,
751,
63,
1397,
14638,
6362,
28205,
1535,
8009,
3771,
1332,
690,
510,
911,
273,
203,
10792,
384,
6388,
2173,
14638,
751,
63,
1397,
14638,
6362,
28205,
1535,
8009,
3771,
1332,
690,
510,
911,
18,
1717,
12,
12498,
6275,
1769,
203,
5411,
289,
203,
5411,
384,
6388,
2173,
14638,
751,
63,
1397,
14638,
6362,
334,
6388,
8009,
334,
911,
273,
394,
510,
911,
31,
203,
5411,
309,
261,
2867,
12,
18465,
744,
11412,
13,
480,
1758,
12,
20,
3719,
288,
203,
7734,
261,
6430,
2216,
16,
262,
273,
1758,
12,
18465,
744,
11412,
2934,
1991,
12,
203,
10792,
24126,
18,
3015,
1190,
5374,
12,
203,
13491,
315,
4110,
1190,
9446,
287,
12,
2867,
16,
11890,
5034,
2225,
16,
203,
13491,
23174,
16,
203,
13491,
5459,
6275,
203,
10792,
262,
203,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./Controller.sol";
/**
* @title Total Binance Cap Token
* @author Cap X Fund
* @notice ERC20 token on the Binance Blockchain that provides total exposure to its crypto sector.
*/
contract BCAP is ERC20, Ownable, IERC165 {
/// @notice Open Zeppelin libraries
using SafeMath for uint256;
/// @notice if enabled BCAP can't be minted if the total supply is above or equal the cap value
bool public capEnabled = false;
/// @notice Maximum value the total supply of BCAP
uint256 public cap;
/**
* @notice Address to Vault Handler
* @dev Only vault handlers can mint and burn BCAP
*/
mapping(address => bool) public vaultHandlers;
/**
* @dev the computed interface ID according to ERC-165. The interface ID is a XOR of interface method selectors.
* mint.selector ^
* burn.selector ^
* setCap.selector ^
* enableCap.selector ^
* transfer.selector ^
* transferFrom.selector ^
* addVaultHandler.selector ^
* removeVaultHandler.selector ^
* approve.selector => 0xbd115939
*/
bytes4 private constant _INTERFACE_ID_TCAP = 0xbd115939;
/// @dev bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/// @notice An event emitted when a vault handler is added
event VaultHandlerAdded(
address indexed _owner,
address indexed _tokenHandler
);
/// @notice An event emitted when a vault handler is removed
event VaultHandlerRemoved(
address indexed _owner,
address indexed _tokenHandler
);
/// @notice An event emitted when the cap value is updated
event NewCap(address indexed _owner, uint256 _amount);
/// @notice An event emitted when the cap is enabled or disabled
event NewCapEnabled(address indexed _owner, bool _enable);
/**
* @notice Constructor
* @param _name uint256
* @param _symbol uint256
* @param _cap uint256
* @param _controller address
*/
constructor(
string memory _name,
string memory _symbol,
uint256 _cap,
Controller _controller
) ERC20(_name, _symbol) {
cap = _cap;
/// @dev transfer ownership to orchestrator
transferOwnership(address(_controller));
}
/// @notice Reverts if called by any account that is not a vault.
modifier onlyVault() {
require(
vaultHandlers[msg.sender],
"BCAP::onlyVault: caller is not a vault"
);
_;
}
/**
* @notice Adds a new address as a vault
* @param _vaultHandler address of a contract with permissions to mint and burn tokens
* @dev Only owner can call it
*/
function addVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = true;
emit VaultHandlerAdded(msg.sender, _vaultHandler);
}
/**
* @notice Removes an address as a vault
* @param _vaultHandler address of the contract to be removed as vault
* @dev Only owner can call it
*/
function removeVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = false;
emit VaultHandlerRemoved(msg.sender, _vaultHandler);
}
/**
* @notice Mints BCAP Tokens
* @param _account address of the receiver of tokens
* @param _amount uint of tokens to mint
* @dev Only vault can call it
*/
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _amount);
}
/**
* @notice Burns BCAP Tokens
* @param _account address of the account which is burning tokens.
* @param _amount uint of tokens to burn
* @dev Only vault can call it
*/
function burn(address _account, uint256 _amount) external onlyVault {
_burn(_account, _amount);
}
/**
* @notice Sets maximum value the total supply of TCAP can have
* @param _cap value
* @dev When capEnabled is true, mint is not allowed to issue tokens that would increase the total supply above or equal the specified capacity.
* @dev Only owner can call it
*/
function setCap(uint256 _cap) external onlyOwner {
cap = _cap;
emit NewCap(msg.sender, _cap);
}
/**
* @notice Enables or Disables the Total Supply Cap.
* @param _enable value
* @dev When capEnabled is true, minting will not be allowed above the max capacity. It can exist a supply above the cap, but it prevents minting above the cap.
* @dev Only owner can call it
*/
function enableCap(bool _enable) external onlyOwner {
capEnabled = _enable;
emit NewCapEnabled(msg.sender, _enable);
}
/**
* @notice ERC165 Standard for support of interfaces
* @param _interfaceId bytes of interface
* @return bool
*/
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_TCAP ||
_interfaceId == _INTERFACE_ID_ERC165);
}
/**
* @notice executes before each token transfer or mint
* @param _from address
* @param _to address
* @param _amount value to transfer
* @dev See {ERC20-_beforeTokenTransfer}.
* @dev minted tokens must not cause the total supply to go over the cap.
* @dev Reverts if the to address is equal to token address
*/
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _amount
) internal virtual override {
super._beforeTokenTransfer(_from, _to, _amount);
require(
_to != address(this),
"BCAP::transfer: can't transfer to BCAP contract"
);
if (_from == address(0) && capEnabled) {
// When minting tokens
require(
totalSupply().add(_amount) <= cap,
"BCAP::Transfer: BCAP cap exceeded"
);
}
}
}
| * @title Total Binance Cap Token @author Cap X Fund @notice ERC20 token on the Binance Blockchain that provides total exposure to its crypto sector./ | contract BCAP is ERC20, Ownable, IERC165 {
using SafeMath for uint256;
bool public capEnabled = false;
uint256 public cap;
mapping(address => bool) public vaultHandlers;
bytes4 private constant _INTERFACE_ID_TCAP = 0xbd115939;
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
event VaultHandlerAdded(
address indexed _owner,
address indexed _tokenHandler
);
event VaultHandlerRemoved(
address indexed _owner,
address indexed _tokenHandler
);
event NewCap(address indexed _owner, uint256 _amount);
event NewCapEnabled(address indexed _owner, bool _enable);
constructor(
string memory _name,
string memory _symbol,
uint256 _cap,
Controller _controller
pragma solidity 0.8.3;
) ERC20(_name, _symbol) {
cap = _cap;
transferOwnership(address(_controller));
}
modifier onlyVault() {
require(
vaultHandlers[msg.sender],
"BCAP::onlyVault: caller is not a vault"
);
_;
}
function addVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = true;
emit VaultHandlerAdded(msg.sender, _vaultHandler);
}
function removeVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = false;
emit VaultHandlerRemoved(msg.sender, _vaultHandler);
}
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _amount);
}
function burn(address _account, uint256 _amount) external onlyVault {
_burn(_account, _amount);
}
function setCap(uint256 _cap) external onlyOwner {
cap = _cap;
emit NewCap(msg.sender, _cap);
}
function enableCap(bool _enable) external onlyOwner {
capEnabled = _enable;
emit NewCapEnabled(msg.sender, _enable);
}
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_TCAP ||
_interfaceId == _INTERFACE_ID_ERC165);
}
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _amount
) internal virtual override {
super._beforeTokenTransfer(_from, _to, _amount);
require(
_to != address(this),
"BCAP::transfer: can't transfer to BCAP contract"
);
if (_from == address(0) && capEnabled) {
require(
totalSupply().add(_amount) <= cap,
"BCAP::Transfer: BCAP cap exceeded"
);
}
}
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _amount
) internal virtual override {
super._beforeTokenTransfer(_from, _to, _amount);
require(
_to != address(this),
"BCAP::transfer: can't transfer to BCAP contract"
);
if (_from == address(0) && capEnabled) {
require(
totalSupply().add(_amount) <= cap,
"BCAP::Transfer: BCAP cap exceeded"
);
}
}
}
| 14,102,714 | [
1,
5269,
16827,
1359,
11200,
3155,
225,
11200,
1139,
478,
1074,
225,
4232,
39,
3462,
1147,
603,
326,
16827,
1359,
3914,
5639,
716,
8121,
2078,
14620,
358,
2097,
8170,
16323,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
605,
17296,
353,
4232,
39,
3462,
16,
14223,
6914,
16,
467,
654,
39,
28275,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
225,
1426,
1071,
3523,
1526,
273,
629,
31,
203,
203,
225,
2254,
5034,
1071,
3523,
31,
203,
203,
225,
2874,
12,
2867,
516,
1426,
13,
1071,
9229,
6919,
31,
203,
203,
225,
1731,
24,
3238,
5381,
389,
18865,
67,
734,
67,
15988,
2203,
273,
374,
6114,
72,
2499,
6162,
5520,
31,
203,
203,
225,
1731,
24,
3238,
5381,
389,
18865,
67,
734,
67,
654,
39,
28275,
273,
374,
92,
1611,
1403,
71,
29,
69,
27,
31,
203,
203,
225,
871,
17329,
1503,
8602,
12,
203,
565,
1758,
8808,
389,
8443,
16,
203,
565,
1758,
8808,
389,
2316,
1503,
203,
225,
11272,
203,
203,
225,
871,
17329,
1503,
10026,
12,
203,
565,
1758,
8808,
389,
8443,
16,
203,
565,
1758,
8808,
389,
2316,
1503,
203,
225,
11272,
203,
203,
225,
871,
1166,
4664,
12,
2867,
8808,
389,
8443,
16,
2254,
5034,
389,
8949,
1769,
203,
203,
225,
871,
1166,
4664,
1526,
12,
2867,
8808,
389,
8443,
16,
1426,
389,
7589,
1769,
203,
203,
225,
3885,
12,
203,
565,
533,
3778,
389,
529,
16,
203,
565,
533,
3778,
389,
7175,
16,
203,
565,
2254,
5034,
389,
5909,
16,
203,
565,
6629,
389,
5723,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
23,
31,
203,
225,
262,
4232,
39,
3462,
24899,
529,
16,
389,
7175,
13,
288,
203,
565,
3523,
273,
389,
5909,
31,
203,
203,
565,
7412,
5460,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./libraries/SafeERC20.sol";
import "../utils/Pausable.sol";
import "./libraries/Math.sol";
import "./AdminInterface.sol";
import "./AlphaToken.sol";
import "./DepositNFT.sol";
import "./WithdrawalNFT.sol";
/**
* @title AlphaStrategy
* @dev Implementation of AlphaStrategy
*/
contract AlphaStrategy is Pausable {
using SafeERC20 for IERC20;
using Math for uint256;
// Decimal factors
uint256 public AMOUNT_SCALE_DECIMALS = 1; // for stable token
uint256 public COEFF_SCALE_DECIMALS_F; // for fees
uint256 public COEFF_SCALE_DECIMALS_P; // for ALPHA price
// Maximum allowed deposit/withdraw amount
uint256 public MAX_AMOUNT_DEPOSIT = 1000000 * 1e18;
uint256 public MAX_AMOUNT_WITHDRAW = 1000000 * 1e18;
// Deposit fee rate
uint256 public DEPOSIT_FEE_RATE;
// Alpha prices
uint256 public ALPHA_PRICE;
uint256 public ALPHA_PRICE_WAVG;
// Event variables
uint public netDepositInd;
uint256 public netAmountEvent;
uint256 public maxDepositAmount;
uint256 public maxWithdrawAmount;
uint256 public withdrawAmountTotal;
uint256 public withdrawAmountTotalOld;
uint256 public depositAmountTotal;
uint256 public TIME_WITHDRAW_MANAGER = 0;
// ALPHA token data
uint256 public totalSupply;
// NFT data
uint256 tokenIdDeposit;
uint256 tokenIdWithdraw;
// Other variables for Alpha strategy
bool public CAN_CANCEL = false;
address public treasury;
mapping(address => uint256) public acceptedWithdrawPerAddress;
//Contracts
AdminInterface public admin;
IERC20 public stableToken;
AlphaToken public alphaToken;
DepositNFT public depositNFT;
WithdrawalNFT public withdrawalNFT;
constructor(address _admin, address _stableTokenAddress, address _alphaToken,
address _depositNFTAdress, address _withdrawalNFTAdress) {
require(
_admin != address(0),
"Formation.Fi: admin address is the zero address"
);
require(
_stableTokenAddress != address(0),
"Formation.Fi: Stable token address is the zero address"
);
require(
_alphaToken != address(0),
"Formation.Fi: ALPHA token address is the zero address"
);
require(
_depositNFTAdress != address(0),
"Formation.Fi: withdrawal NFT address is the zero address"
);
require(
_withdrawalNFTAdress != address(0),
"Formation.Fi: withdrawal NFT address is the zero address"
);
admin = AdminInterface(_admin);
stableToken = IERC20(_stableTokenAddress);
alphaToken = AlphaToken(_alphaToken);
depositNFT = DepositNFT(_depositNFTAdress);
withdrawalNFT = WithdrawalNFT(_withdrawalNFTAdress);
uint8 _stableTokenDecimals = ERC20(_stableTokenAddress).decimals();
if (_stableTokenDecimals == 6) {
AMOUNT_SCALE_DECIMALS = 1e12;
}
}
// Modifiers
modifier onlyManager() {
address _manager = admin.manager();
require(msg.sender == _manager, "Formation.Fi: Caller is not the manager");
_;
}
modifier canCancel() {
bool _CAN_CANCEL = admin.CAN_CANCEL();
require( _CAN_CANCEL == true, "Formation.Fi: Cancel feature is not available");
_;
}
// Getter functions.
function getTVL() public view returns (uint256) {
return (admin.ALPHA_PRICE() * alphaToken.totalSupply())
/ admin.COEFF_SCALE_DECIMALS_P();
}
// Setter functions
function set_MAX_AMOUNT_DEPOSIT(uint256 _MAX_AMOUNT_DEPOSIT) external
onlyManager {
MAX_AMOUNT_DEPOSIT = _MAX_AMOUNT_DEPOSIT;
}
function set_MAX_AMOUNT_WITHDRAW(uint256 _MAX_AMOUNT_WITHDRAW) external
onlyManager{
MAX_AMOUNT_WITHDRAW = _MAX_AMOUNT_WITHDRAW;
}
function updateAdminData() internal {
COEFF_SCALE_DECIMALS_F = admin.COEFF_SCALE_DECIMALS_F();
COEFF_SCALE_DECIMALS_P= admin.COEFF_SCALE_DECIMALS_P();
DEPOSIT_FEE_RATE = admin.DEPOSIT_FEE_RATE();
ALPHA_PRICE = admin.ALPHA_PRICE();
ALPHA_PRICE_WAVG = admin.ALPHA_PRICE_WAVG();
totalSupply = alphaToken.totalSupply();
treasury = admin.treasury();
}
// Calculate rebalancing Event parameters
function calculateNetDepositInd() public onlyManager {
updateAdminData();
netDepositInd = admin.calculateNetDepositInd(depositAmountTotal, withdrawAmountTotal);
}
function calculateNetAmountEvent() public onlyManager {
netAmountEvent = admin.calculateNetAmountEvent(depositAmountTotal, withdrawAmountTotal,
MAX_AMOUNT_DEPOSIT, MAX_AMOUNT_WITHDRAW);
}
function calculateMaxDepositAmount( ) external
whenNotPaused onlyManager {
if (netDepositInd == 1) {
maxDepositAmount = (netAmountEvent + ((withdrawAmountTotal *
ALPHA_PRICE) / COEFF_SCALE_DECIMALS_P));
}
else {
maxDepositAmount = Math.min(depositAmountTotal, MAX_AMOUNT_DEPOSIT);
}
}
function calculateMaxWithdrawAmount( ) external
whenNotPaused onlyManager
{
withdrawAmountTotalOld = withdrawAmountTotal;
maxWithdrawAmount = ((netAmountEvent + depositAmountTotal)
* COEFF_SCALE_DECIMALS_P);
}
function calculateAcceptedWithdrawRequests(address[] memory _users)
internal {
require (_users.length > 0, "Formation.Fi: no users provided");
uint256 _amountLP;
for (uint256 i = 0; i < _users.length; i++) {
require(
_users[i]!= address(0),
"Formation.Fi: user address is the zero address"
);
( , _amountLP, )= withdrawalNFT.pendingWithdrawPerAddress(_users[i]);
if (withdrawalNFT.balanceOf( _users[i]) == 0) {
continue;
}
_amountLP = Math.min((maxWithdrawAmount * _amountLP)/( ALPHA_PRICE * withdrawAmountTotalOld), _amountLP);
acceptedWithdrawPerAddress[_users[i]] = _amountLP;
}
}
// Validate users deposit requests
function finalizeDeposits( address[] memory _users) external
whenNotPaused onlyManager {
uint256 _amountStable;
uint256 _amountStableTotal = 0;
uint256 _depositAlpha;
uint256 _depositAlphaTotal = 0;
uint256 _feeStable;
uint256 _feeStableTotal = 0;
uint256 _tokenIdDeposit;
require (_users.length > 0, "Formation.Fi: no users provided ");
for (uint256 i = 0; i < _users.length ; i++) {
address _user =_users[i];
( , _amountStable, )= depositNFT.pendingDepositPerAddress(_user);
if (depositNFT.balanceOf(_user) == 0) {
continue;
}
if (maxDepositAmount <= _amountStableTotal) {
break;
}
_tokenIdDeposit = depositNFT.getTokenId(_user);
_amountStable = Math.min(maxDepositAmount - _amountStableTotal , _amountStable);
_feeStable = (_amountStable * DEPOSIT_FEE_RATE ) /
COEFF_SCALE_DECIMALS_F;
depositAmountTotal = depositAmountTotal - _amountStable;
_feeStableTotal = _feeStableTotal + _feeStable;
_depositAlpha = (( _amountStable - _feeStable) *
COEFF_SCALE_DECIMALS_P) / ALPHA_PRICE;
_depositAlphaTotal = _depositAlphaTotal + _depositAlpha;
_amountStableTotal = _amountStableTotal + _amountStable;
alphaToken.mint(_user, _depositAlpha);
depositNFT.updateDepositData( _user, _tokenIdDeposit, _amountStable, false);
alphaToken.addAmountDeposit(_user, _depositAlpha );
alphaToken.addTimeDeposit(_user, block.timestamp);
}
maxDepositAmount = maxDepositAmount - _amountStableTotal;
if (_depositAlphaTotal >0){
ALPHA_PRICE_WAVG = (( totalSupply * ALPHA_PRICE_WAVG) + ( _depositAlphaTotal * ALPHA_PRICE)) /
( totalSupply + _depositAlphaTotal);
}
admin.updateAlphaPriceWAVG( ALPHA_PRICE_WAVG);
if (admin.MANAGEMENT_FEE_TIME() == 0){
admin.updateManagementFeeTime(block.timestamp);
}
if ( _feeStableTotal >0){
stableToken.safeTransfer( treasury, _feeStableTotal/AMOUNT_SCALE_DECIMALS);
}
}
// Validate users withdrawal requests
function finalizeWithdrawals(address[] memory _users) external
whenNotPaused onlyManager {
uint256 tokensToBurn = 0;
uint256 _amountLP;
uint256 _amountStable;
uint256 _tokenIdWithdraw;
calculateAcceptedWithdrawRequests(_users);
for (uint256 i = 0; i < _users.length; i++) {
address _user =_users[i];
( , _amountLP, )= withdrawalNFT.pendingWithdrawPerAddress(_user);
if (withdrawalNFT.balanceOf(_user) == 0) {
continue;
}
_amountLP = acceptedWithdrawPerAddress[_user];
withdrawAmountTotal = withdrawAmountTotal - _amountLP ;
_amountStable = (_amountLP * ALPHA_PRICE) /
( COEFF_SCALE_DECIMALS_P * AMOUNT_SCALE_DECIMALS);
stableToken.safeTransfer(_user, _amountStable);
_tokenIdWithdraw = withdrawalNFT.getTokenId(_user);
withdrawalNFT.updateWithdrawData( _user, _tokenIdWithdraw, _amountLP, false);
tokensToBurn = tokensToBurn + _amountLP;
alphaToken.updateDepositDataExternal(_user, _amountLP);
delete acceptedWithdrawPerAddress[_user];
}
if ((tokensToBurn) > 0){
alphaToken.burn(address(this), tokensToBurn);
}
if (withdrawAmountTotal == 0){
withdrawAmountTotalOld = 0;
}
}
// Make deposit stable token request
function depositRequest(uint256 _amount) external whenNotPaused {
require(_amount >= admin.MIN_AMOUNT(),
"Formation.Fi: amount is lower than the minimum deposit amount");
if (depositNFT.balanceOf(msg.sender)==0){
tokenIdDeposit = tokenIdDeposit +1;
depositNFT.mint(msg.sender, tokenIdDeposit, _amount);
}
else {
uint256 _tokenIdDeposit = depositNFT.getTokenId(msg.sender);
depositNFT.updateDepositData (msg.sender, _tokenIdDeposit, _amount, true);
}
depositAmountTotal = depositAmountTotal + _amount;
stableToken.safeTransferFrom(msg.sender, address(this), _amount/AMOUNT_SCALE_DECIMALS);
}
// Cancel deposit stable token request
function cancelDepositRequest(uint256 _amount) external whenNotPaused canCancel {
uint256 _tokenIdDeposit = depositNFT.getTokenId(msg.sender);
require( _tokenIdDeposit > 0,
"Formation.Fi: deposit request doesn't exist");
depositNFT.updateDepositData(msg.sender, _tokenIdDeposit, _amount, false);
depositAmountTotal = depositAmountTotal - _amount;
stableToken.safeTransfer(msg.sender, _amount/AMOUNT_SCALE_DECIMALS);
}
// Make withdrawal ALPHA token request
function withdrawRequest(uint256 _amount) external whenNotPaused {
require ( _amount > 0, "Formation Fi: amount is zero");
require(withdrawalNFT.balanceOf(msg.sender) == 0, "Formation.Fi: withdraw request on pending");
require (alphaToken.ChecklWithdrawalRequest(msg.sender, _amount, admin.LOCKUP_PERIOD_USER()),
"Formation.Fi: user Position locked");
tokenIdWithdraw = tokenIdWithdraw +1;
withdrawalNFT.mint(msg.sender, tokenIdWithdraw, _amount);
withdrawAmountTotal = withdrawAmountTotal + _amount;
alphaToken.transferFrom(msg.sender, address(this), _amount);
}
// Cancel withdraw ALPHA token request
function cancelWithdrawalRequest( uint256 _amount) external whenNotPaused {
require ( _amount > 0, "Formation Fi: amount is zero");
uint256 _tokenIdWithdraw = withdrawalNFT.getTokenId(msg.sender);
require( _tokenIdWithdraw > 0,
"Formation.Fi: withdraw request doesn't exist");
withdrawalNFT.updateWithdrawData(msg.sender, _tokenIdWithdraw, _amount, false);
withdrawAmountTotal = withdrawAmountTotal - _amount;
alphaToken.transfer(msg.sender, _amount);
}
// Withdraw stable tokens from the contract
function availableBalanceWithdrawal(uint256 _amount) external
whenNotPaused onlyManager {
require((block.timestamp - TIME_WITHDRAW_MANAGER) >= admin.LOCKUP_PERIOD_MANAGER(),
"Formation.Fi: Manager Position locked");
uint256 _amountScaled = _amount/AMOUNT_SCALE_DECIMALS;
require(
stableToken.balanceOf(address(this)) >= _amountScaled,
"Formation.Fi: requested amount exceeds contract balance"
);
TIME_WITHDRAW_MANAGER = block.timestamp;
stableToken.safeTransfer(admin.manager(), _amountScaled);
}
// Send stable tokens to the contract
function sendStableTocontract(uint256 _amount) external
whenNotPaused onlyManager {
require( _amount > 0, "Formation.Fi: amount is zero");
stableToken.safeTransferFrom(msg.sender, address(this), _amount/AMOUNT_SCALE_DECIMALS);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
library SafeERC20 {
function safeSymbol(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(
abi.encodeWithSelector(0x95d89b41)
);
return success && data.length > 0 ? abi.decode(data, (string)) : "???";
}
function safeName(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(
abi.encodeWithSelector(0x06fdde03)
);
return success && data.length > 0 ? abi.decode(data, (string)) : "???";
}
function safeDecimals(IERC20 token) public view returns (uint8) {
(bool success, bytes memory data) = address(token).staticcall(
abi.encodeWithSelector(0x313ce567)
);
return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
}
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(0xa9059cbb, to, amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"SafeERC20: Transfer failed"
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(0x23b872dd, from, to, amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"SafeERC20: TransferFrom failed"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.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, "Transaction is not available");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused, "Transaction is available");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol)
pragma solidity ^0.8.4;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./libraries/SafeERC20.sol";
import "../utils/Pausable.sol";
import "./libraries/Math.sol";
import "./AlphaToken.sol";
/**
* @title AdminInterface
* @dev Implementation of AdminInterface
*/
contract AdminInterface is Pausable {
using SafeERC20 for IERC20;
// Decimal factors
uint256 public COEFF_SCALE_DECIMALS_F = 1e4; // for fees
uint256 public COEFF_SCALE_DECIMALS_P = 1e6; // for price
uint256 public AMOUNT_SCALE_DECIMALS = 1; // for stable token
// Fees rate
uint256 public DEPOSIT_FEE_RATE = 50; //
uint256 public MANAGEMENT_FEE_RATE = 200;
uint256 public PERFORMANCE_FEE_RATE = 2000;
// Fees parameters
uint256 public SECONDES_PER_YEAR = 86400 * 365;
uint256 public PERFORMANCE_FEES = 0;
uint256 public MANAGEMENT_FEES = 0;
uint256 public MANAGEMENT_FEE_TIME = 0;
// ALPHA price
uint256 public ALPHA_PRICE = 1000000;
uint256 public ALPHA_PRICE_WAVG = 1000000;
// User deposit parameters
uint256 public MIN_AMOUNT = 1000 * 1e18;
bool public CAN_CANCEL = true;
// Withdrawal parameters
uint256 public LOCKUP_PERIOD_MANAGER = 2 hours;
uint256 public LOCKUP_PERIOD_USER = 0 days;
uint256 public TIME_WITHDRAW_MANAGER = 0;
// Portfolio management parameters
uint public netDepositInd= 0;
uint256 public netAmountEvent =0;
uint256 public SLIPPAGE_TOLERANCE = 200;
address public manager;
address public treasury;
address public alphaStrategy;
//Contracts
AlphaToken public alphaToken;
IERC20 public stableToken;
constructor( address _manager, address _treasury, address _stableTokenAddress,
address _alphaToken) {
require(
_manager != address(0),
"Formation.Fi: manager address is the zero address"
);
require(
_treasury != address(0),
"Formation.Fi: treasury address is the zero address"
);
require(
_stableTokenAddress != address(0),
"Formation.Fi: Stable token address is the zero address"
);
require(
_alphaToken != address(0),
"Formation.Fi: ALPHA token address is the zero address"
);
manager = _manager;
treasury = _treasury;
stableToken = IERC20(_stableTokenAddress);
alphaToken = AlphaToken(_alphaToken);
uint8 _stableTokenDecimals = ERC20( _stableTokenAddress).decimals();
if ( _stableTokenDecimals == 6) {
AMOUNT_SCALE_DECIMALS= 1e12;
}
}
// Modifiers
modifier onlyAlphaStrategy() {
require(alphaStrategy != address(0),
"Formation.Fi: alphaStrategy is the zero address"
);
require(msg.sender == alphaStrategy,
"Formation.Fi: Caller is not the alphaStrategy"
);
_;
}
modifier onlyManager() {
require(msg.sender == manager,
"Formation.Fi: Caller is not the manager");
_;
}
modifier canCancel() {
require(CAN_CANCEL == true, "Formation Fi: Cancel feature is not available");
_;
}
// Setter functions
function setTreasury(address _treasury) external onlyOwner {
require(
_treasury != address(0),
"Formation.Fi: manager address is the zero address"
);
treasury = _treasury;
}
function setManager(address _manager) external onlyOwner {
require(
_manager != address(0),
"Formation.Fi: manager address is the zero address"
);
manager = _manager;
}
function setAlphaStrategy(address _alphaStrategy) public onlyOwner {
require(
_alphaStrategy!= address(0),
"Formation.Fi: alphaStrategy is the zero address"
);
alphaStrategy = _alphaStrategy;
}
function setCancel(bool _cancel) external onlyManager {
CAN_CANCEL = _cancel;
}
function setLockupPeriodManager(uint256 _lockupPeriodManager) external onlyManager {
LOCKUP_PERIOD_MANAGER = _lockupPeriodManager;
}
function setLockupPeriodUser(uint256 _lockupPeriodUser) external onlyManager {
LOCKUP_PERIOD_USER = _lockupPeriodUser;
}
function setDepositFeeRate(uint256 _rate) external onlyManager {
DEPOSIT_FEE_RATE = _rate;
}
function setManagementFeeRate(uint256 _rate) external onlyManager {
MANAGEMENT_FEE_RATE = _rate;
}
function setPerformanceFeeRate(uint256 _rate) external onlyManager {
PERFORMANCE_FEE_RATE = _rate;
}
function setMinAmount(uint256 _minAmount) external onlyManager {
MIN_AMOUNT = _minAmount;
}
function setCoeffScaleDecimalsFees (uint256 _scale) external onlyManager {
require(
_scale > 0,
"Formation.Fi: decimal fees factor is 0"
);
COEFF_SCALE_DECIMALS_F = _scale;
}
function setCoeffScaleDecimalsPrice (uint256 _scale) external onlyManager {
require(
_scale > 0,
"Formation.Fi: decimal price factor is 0"
);
COEFF_SCALE_DECIMALS_P = _scale;
}
function updateAlphaPrice(uint256 _price) external onlyManager{
require(
_price > 0,
"Formation.Fi: ALPHA price is 0"
);
ALPHA_PRICE = _price;
}
function updateAlphaPriceWAVG(uint256 _price_WAVG) external onlyAlphaStrategy {
require(
_price_WAVG > 0,
"Formation.Fi: ALPHA price WAVG is 0"
);
ALPHA_PRICE_WAVG = _price_WAVG;
}
function updateManagementFeeTime(uint256 _time) external onlyAlphaStrategy {
MANAGEMENT_FEE_TIME = _time;
}
// Calculate fees
function calculatePerformanceFees() external onlyManager {
require(PERFORMANCE_FEES == 0, "Formation.Fi: performance fees pending minting");
uint256 _deltaPrice = 0;
if (ALPHA_PRICE > ALPHA_PRICE_WAVG) {
_deltaPrice = ALPHA_PRICE - ALPHA_PRICE_WAVG;
ALPHA_PRICE_WAVG = ALPHA_PRICE;
PERFORMANCE_FEES = (alphaToken.totalSupply() *
_deltaPrice * PERFORMANCE_FEE_RATE) / (ALPHA_PRICE * COEFF_SCALE_DECIMALS_F);
}
}
function calculateManagementFees() external onlyManager {
require(MANAGEMENT_FEES == 0, "Formation.Fi: management fees pending minting");
if (MANAGEMENT_FEE_TIME!= 0){
uint256 _deltaTime;
_deltaTime = block.timestamp - MANAGEMENT_FEE_TIME;
MANAGEMENT_FEES = (alphaToken.totalSupply() * MANAGEMENT_FEE_RATE * _deltaTime )
/(COEFF_SCALE_DECIMALS_F * SECONDES_PER_YEAR);
MANAGEMENT_FEE_TIME = block.timestamp;
}
}
// Mint fees
function mintFees() external onlyManager {
if ((PERFORMANCE_FEES + MANAGEMENT_FEES) > 0){
alphaToken.mint(treasury, PERFORMANCE_FEES + MANAGEMENT_FEES);
PERFORMANCE_FEES = 0;
MANAGEMENT_FEES = 0;
}
}
// Calculate protfolio deposit indicator
function calculateNetDepositInd(uint256 _depositAmountTotal, uint256 _withdrawAmountTotal)
public onlyAlphaStrategy returns( uint) {
if ( _depositAmountTotal >=
((_withdrawAmountTotal * ALPHA_PRICE) / COEFF_SCALE_DECIMALS_P)){
netDepositInd = 1 ;
}
else {
netDepositInd = 0;
}
return netDepositInd;
}
// Calculate protfolio Amount
function calculateNetAmountEvent(uint256 _depositAmountTotal, uint256 _withdrawAmountTotal,
uint256 _MAX_AMOUNT_DEPOSIT, uint256 _MAX_AMOUNT_WITHDRAW)
public onlyAlphaStrategy returns(uint256) {
uint256 _netDeposit;
if (netDepositInd == 1) {
_netDeposit = _depositAmountTotal -
(_withdrawAmountTotal * ALPHA_PRICE) / COEFF_SCALE_DECIMALS_P;
netAmountEvent = Math.min( _netDeposit, _MAX_AMOUNT_DEPOSIT);
}
else {
_netDeposit= ((_withdrawAmountTotal * ALPHA_PRICE) / COEFF_SCALE_DECIMALS_P) -
_depositAmountTotal;
netAmountEvent = Math.min(_netDeposit, _MAX_AMOUNT_WITHDRAW);
}
return netAmountEvent;
}
// Protect against Slippage
function protectAgainstSlippage(uint256 _withdrawAmount) public onlyManager
whenNotPaused returns (uint256) {
require(netDepositInd == 0, "Formation.Fi: it is not a slippage case");
require(_withdrawAmount != 0, "Formation.Fi: amount is zero");
uint256 _amount = 0;
uint256 _deltaAmount =0;
uint256 _slippage = 0;
uint256 _alphaAmount = 0;
uint256 _balanceAlphaTreasury = alphaToken.balanceOf(treasury);
uint256 _balanceStableTreasury = stableToken.balanceOf(treasury) * AMOUNT_SCALE_DECIMALS;
if (_withdrawAmount< netAmountEvent){
_amount = netAmountEvent - _withdrawAmount;
_slippage = (_amount * COEFF_SCALE_DECIMALS_F ) / netAmountEvent;
if (_slippage >= SLIPPAGE_TOLERANCE) {
return netAmountEvent;
}
else {
_deltaAmount = Math.min( _amount, _balanceStableTreasury);
if ( _deltaAmount > 0){
stableToken.safeTransferFrom(treasury, alphaStrategy, _deltaAmount/AMOUNT_SCALE_DECIMALS);
_alphaAmount = (_deltaAmount * COEFF_SCALE_DECIMALS_P)/ALPHA_PRICE;
alphaToken.mint(treasury, _alphaAmount);
return _amount - _deltaAmount;
}
else {
return _amount;
}
}
}
else {
_amount = _withdrawAmount - netAmountEvent;
_alphaAmount = (_amount * COEFF_SCALE_DECIMALS_P)/ALPHA_PRICE;
_alphaAmount = Math.min(_alphaAmount, _balanceAlphaTreasury);
if (_alphaAmount >0) {
_deltaAmount = (_alphaAmount * ALPHA_PRICE)/COEFF_SCALE_DECIMALS_P;
stableToken.safeTransfer(treasury, _deltaAmount/AMOUNT_SCALE_DECIMALS);
alphaToken.burn( treasury, _alphaAmount);
}
if ((_amount - _deltaAmount) > 0) {
stableToken.safeTransfer(manager, (_amount - _deltaAmount)/AMOUNT_SCALE_DECIMALS);
}
}
return 0;
}
// send Stable Tokens to the contract
function sendStableTocontract(uint256 _amount) external
whenNotPaused onlyManager {
require( _amount > 0, "Formation.Fi: amount is zero");
stableToken.safeTransferFrom(msg.sender, address(this), _amount/AMOUNT_SCALE_DECIMALS);
}
// send Stable Tokens from the contract AlphaStrategy
function sendStableFromcontract() external
whenNotPaused onlyManager {
require(alphaStrategy != address(0),
"Formation.Fi: alphaStrategy is the zero address"
);
stableToken.safeTransfer(alphaStrategy, stableToken.balanceOf(address(this)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./libraries/Math.sol";
/**
* @title AlphaToken
* @dev Implementation of the LP Token "ALPHA".
*/
contract AlphaToken is ERC20, Ownable {
// Proxy address
address alphaStrategy;
address admin;
// Deposit Mapping
mapping(address => uint256[]) public amountDepositPerAddress;
mapping(address => uint256[]) public timeDepositPerAddress;
constructor() ERC20("Formation Fi: ALPHA TOKEN", "ALPHA") {}
// Modifiers
modifier onlyProxy() {
require(
(alphaStrategy != address(0)) && (admin != address(0)),
"Formation.Fi: proxy is the zero address"
);
require(
(msg.sender == alphaStrategy) || (msg.sender == admin),
"Formation.Fi: Caller is not the proxy"
);
_;
}
modifier onlyAlphaStrategy() {
require(alphaStrategy != address(0),
"Formation.Fi: alphaStrategy is the zero address"
);
require(msg.sender == alphaStrategy,
"Formation.Fi: Caller is not the alphaStrategy"
);
_;
}
// Setter functions
function setAlphaStrategy(address _alphaStrategy) external onlyOwner {
require(
_alphaStrategy!= address(0),
"Formation.Fi: alphaStrategy is the zero address"
);
alphaStrategy = _alphaStrategy;
}
function setAdmin(address _admin) external onlyOwner {
require(
_admin!= address(0),
"Formation.Fi: admin is the zero address"
);
admin = _admin;
}
function addTimeDeposit(address _account, uint256 _time) external onlyAlphaStrategy {
require(
_account!= address(0),
"Formation.Fi: account is the zero address"
);
require(
_time!= 0,
"Formation.Fi: deposit time is zero"
);
timeDepositPerAddress[_account].push(_time);
}
function addAmountDeposit(address _account, uint256 _amount) external onlyAlphaStrategy {
require(
_account!= address(0),
"Formation.Fi: account is the zero address"
);
require(
_amount!= 0,
"Formation.Fi: deposit amount is zero"
);
amountDepositPerAddress[_account].push(_amount);
}
// functions "mint" and "burn"
function mint(address _account, uint256 _amount) external onlyProxy {
require(
_account!= address(0),
"Formation.Fi: account is the zero address"
);
require(
_amount!= 0,
"Formation.Fi: amount is zero"
);
_mint(_account, _amount);
}
function burn(address _account, uint256 _amount) external onlyProxy {
require(
_account!= address(0),
"Formation.Fi: account is the zero address"
);
require(
_amount!= 0,
"Formation.Fi: amount is zero"
);
_burn( _account, _amount);
}
// Check the user lock up condition for his withdrawal request
function ChecklWithdrawalRequest(address _account, uint256 _amount, uint256 _period)
external view returns (bool){
require(
_account!= address(0),
"Formation.Fi: account is the zero address"
);
require(
_amount!= 0,
"Formation.Fi: amount is zero"
);
uint256 [] memory _amountDeposit = amountDepositPerAddress[_account];
uint256 [] memory _timeDeposit = timeDepositPerAddress[_account];
uint256 _amountTotal = 0;
for (uint256 i = 0; i < _amountDeposit.length; i++) {
require ((block.timestamp - _timeDeposit[i]) >= _period,
"Formation.Fi: user position locked");
if (_amount<= (_amountTotal + _amountDeposit[i])){
break;
}
_amountTotal = _amountTotal + _amountDeposit[i];
}
return true;
}
// Functions to update users deposit data
function updateDepositDataExternal( address _account, uint256 _amount)
external onlyAlphaStrategy {
updateDepositData(_account, _amount);
}
function updateDepositData( address _account, uint256 _amount) internal {
require(
_account!= address(0),
"Formation.Fi: account is the zero address"
);
require(
_amount!= 0,
"Formation.Fi: amount is zero"
);
uint256 [] memory _amountDeposit = amountDepositPerAddress[ _account];
uint256 _amountlocal = 0;
uint256 _amountTotal = 0;
uint256 _newAmount;
for (uint256 i = 0; i < _amountDeposit.length; i++) {
_amountlocal = Math.min(_amountDeposit[i], _amount- _amountTotal);
_amountTotal = _amountTotal + _amountlocal;
_newAmount = _amountDeposit[i] - _amountlocal;
amountDepositPerAddress[_account][i] = _newAmount;
if (_newAmount==0){
deleteDepositData(_account, i);
}
if (_amountTotal == _amount){
break;
}
}
}
// Delete deposit data
function deleteDepositData(address _account, uint256 _ind) internal {
require(
_account!= address(0),
"Formation.Fi: account is the zero address"
);
uint256 size = amountDepositPerAddress[_account].length-1;
require( _ind <= size,
"Formation.Fi: index is out of the range"
);
for (uint256 i = _ind; i< size; i++){
amountDepositPerAddress[ _account][i] = amountDepositPerAddress[ _account][i+1];
timeDepositPerAddress[ _account][i] = timeDepositPerAddress[ _account][i+1];
}
amountDepositPerAddress[ _account].pop();
timeDepositPerAddress[ _account].pop();
}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override{
if ((to != address(0)) && (to != alphaStrategy)
&& (to != admin) && (from != address(0)) )
{
updateDepositData(from, amount);
amountDepositPerAddress[to].push(amount);
timeDepositPerAddress[to].push(block.timestamp);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./libraries/Data.sol";
/**
* @title DepositNFT
* @dev Implementation of DepositNFT "The deposit Proof"
*/
contract DepositNFT is ERC721, Ownable {
struct PendingDeposit {
Data.State state;
uint256 amountStable;
uint256 listPointer;
}
// Proxy "alphaStrategy contract
address public proxy;
// Users deposit data
mapping(address => PendingDeposit) public pendingDepositPerAddress;
address[] public usersOnPendingDeposit;
// NFT mapping
mapping(address => uint256) private tokenIdPerAddress;
constructor () ERC721 ("Alpha Deposit ", "ALPHA_D"){
}
// Modifiers
modifier onlyProxy() {
require(
proxy != address(0),
"Formation.Fi: proxy is the zero address"
);
require(msg.sender == proxy, "Formation.Fi: Caller is not the proxy");
_;
}
// Getter functions
function getTokenId(address _account) public view returns (uint256) {
require(
_account!= address(0),
"Formation.Fi: account is the zero address"
);
return tokenIdPerAddress[_account];
}
function getUsersSize() public view returns (uint256) {
return usersOnPendingDeposit.length;
}
function getUsers() public view returns (address[] memory) {
return usersOnPendingDeposit;
}
// Setter functions
function setProxy(address _proxy) public onlyOwner {
require(
_proxy != address(0),
"Formation.Fi: proxy is the zero address"
);
proxy = _proxy;
}
// Functions "mint" and "burn"
function mint(address _account, uint256 _tokenId, uint256 _amount)
external onlyProxy {
require (balanceOf(_account) == 0, "Formation.Fi: account has already a deposit NFT");
_safeMint(_account, _tokenId);
updateDepositData( _account, _tokenId, _amount, true);
}
function burn(uint256 tokenId) internal {
address owner = ownerOf(tokenId);
require (pendingDepositPerAddress[owner].state != Data.State.PENDING,
"Formation.Fi: position is on pending");
deleteDepositData(owner);
_burn(tokenId);
}
// Update user deposit data
function updateDepositData(address _account, uint256 _tokenId,
uint256 _amount, bool add) public onlyProxy {
require (_exists(_tokenId), "Formation.Fi: token does not exist");
require (ownerOf(_tokenId) == _account , "Formation.Fi: account is not the token owner");
if( _amount > 0){
if (add){
if(pendingDepositPerAddress[_account].amountStable == 0){
pendingDepositPerAddress[_account].state = Data.State.PENDING;
pendingDepositPerAddress[_account].listPointer = usersOnPendingDeposit.length;
tokenIdPerAddress[_account] = _tokenId;
usersOnPendingDeposit.push(_account);
}
pendingDepositPerAddress[_account].amountStable = pendingDepositPerAddress[_account].amountStable
+ _amount;
}
else {
require(pendingDepositPerAddress[_account].amountStable >= _amount,
"Formation Fi: amount excedes pending deposit");
uint256 _newAmount = pendingDepositPerAddress[_account].amountStable - _amount;
pendingDepositPerAddress[_account].amountStable = _newAmount;
if (_newAmount == 0){
pendingDepositPerAddress[_account].state = Data.State.NONE;
burn(_tokenId);
}
}
}
}
// Delete user deposit data
function deleteDepositData(address _account) internal {
require(
_account!= address(0),
"Formation.Fi: account is the zero address"
);
uint256 _ind = pendingDepositPerAddress[_account].listPointer;
address _user = usersOnPendingDeposit[usersOnPendingDeposit.length - 1];
usersOnPendingDeposit[_ind] = _user;
pendingDepositPerAddress[_user].listPointer = _ind;
usersOnPendingDeposit.pop();
delete pendingDepositPerAddress[_account];
delete tokenIdPerAddress[_account];
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
if ((to != address(0)) && (from != address(0))){
require ((to != proxy),
"Formation.Fi: destination address cannot be the proxy"
);
uint256 indFrom = pendingDepositPerAddress[from].listPointer;
pendingDepositPerAddress[to] = pendingDepositPerAddress[from];
pendingDepositPerAddress[from].state = Data.State.NONE;
pendingDepositPerAddress[from].amountStable =0;
usersOnPendingDeposit[indFrom] = to;
tokenIdPerAddress[to] = tokenIdPerAddress[from];
delete pendingDepositPerAddress[from];
delete tokenIdPerAddress[from];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./libraries/Data.sol";
/**
* @title WithdrawalNFT
* @dev Implementation of WithdrawalNFT "The Withdrawal Proof"
*/
contract WithdrawalNFT is ERC721, Ownable {
// Proxy "alphaStrategy contract
address proxy;
// Users Withdrawal data
struct PendingWithdrawal {
Data.State state;
uint256 amountAlpha;
uint256 listPointer;
}
mapping(address => PendingWithdrawal) public pendingWithdrawPerAddress;
address[] public usersOnPendingWithdraw;
// NFT mapping
mapping(address => uint256) private tokenIdPerAddress;
constructor () ERC721 ("Alpha Withdraw", "Alpha_W"){
}
// Modifiers
modifier onlyProxy() {
require(
proxy != address(0),
"Formation.Fi: proxy is the zero address"
);
require(msg.sender == proxy, "Formation.Fi: Caller is not the proxy");
_;
}
// Getter functions
function getTokenId(address _owner) public view returns (uint256) {
return tokenIdPerAddress[ _owner];
}
function getUsersSize() public view returns (uint256) {
return usersOnPendingWithdraw.length;
}
function getUsers() public view returns (address[] memory) {
return usersOnPendingWithdraw;
}
// Setter functions
function setProxy(address _proxy) public onlyOwner {
require(
_proxy != address(0),
"Formation.Fi: proxy is the zero address"
);
proxy = _proxy;
}
// Functions "mint" and "burn"
function mint(address _account, uint256 _tokenId, uint256 _amount)
external onlyProxy {
require (balanceOf( _account) == 0, "Formation.Fi: account has already a withdraw NFT");
_safeMint(_account, _tokenId);
tokenIdPerAddress[_account] = _tokenId;
updateWithdrawData (_account, _tokenId, _amount, true);
}
function burn(uint256 tokenId) internal {
address owner = ownerOf(tokenId);
require (pendingWithdrawPerAddress[owner].state != Data.State.PENDING,
"Formation.Fi: position is on pending");
deleteWithdrawData(owner);
_burn(tokenId);
}
// Update user withdraw data
function updateWithdrawData (address _account, uint256 _tokenId,
uint256 _amount, bool add) public onlyProxy {
require (_exists(_tokenId), "Formation Fi: token does not exist");
require (ownerOf(_tokenId) == _account ,
"Formation.Fi: account is not the token owner");
if( _amount > 0){
if (add){
pendingWithdrawPerAddress[_account].state = Data.State.PENDING;
pendingWithdrawPerAddress[_account].amountAlpha = _amount;
pendingWithdrawPerAddress[_account].listPointer = usersOnPendingWithdraw.length;
usersOnPendingWithdraw.push(_account);
}
else {
require(pendingWithdrawPerAddress[_account].amountAlpha >= _amount,
"Formation.Fi: amount excedes pending withdraw");
uint256 _newAmount = pendingWithdrawPerAddress[_account].amountAlpha - _amount;
pendingWithdrawPerAddress[_account].amountAlpha = _newAmount;
if (_newAmount == 0){
pendingWithdrawPerAddress[_account].state = Data.State.NONE;
burn(_tokenId);
}
}
}
}
// Delete user withdraw data
function deleteWithdrawData(address _account) internal {
require(
_account!= address(0),
"Formation.Fi: account is the zero address"
);
uint256 _ind = pendingWithdrawPerAddress[_account].listPointer;
address _user = usersOnPendingWithdraw[usersOnPendingWithdraw.length -1];
usersOnPendingWithdraw[ _ind] = _user ;
pendingWithdrawPerAddress[ _user].listPointer = _ind;
usersOnPendingWithdraw.pop();
delete pendingWithdrawPerAddress[_account];
delete tokenIdPerAddress[_account];
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
if ((to != address(0)) && (from != address(0))){
require ((to != proxy),
"Formation Fi: destination address is the proxy"
);
uint256 indFrom = pendingWithdrawPerAddress[from].listPointer;
pendingWithdrawPerAddress[to] = pendingWithdrawPerAddress[from];
pendingWithdrawPerAddress[from].state = Data.State.NONE;
pendingWithdrawPerAddress[from].amountAlpha =0;
usersOnPendingWithdraw[indFrom] = to;
tokenIdPerAddress[to] = tokenIdPerAddress[from];
delete pendingWithdrawPerAddress[from];
delete tokenIdPerAddress[from];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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;
/**
* @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";
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 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 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;
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;
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.4;
library Data {
enum State {
NONE,
PENDING,
READY
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
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 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;
/**
* @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);
} | functions "mint" and "burn" | function mint(address _account, uint256 _amount) external onlyProxy {
require(
_account!= address(0),
"Formation.Fi: account is the zero address"
);
require(
_amount!= 0,
"Formation.Fi: amount is zero"
);
_mint(_account, _amount);
}
| 1,652,646 | [
1,
10722,
315,
81,
474,
6,
471,
315,
70,
321,
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,
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,
282,
445,
312,
474,
12,
2867,
389,
4631,
16,
2254,
5034,
389,
8949,
13,
3903,
1338,
3886,
288,
203,
4202,
2583,
12,
203,
1850,
389,
4631,
5,
33,
1758,
12,
20,
3631,
203,
6647,
315,
12624,
18,
42,
77,
30,
2236,
353,
326,
3634,
1758,
6,
203,
3639,
11272,
203,
540,
2583,
12,
203,
5411,
389,
8949,
5,
33,
374,
16,
203,
5411,
315,
12624,
18,
42,
77,
30,
3844,
353,
3634,
6,
203,
3639,
11272,
203,
4202,
389,
81,
474,
24899,
4631,
16,
225,
389,
8949,
1769,
203,
282,
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
] |
./full_match/4/0x8DE09Ac58C42aB4B0c3638a243C206C6454eCEd4/sources/contracts/test.sol | The token being sold Address where funds are collected How many token units a buyer gets per wei Amount of wei raised | contract SimpleCrowdsale {
using SafeMath for uint256;
address public token;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
uint256 total_tokens_value;
bool public locked = false;
address payable owner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
constructor(uint256 t_rate,address payable t_wallet,address t_token) public{
token = t_token;
owner = t_wallet;
rate = t_rate;
}
function total_tokens() public view returns (uint256)
{
return IERC20(token).balanceOf(address(this));
}
function upadte_total_tokens() internal
{
total_tokens_value = IERC20(token).balanceOf(address(this));
}
function unlock() public onlyOwner {
locked = false;
}
function get_back_all_tokens() public {
IERC20(token).transfer(msg.sender, IERC20(token).balanceOf(address(this)));
upadte_total_tokens();
}
function get_back_tokens(uint256 amount) public {
require(msg.sender == owner,"Only owner");
IERC20(token).transfer(msg.sender, amount);
upadte_total_tokens();
}
function lock() public onlyOwner {
locked = true;
}
receive() external payable {
}
fallback() external payable {
}
function buyTokens(address payable _beneficiary) public payable{
require(!locked, "Locked");
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary,msg.value);
uint256 t_rate = _getTokenAmount(weiAmount);
_deliverTokens(_beneficiary, t_rate);
upadte_total_tokens();
}
function _preValidatePurchase (
address _beneficiary,
uint256 _weiAmount
) pure
internal
{
require(_beneficiary != address(0), "Beneficiary = address(0)");
require(_weiAmount >= 100000000000000000 || _weiAmount <= 10000000000000000000 ,"send Minimum 0.1 eth or 10 Eth max");
}
function extractEther() public onlyOwner {
owner.transfer(address(this).balance);
}
function _getTokenAmount(uint256 _weiAmount)
public view returns (uint256)
{
uint256 temp1 = _weiAmount.div(1000000000);
return temp1.mul(rate) * 10**9;
}
function _calculate_TokenAmount(uint256 _weiAmount, uint256 t_rate, uint divide_amount)
public pure returns (uint256)
{
uint256 temp2 = _weiAmount.div(divide_amount);
return temp2.mul(t_rate);
}
function update_rate(uint256 _rate)
public
{
require(msg.sender == owner,"Only owner");
rate = _rate;
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
IERC20(token).transfer(_beneficiary, _tokenAmount);
}
}
| 13,374,594 | [
1,
1986,
1147,
3832,
272,
1673,
5267,
1625,
284,
19156,
854,
12230,
9017,
4906,
1147,
4971,
279,
27037,
5571,
1534,
732,
77,
16811,
434,
732,
77,
11531,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
4477,
39,
492,
2377,
5349,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
225,
1758,
1071,
1147,
31,
203,
203,
225,
1758,
1071,
9230,
31,
203,
203,
225,
2254,
5034,
1071,
4993,
31,
203,
203,
225,
2254,
5034,
1071,
732,
77,
12649,
5918,
31,
203,
565,
2254,
5034,
2078,
67,
7860,
67,
1132,
31,
203,
21281,
225,
1426,
1071,
8586,
273,
629,
31,
203,
21281,
565,
1758,
8843,
429,
3410,
31,
203,
377,
203,
1377,
9606,
1338,
5541,
288,
203,
1377,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
1377,
389,
31,
203,
282,
289,
203,
203,
203,
21281,
565,
3885,
12,
11890,
5034,
268,
67,
5141,
16,
2867,
8843,
429,
268,
67,
19177,
16,
2867,
268,
67,
2316,
13,
1071,
95,
203,
3639,
1147,
273,
268,
67,
2316,
31,
203,
3639,
3410,
273,
268,
67,
19177,
31,
203,
3639,
4993,
273,
268,
67,
5141,
31,
203,
540,
203,
540,
203,
565,
289,
203,
3639,
445,
2078,
67,
7860,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
327,
467,
654,
39,
3462,
12,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
289,
203,
5411,
445,
731,
361,
736,
67,
4963,
67,
7860,
1435,
2713,
203,
565,
288,
203,
3639,
2078,
67,
7860,
67,
1132,
273,
467,
654,
39,
3462,
12,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
289,
203,
565,
445,
7186,
1435,
1071,
1338,
5541,
288,
203,
3639,
8586,
273,
629,
31,
203,
565,
289,
203,
2
] |
//SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
contract inbetween {
/********************
* Create Deck
*
********************/
struct Card {
string cardName;
uint256 rank;
}
mapping(uint256 => Card) cards;
constructor() {
cards[1] = Card("Ace of Hearts", 14);
cards[2] = Card("King of Hearts", 13);
cards[3] = Card("Queen of Hearts", 12);
cards[4] = Card("Jack of Hearts", 11);
cards[5] = Card("Ten of Hearts", 10);
cards[6] = Card("Nine of Hearts", 9);
cards[7] = Card("Eight of Hearts", 8);
cards[8] = Card("Seven of Hearts", 7);
cards[9] = Card("Six of Hearts", 6);
cards[10] = Card("Five of Hearts", 5);
cards[11] = Card("Four of Hearts", 4);
cards[12] = Card("Three of Hearts", 3);
cards[13] = Card("Two of Hearts", 2);
cards[14] = Card("Ace of Diamonds", 14);
cards[15] = Card("King of Diamonds", 13);
cards[16] = Card("Queen of Diamonds", 12);
cards[17] = Card("Jack of Diamonds", 11);
cards[18] = Card("Ten of Diamonds", 10);
cards[19] = Card("Nine of Diamonds", 9);
cards[20] = Card("Eight of Diamonds", 8);
cards[21] = Card("Seven of Diamonds", 7);
cards[22] = Card("Six of Diamonds", 6);
cards[23] = Card("Five of Diamonds", 5);
cards[24] = Card("Four of Diamonds", 4);
cards[25] = Card("Three of Diamonds", 3);
cards[26] = Card("Two of Diamonds", 2);
cards[27] = Card("Ace of Spades", 14);
cards[28] = Card("King of Spades", 13);
cards[29] = Card("Queen of Spades", 12);
cards[30] = Card("Jack of Spades", 11);
cards[31] = Card("Ten of Spades", 10);
cards[32] = Card("Nine of Spades", 9);
cards[33] = Card("Eight of Spades", 8);
cards[34] = Card("Seven of Spades", 7);
cards[35] = Card("Six of Spades", 6);
cards[36] = Card("Five of Spades", 5);
cards[37] = Card("Four of Spades", 4);
cards[38] = Card("Three of Spades", 3);
cards[39] = Card("Two of Spades", 2);
cards[40] = Card("Ace of Clubs", 14);
cards[41] = Card("King of Clubs", 13);
cards[42] = Card("Queen of Clubs", 12);
cards[43] = Card("Jack of Clubs", 11);
cards[44] = Card("Ten of Clubs", 10);
cards[45] = Card("Nine of Clubs", 9);
cards[46] = Card("Eight of Clubs", 8);
cards[47] = Card("Seven of Clubs", 7);
cards[48] = Card("Six of Clubs", 6);
cards[49] = Card("Five of Clubs", 5);
cards[50] = Card("Four of Clubs", 4);
cards[51] = Card("Three of Clubs", 3);
cards[52] = Card("Two of Clubs", 2);
}
/********************
* Game Variables
*
********************/
uint256 turnSelector = 1;
uint256 playerCount;
uint256 ante_amount;
bool game_started;
bool isRoundOne;
bool cardsDealt;
uint256 pot;
uint256 time_left = 30;
string whos_turn;
string[5] Whos_Turn_Array = ["", "It's Player_1's turn.", "It's Player_2's turn.", "It's Player_3's turn.", "It's Player_4's turn."];
string message;
string[3] Message_Array = ["Game has not started yet.", "Write 'Deal Cards' to see your first two cards.", "Write 'Bet' to see the third card or 'Pass' to pass the turn."];
string card_one;
string card_two;
uint256 card1rank;
uint256 card2rank;
string card_three;
uint256 card3rank;
string result;
string[6] Result_Array = ["", "Bet won!", "Bet lost!", "Turn passed", "Cards too close in rank, turn passed."]; //we have to ignore posts for now because there is no way to pull funds from a player,
//kinda jank to make players bet twice as much in the event they post
uint256 rand1;
uint256 rand2;
uint256 rand3;
/********************
* Player Data Arrays
*
********************/
string[5] playerIndexToName; //set player names
uint256[5] playerIndexToAcePref = [1,1,1,1,1]; //set first ace prefs, 0 = prefer low, 1 = prefer high
string[2] acePrefStatement = ["Aces are Low", "Aces are High"];
string[3] activityStatement = ["Position is empty", "Player is active", "Player is AFK, their turn will be passed"];
address[5] playerIndexToAddress; //set player 1 2 3 & 4 addresses
uint256[5] playerIndexIsInGame; //show whether a player is in the game, 1=ingame, 0=notingane useful for turn selector. using ints so i can add them
uint256[5] playerIndexIsAFK; //shows whether a player is afk,0=empty position 1=active, 2=afk. using ints so I can add them.
/********************
* Set Ante Amount
* (before someone
* antes up)
********************/
function Set_Ante_Amt(uint256 Ante_Amount) public {
require((game_started == false), "You cannot change this if the game has started or if there are people in the lobby.");
require((playerIndexIsInGame[1] + playerIndexIsInGame[2] + playerIndexIsInGame[3] + playerIndexIsInGame[4]) == 0, "You cannot change the ante amount while players are in the lobby.");
ante_amount = Ante_Amount;
pot = address(this).balance;
}
/********************
* Ante Up
* Pay Ante
*(before game starts)
********************/
function Ante_Up(uint256 _PlayerNumber,uint256 HighAce1_LowAce0,string memory Name) public payable {
require(ante_amount != 0, "Please set an ante amount using the 'Set_Ante_Amt' function.");
require(msg.sender != playerIndexToAddress[1], "You are already in the lobby (Player_1)");
require(msg.sender != playerIndexToAddress[2], "You are already in the lobby (Player_2)");
require(msg.sender != playerIndexToAddress[3], "You are already in the lobby (Player_3)");
require(msg.sender != playerIndexToAddress[4], "You are already in the lobby (Player_4)");
require(game_started == false, "The game has already started. You can only ante up before the game starts.");
require(msg.value == ante_amount, "You must pay the ante amount exactly.");
require(playerIndexIsAFK[_PlayerNumber] == 0, "There is already a player in this position.");
playerIndexToName[_PlayerNumber] = Name;
playerIndexToAcePref[_PlayerNumber] = HighAce1_LowAce0;
playerIndexToAddress[_PlayerNumber] = msg.sender;
playerIndexIsInGame[_PlayerNumber] = 1;
playerIndexIsAFK[_PlayerNumber] = 1;
pot = address(this).balance;
playerCount++;
}
/********************
* Remove Players
* Return Ante
*(before game starts)
********************/
function Remove_Player(uint256 _PlayerNumber) public {
require(game_started == false, "You can only remove players from lobbies before the game starts. Try starting a timer if a player is AFK.");
payable(playerIndexToAddress[_PlayerNumber]).transfer(ante_amount);
delete playerIndexToName[_PlayerNumber];
delete playerIndexToAcePref[_PlayerNumber];
delete playerIndexToAddress[_PlayerNumber];
playerIndexIsInGame[_PlayerNumber] = 0;
playerIndexIsAFK[_PlayerNumber] = 0;
playerCount = playerCount - 1;
pot = address(this).balance;
}
/********************
* Toggle aces preference
* (anytime)
********************/
function Toggle_Aces() public {
for(uint256 i=1; i<=4; i++) {
if(msg.sender == playerIndexToAddress[i]) {
if(playerIndexToAcePref[i] == 1) {
playerIndexToAcePref[i] = 0;
}
else {
playerIndexToAcePref[i] = 1;
}
}
}
}
/********************
* Toggle to "go AFK"
* (anytime)
********************/
function Toggle_AFK() public {
for(uint256 i=1; i<=4; i++) {
if(msg.sender == playerIndexToAddress[i]) {
if(playerIndexIsAFK[i] == 1) {
playerIndexIsAFK[i] = 2;
}
else {
playerIndexIsAFK[i] = 1;
}
}
}
}
/********************
* Request Player Info
* (anytime)
********************/
function Player_1() public view returns(string memory, string memory, string memory, address) {
return (playerIndexToName[1], acePrefStatement[playerIndexToAcePref[1]], activityStatement[playerIndexIsAFK[1]], playerIndexToAddress[1]);
}
function Player_2() public view returns(string memory, string memory, string memory, address) {
return (playerIndexToName[2], acePrefStatement[playerIndexToAcePref[2]], activityStatement[playerIndexIsAFK[2]], playerIndexToAddress[2]);
}
function Player_3() public view returns(string memory, string memory, string memory, address) {
return (playerIndexToName[3], acePrefStatement[playerIndexToAcePref[3]], activityStatement[playerIndexIsAFK[3]], playerIndexToAddress[3]);
}
function Player_4() public view returns(string memory, string memory, string memory, address) {
return (playerIndexToName[4], acePrefStatement[playerIndexToAcePref[4]], activityStatement[playerIndexIsAFK[4]], playerIndexToAddress[4]);
}
/********************
* Request Game Status
* (anytime)
********************/
function Game_Status() public view
returns(bool Game_Started, uint256 Player_Count, uint256 Ante_Amount, uint256 Pot, uint256 Time_Left, string memory Whos_Turn, string memory Message, string memory Card_1, string memory Card_2, string memory Card_3, string memory Result) {
return (game_started, playerCount, ante_amount, pot, time_left, whos_turn, message, card_one, card_two, card_three, result);
}
/********************
* Start the Game
*
********************/
function Start_Game() public {
require(game_started == false, "The game has already started.");
// require at least 2 players are in the lobby
playerCount = playerIndexIsInGame[1] + playerIndexIsInGame[2] + playerIndexIsInGame[3] + playerIndexIsInGame[4];
require(playerCount >=2, "There must be at least two players in the lobby to start a game.");
game_started = true;
isRoundOne = true;
message = Message_Array[1];
pot = address(this).balance;
if (playerIndexIsInGame[1] == 1) {
turnSelector = 1;
whos_turn = Whos_Turn_Array[1];
}
else if (playerIndexIsInGame[2] == 1) {
turnSelector = 2;
whos_turn = Whos_Turn_Array[2];
}
else if (playerIndexIsInGame[3] == 1) {
turnSelector = 3;
whos_turn = Whos_Turn_Array[3];
}
else if (playerIndexIsInGame[4] == 1) {
turnSelector = 4;
whos_turn = Whos_Turn_Array[4];
}
}
/********************
* Turn Selector
*
********************/
function UpdateTurn() private {
cardsDealt = false;
message = Message_Array[1];
if (turnSelector == 1) {
if (playerIndexIsInGame[2] == 1) {
turnSelector = 2;
whos_turn = Whos_Turn_Array[2];
}
else if (playerIndexIsInGame[3] == 1) {
turnSelector = 3;
whos_turn = Whos_Turn_Array[3];
}
else if (playerIndexIsInGame[4] == 1) {
turnSelector = 4;
whos_turn = Whos_Turn_Array[4];
}
else {
turnSelector = 1;
whos_turn = Whos_Turn_Array[1];
isRoundOne = false;
}
}
else if (turnSelector == 2) {
if (playerIndexIsInGame[3] == 1) {
turnSelector = 3;
whos_turn = Whos_Turn_Array[3];
}
else if (playerIndexIsInGame[4] == 1) {
turnSelector = 4;
whos_turn = Whos_Turn_Array[4];
}
else if (playerIndexIsInGame[1] == 1) {
turnSelector = 1;
whos_turn = Whos_Turn_Array[1];
isRoundOne = false;
}
else {
turnSelector = 2;
whos_turn = Whos_Turn_Array[2];
isRoundOne = false;
}
}
else if (turnSelector == 3) {
if (playerIndexIsInGame[4] == 1) {
turnSelector = 4;
whos_turn = Whos_Turn_Array[4];
}
else if (playerIndexIsInGame[1] == 1) {
turnSelector = 1;
whos_turn = Whos_Turn_Array[1];
isRoundOne = false;
}
else if (playerIndexIsInGame[2] == 1) {
turnSelector = 2;
whos_turn = Whos_Turn_Array[2];
isRoundOne = false;
}
else {
turnSelector = 3;
whos_turn = Whos_Turn_Array[3];
isRoundOne = false;
}
}
else if (turnSelector == 4) {
if (playerIndexIsInGame[1] == 1) {
turnSelector = 1;
whos_turn = Whos_Turn_Array[1];
isRoundOne = false;
}
else if (playerIndexIsInGame[2] == 1) {
turnSelector = 2;
whos_turn = Whos_Turn_Array[2];
isRoundOne = false;
}
else if (playerIndexIsInGame[3] == 1) {
turnSelector = 3;
whos_turn = Whos_Turn_Array[3];
isRoundOne = false;
}
else {
turnSelector = 4;
whos_turn = Whos_Turn_Array[4];
isRoundOne = false;
}
}
}
/********************
* Generate (almost) Random Number
* Need to fix this later
********************/
function randomnumbersx2() private {
uint256 number = uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp, msg.sender)));
bool continueloop1 = true;
bool continueloop2 = true;
while (continueloop1) {
rand1 = uint256(number % 100);
number = number/100;
if ((rand1 >= 1) && (rand1 <=52)) {
continueloop1 = false;
}
}
while (continueloop2 || (rand1 == rand2)) {
rand2 = uint256(number % 100);
number = number/100;
if ((rand2 >= 1) && (rand2 <=52)) {
continueloop2 = false;
}
}
}
function randomnumbersx1() private {
uint256 number = uint256(keccak256(abi.encodePacked(block.difficulty, block.timestamp, msg.sender)));
bool continueloop1 = true;
while (continueloop1 || (rand3 == rand2) || (rand3 == rand2)) {
rand3 = uint256(number % 100);
number = number/100;
if ((rand3 >= 1) && (rand3 <=52)) {
continueloop1 = false;
}
}
}
/********************
* Deal Cards
*
********************/
function Deal_Cards() public {
require(game_started == true, "The game hasn't started yet.");
require(playerIndexToAddress[turnSelector] == msg.sender, "You can only do this on your turn.");
require(cardsDealt == false, "You have already been dealt cards.");
result = Result_Array[0];
randomnumbersx2();
card_one = cards[rand1].cardName;
card_two = cards[rand2].cardName;
card_three = "";
card1rank = cards[rand1].rank;
card2rank = cards[rand2].rank;
cardsDealt = true;
message = Message_Array[2];
if ((card1rank == card2rank) || (card1rank == card2rank +1) || (card1rank + 1 == card2rank)) {
UpdateTurn();
result = Result_Array[4];
}
}
/********************
* Bet
*
********************/
function Bet() public payable {
require(game_started == true, "The game hasn't started yet.");
require(playerIndexToAddress[turnSelector] == msg.sender, "You can only do this on your turn.");
require(cardsDealt == true, "Your cards have not been dealt yet.");
require(msg.value <= pot, "You cannot bet more than what is in the pot.");
if (isRoundOne) {
require(msg.value <= ante_amount, "You cannot bet more than the ante amount during round one.");
}
bool betWon = false;
bool cardoneislow;
if (cards[rand1].rank < cards[rand2].rank) {
cardoneislow = true;
}
if (cards[rand1].rank > cards[rand2].rank) {
cardoneislow = false;
}
randomnumbersx1();
card_three = cards[rand3].cardName;
card3rank = cards[rand3].rank;
if ((playerIndexToAcePref[turnSelector] == 0) && (cards[rand1].rank == 14)) { //aces low
if(cards[rand3].rank < cards[rand2].rank) {
betWon = true;
}
}
if (cardoneislow) {
if ((cards[rand3].rank > cards[rand1].rank) && (cards[rand3].rank < cards[rand2].rank)) {
betWon = true;
}
}
if (!cardoneislow) {
if ((cards[rand3].rank < cards[rand1].rank) && (cards[rand3].rank > cards[rand2].rank)) {
betWon = true;
}
}
if (betWon == true) {
payable(msg.sender).transfer(2*msg.value);
result = Result_Array[1];
}
if (betWon == false) {
result = Result_Array[2];
}
UpdateTurn();
cardsDealt = false;
pot = address(this).balance;
if (address(this).balance <= 0) {
End_Game();
}
}
/********************
* Pass
*
********************/
function Pass() public {
require(game_started == true, "The game hasn't started yet.");
require(playerIndexToAddress[turnSelector] == msg.sender, "You can only do this on your turn.");
result = Result_Array[3];
UpdateTurn();
cardsDealt = false;
}
/********************
* End Game
*
********************/
function End_Game() private {
if (pot > 0) {
//divide the remaining pot equally between addresses in the player array
if (playerIndexIsInGame[1] == 1) {
payable(playerIndexToAddress[1]).transfer(pot/playerCount);
}
if (playerIndexIsInGame[2] == 1) {
payable(playerIndexToAddress[2]).transfer(pot/playerCount);
}
if (playerIndexIsInGame[3] == 1) {
payable(playerIndexToAddress[3]).transfer(pot/playerCount);
}
if (playerIndexIsInGame[4] == 1) {
payable(playerIndexToAddress[4]).transfer(pot/playerCount);
}
payable(msg.sender).transfer(address(this).balance);
}
//reset the game Variables
game_started = false;
turnSelector = 1;
cardsDealt = false;
playerCount = 0;
playerIndexToName = ["","","","",""]; //reset player names
playerIndexToAcePref = [1,1,1,1,1]; //reset first ace prefs, 0 = prefer low, 1 = prefer high
delete playerIndexToAddress[1];
delete playerIndexToAddress[2];
delete playerIndexToAddress[3];
delete playerIndexToAddress[4];
playerIndexIsInGame = [0,0,0,0,0]; //reset player is in the game, 1=ingame, 0=notingane useful for turn selector. using ints so i can add them
playerIndexIsAFK = [0,0,0,0,0]; //reset a player is afk,0=empty position 1=active, 2=afk. using ints so I can add them.
message = Message_Array[0];
whos_turn = Whos_Turn_Array[0];
card_one = "";
card_two = "";
card_three = "";
result = Result_Array[0];
pot = address(this).balance;
}
}
| ******************* Turn Selector/ | function UpdateTurn() private {
cardsDealt = false;
message = Message_Array[1];
if (turnSelector == 1) {
if (playerIndexIsInGame[2] == 1) {
turnSelector = 2;
whos_turn = Whos_Turn_Array[2];
}
else if (playerIndexIsInGame[3] == 1) {
turnSelector = 3;
whos_turn = Whos_Turn_Array[3];
}
else if (playerIndexIsInGame[4] == 1) {
turnSelector = 4;
whos_turn = Whos_Turn_Array[4];
}
else {
turnSelector = 1;
whos_turn = Whos_Turn_Array[1];
isRoundOne = false;
}
}
else if (turnSelector == 2) {
if (playerIndexIsInGame[3] == 1) {
turnSelector = 3;
whos_turn = Whos_Turn_Array[3];
}
else if (playerIndexIsInGame[4] == 1) {
turnSelector = 4;
whos_turn = Whos_Turn_Array[4];
}
else if (playerIndexIsInGame[1] == 1) {
turnSelector = 1;
whos_turn = Whos_Turn_Array[1];
isRoundOne = false;
}
else {
turnSelector = 2;
whos_turn = Whos_Turn_Array[2];
isRoundOne = false;
}
}
else if (turnSelector == 3) {
if (playerIndexIsInGame[4] == 1) {
turnSelector = 4;
whos_turn = Whos_Turn_Array[4];
}
else if (playerIndexIsInGame[1] == 1) {
turnSelector = 1;
whos_turn = Whos_Turn_Array[1];
isRoundOne = false;
}
else if (playerIndexIsInGame[2] == 1) {
turnSelector = 2;
whos_turn = Whos_Turn_Array[2];
isRoundOne = false;
}
else {
turnSelector = 3;
whos_turn = Whos_Turn_Array[3];
isRoundOne = false;
}
}
else if (turnSelector == 4) {
if (playerIndexIsInGame[1] == 1) {
turnSelector = 1;
whos_turn = Whos_Turn_Array[1];
isRoundOne = false;
}
else if (playerIndexIsInGame[2] == 1) {
turnSelector = 2;
whos_turn = Whos_Turn_Array[2];
isRoundOne = false;
}
else if (playerIndexIsInGame[3] == 1) {
turnSelector = 3;
whos_turn = Whos_Turn_Array[3];
isRoundOne = false;
}
else {
turnSelector = 4;
whos_turn = Whos_Turn_Array[4];
isRoundOne = false;
}
}
}
| 12,877,513 | [
1,
15858,
11703,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
445,
2315,
15858,
1435,
3238,
288,
203,
5411,
18122,
758,
2390,
273,
629,
31,
203,
5411,
883,
273,
2350,
67,
1076,
63,
21,
15533,
203,
5411,
309,
261,
20922,
4320,
422,
404,
13,
288,
203,
7734,
309,
261,
14872,
1016,
2520,
382,
12496,
63,
22,
65,
422,
404,
13,
288,
203,
10792,
7005,
4320,
273,
576,
31,
203,
10792,
600,
538,
67,
20922,
273,
3497,
538,
67,
15858,
67,
1076,
63,
22,
15533,
203,
7734,
289,
203,
7734,
469,
309,
261,
14872,
1016,
2520,
382,
12496,
63,
23,
65,
422,
404,
13,
288,
203,
10792,
7005,
4320,
273,
890,
31,
203,
10792,
600,
538,
67,
20922,
273,
3497,
538,
67,
15858,
67,
1076,
63,
23,
15533,
203,
7734,
289,
203,
7734,
469,
309,
261,
14872,
1016,
2520,
382,
12496,
63,
24,
65,
422,
404,
13,
288,
203,
10792,
7005,
4320,
273,
1059,
31,
203,
10792,
600,
538,
67,
20922,
273,
3497,
538,
67,
15858,
67,
1076,
63,
24,
15533,
203,
7734,
289,
203,
7734,
469,
288,
203,
10792,
7005,
4320,
273,
404,
31,
203,
10792,
600,
538,
67,
20922,
273,
3497,
538,
67,
15858,
67,
1076,
63,
21,
15533,
203,
10792,
353,
11066,
3335,
273,
629,
31,
203,
7734,
289,
203,
5411,
289,
203,
5411,
469,
309,
261,
20922,
4320,
422,
576,
13,
288,
203,
7734,
309,
261,
14872,
1016,
2520,
382,
12496,
63,
23,
65,
422,
404,
13,
288,
203,
10792,
7005,
4320,
273,
890,
31,
203,
10792,
600,
538,
67,
20922,
273,
3497,
538,
67,
15858,
67,
1076,
63,
23,
15533,
2
] |
// LC->24.10.2015
tree_scorers ОдушОбъект
tree_scorer ОдушОбъект language=Russian
{
if context { местоим_сущ:кто{} }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоим_сущ:кто-нибудь{} }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоим_сущ:кто-то{} }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоим_сущ:кто-либо{} }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { существительное:*{ одуш:одуш } }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоимение:я{ род:муж } }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { местоимение:я{ род:жен } }
then 1
}
// друзья должны были дождаться нас у леса
// ^^^
tree_scorer ОдушОбъект language=Russian
{
if context { местоимение:я{ лицо:1 } }
then 1
}
// Я дождусь вас
// ^^^
tree_scorer ОдушОбъект language=Russian
{
if context { местоимение:я{ лицо:2 } }
then 1
}
tree_scorer ОдушОбъект language=Russian
{
if context { 'себе' }
then 1
}
tree_scorers НеодушОбъект
tree_scorer НеодушОбъект language=Russian
{
if context { существительное:*{ одуш:неодуш } }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоим_сущ:что-то{} }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоимение:я{ род:ср } }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоим_сущ:что{} }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоим_сущ:что-нибудь{} }
then 1
}
tree_scorer НеодушОбъект language=Russian
{
if context { местоим_сущ:что-либо{} }
then 1
}
// ------------------------------------
/*
function int CheckVerbSubjectConcord( tree v, tree sbj )
{
int res_score=0;
// Для безличных глаголов проверять не надо.
if( eq( wordform_class(v),ГЛАГОЛ) )
then
{
int sbj_number = wordform_get_coord( sbj, ЧИСЛО );
if( eq(sbj_number,-1) )
then
{
// Подлежащим может оказаться часть речи без категории числа.
// У нас есть кое-что общее.
// ^^^^^^^
if( eq( wordform_class( sbj ), МЕСТОИМ_СУЩ ) )
then sbj_number = ЧИСЛО:ЕД;
else if( eq( wordform_class( sbj ), ИНФИНИТИВ ) )
then sbj_number = ЧИСЛО:ЕД;
}
int v_number = wordform_get_coord( v, ЧИСЛО );
// согласование по числу выполняется в любом времени
if( neq( sbj_number, v_number ) )
then res_score=-10; // рассогласование по числу
else
{
int v_tense = wordform_get_coord( v, ВРЕМЯ );
if( eq( v_tense, ВРЕМЯ:ПРОШЕДШЕЕ ) )
then
{
if( eq( v_number, ЧИСЛО:ЕД ) )
then
{
// В прошедшем времени надо сопоставить род.
// Если подлежащее - местоимение Я в первом или втором лице, то род
// проверять не надо:
// А я и не слышала.
// ^^^ ^^^^^^^
if( log_and(
eq( wordform_class(sbj), МЕСТОИМЕНИЕ ),
one_of( wordform_get_coord(sbj,ЛИЦО), ЛИЦО:1, ЛИЦО:2 )
) )
then
{
// nothing to check
}
else
{
int sbj_gender = wordform_get_coord( sbj, РОД );
int v_gender = wordform_get_coord( v, РОД );
if( neq( sbj_gender, v_gender ) )
then res_score=-10; // рассогласование по роду
}
}
}
else
{
// в настоящем и будущем времени надо сопоставить число и лицо
// особый случай - глагол ЕСТЬ (форма глагола БЫТЬ настоящего времени),
// она не имеет признака лица.
int sbj_person = wordform_get_coord( sbj, ЛИЦО );
if( eq( sbj_person, -1 ) )
then sbj_person=ЛИЦО:3;
if( log_not( eqi( wordform_lexem(v), 'есть' ) ) )
then
{
int v_person = wordform_get_coord( v, ЛИЦО );
if( neq( sbj_person, v_person ) )
then res_score=-10; // рассогласование по лицу
}
}
}
}
return res_score;
}
// Обычный предикат с глаголом в личной форме:
// Я буду читать сказку
// ^^^^^^^^^^^^^
//
// Безличная конструкция:
// от этого мне было жаль отказываться
// ^^^ ^^^^ ^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { инфинитив:*{}.{ v=<LEFT_AUX_VERB>глагол:*{} sbj=<SUBJECT>*:*{} } }
then CheckVerbSubjectConcord(v,sbj)
}
// Суд вынес решение
// ^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { v=глагол:*{}.sbj=<SUBJECT>*:*{} }
then CheckVerbSubjectConcord(v,sbj)
}
*/
// ------------------------------------
// В предложении БЕЖАТЬ НА УРОК понижаем достоверность распознавания УРОК как формы слова УРКА,
// предпочитая неодушевленные объекты.
tree_scorer language=Russian
{
if context { rus_verbs:бежать{}.предлог:на{}.ОдушОбъект }
then -1
}
// пойти на урок
// ^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:пойти{}.предлог:на{}.ОдушОбъект }
then -1
}
// Стали слышны крики играющих детей
// ^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:*{}.<OBJECT>существительное:сталь{падеж:дат} }
then -10
}
// давно хотел взять его рабочий телефон.
// --> неодушевленные обычно не хотят
tree_scorer language=Russian { if context { rus_verbs:хотеть{}.<SUBJECT>НеодушОбъект } then -2 }
tree_scorer language=Russian { if context { rus_verbs:захотеть{}.<SUBJECT>НеодушОбъект } then -2 }
//+tree_scorer language=Russian { if context { rus_verbs:перехотеть{}.<SUBJECT>НеодушОбъект } then -2 }
// ------------------------------------------------------
// Чтобы подавить связывание глагола с предложным паттерном в конструкции:
// завтракать яичницей с беконом
// ^^^^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:завтракать{}.предлог:с{}.существительное:*{ одуш:неодуш <в_класс>существительное:еда{} } }
then -10
}
tree_scorer language=Russian
{
if context { существительное:*{ одуш:неодуш <в_класс>существительное:еда{} }
.предлог:с{}.существительное:*{ одуш:неодуш <в_класс>существительное:еда{} падеж:твор }
}
then 2
}
// Обычно ЯВЛЯТЬСЯ можно кому-то, а не чему-то
// Цена является денежным выражением стоимости.
// ^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:являться{}.<OBJECT>существительное:*{ падеж:дат одуш:неодуш } }
then -10
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:явиться{}.<OBJECT>существительное:*{ падеж:дат одуш:неодуш } }
then -10
}
// обрушивать на головы врагов
// ^^^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обрушивать{}.<OBJECT>существительное:*{ одуш:одуш падеж:вин} }
then -10
}
// Мы подали им руку помощи.
// ^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подать{}.<OBJECT>местоимение:я{ падеж:дат } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подать{}.<OBJECT>существительное:*{ одуш:одуш падеж:дат } }
then 2
}
// Белки прячутся в дупле
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:прятаться{}.<SUBJECT>ОдушОбъект }
then 2
}
// им пришлось идти боком.
// ^^ ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:пришлось{}.<SUBJECT>*:*{ падеж:дат } }
then 2
}
// Основным доводом явилось беспокойство за сохранение здоровой экологической обстановки.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:беспокойство{}.предлог:за{}.*:*{падеж:вин} }
then 2
}
// Команды-победительницы в каждой номинации получили сертификаты на спутниковые тарелки.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:сертификат{}.предлог:на{}.*:*{падеж:вин} }
then 2
}
// Поводом для раскрытия банковской тайны могут стать подозрения в нарушении налогового законодательства
// ^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:повод{}.предлог:для{} }
then 2
}
// - Вы знали, что перевоплощаться в существа другого биологического вида запрещено сроком на шесть месяцев?
// ^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:срок{падеж:твор}.предлог:на{} }
then 5
}
// различные страны продолжают осуществлять политику по укреплению своих позиций на Южном Кавказе
// ^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:политика{}.предлог:по{} }
then 2
}
// Она не могла оторвать взгляда от их грубой подошвы и толстых ниток, прошивающих ботинки по краям.
// ^^^^^^^^ ^^...
tree_scorer language=Russian
{
if context { rus_verbs:оторвать{}.предлог:от{} }
then 2
}
// Предварительное расследование пока исключает вмешательство членов экипажа в работу системы пожаротушения.
tree_scorer language=Russian
{
if context { существительное:вмешательство{}.предлог:в{}.*:*{падеж:вин} }
then 2
}
// Европейский союз готов присоединиться к украинско-российским переговорам по пересмотру цены на газ
// ^^^^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:переговоры{}.предлог:по{}.*:*{падеж:дат} }
then 2
}
// Ведь и в Мадриде, и в Барселоне начиналось именно с шумихи вокруг их гастрольной поездки...
// ^^^^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:шумиха{}.предлог:вокруг{} }
then 2
}
// проводили мероприятие по выявлению лиц , занимающихся изготовлением контрафактных лекарств
// ^^^^^^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:мероприятие{}.предлог:по{}.*:*{падеж:дат} }
then 2
}
// Ведь не была же она настолько наивна, чтобы верить во всю эту чушь насчет надежной мужской руки
// ^^^^^^^^^^^...
tree_scorer language=Russian
{
if context { существительное:чушь{}.предлог:насчет{} }
then 2
}
// Они занимались распространением наркотиков среди посетителей этого увеселительного заведения.
// ^^^^^^^^^^^^^^^^ ^^^^^
tree_scorer language=Russian
{
if context { существительное:распространение{}.предлог:среди{}.*:*{падеж:род} }
then 2
}
// Этот фильм посвящен попытке человека освободиться от своего прошлого, начать новую жизнь
// ^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:освободиться{}.предлог:от{}.*:*{падеж:род} }
then 2
}
// старик прав : все имеет свою цену.
// ^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:правый{ краткий число:ед род:муж }.<SUBJECT>*:*{ падеж:им род:муж число:ед } }
then 2
}
// тем временем надо приготовить лодки.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приготовить{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Мы выбрали его секретарём нашей организации.
// ^^^^^^^ ^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выбрать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>существительное:*{ падеж:твор }
} }
then 3
}
// При жизни его не ценили.
// ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ценить{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// разгрести в задачах залежи
// ^^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разгрести{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 2
}
// император осторожно коснулся пальцами белой перчатки.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:коснуться{}.{
<OBJECT>*:*{ падеж:твор }
<OBJECT>*:*{ падеж:род }
} }
then 4
}
// именно поэтому она собиралась предложить им очень простой выбор.
// ^^^^^^^^^^ ^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:предложить{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:вин }
} }
then 1
}
// девушка смутно ощущала тепло.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ощущать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Томас внимательно рассматривал дома.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рассматривать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Ричард обвел глазами окрестности.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обвести{}.{
<OBJECT>*:*{ падеж:твор }
<OBJECT>*:*{ падеж:вин }
} }
then 4
}
// император осторожно коснулся пальцами белой перчатки.
// ^^^^^^^^ ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:коснуться{}.*:*{ падеж:род } }
then 1
}
// собирать щеткой крошки со стола
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:собирать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Глагол ТРУБИТЬ обычно не присоединяет одушевленное прямое дополнение:
// трубить о поимке разбойников
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:трубить{}.<OBJECT>*:*{ одуш:одуш } }
then -10
}
// Глагол СЛАГАТЬ обычно не присоединяет одушевленное прямое дополнение:
// слагать о подвигах викингов
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:слагать{}.<OBJECT>*:*{ одуш:одуш } }
then -10
}
// семья арендовала домик у владельца
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:арендовать{}.предлог:у{}.*:*{ падеж:род одуш:одуш } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:арендовать{}.предлог:у{}.местоимение:*{ падеж:род } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:арендовать{}.предлог:у{}.местоим_сущ:*{ падеж:род } }
then 2
}
// укрыться от маньяка в доме
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:укрыться{}.предлог:в{}.*:*{ падеж:предл } }
then 2
}
// уединяться с подругой в доме
// ^^^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:уединяться{}.предлог:в{}.*:*{ падеж:предл } }
then 2
}
// Дни стали короче.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стать{}.прилагательное:*{ степень:сравн } }
then 2
}
// Чтобы устранить вариант с творительным падежом:
// причинить животным страдания
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинить{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
} }
then 4
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинять{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
} }
then 4
}
// запах реки сделался сильнее.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сделаться{}.прилагательное:*{ степень:сравн } }
then 2
}
// У вас есть чистый лист бумаги и конверт?
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{ время:настоящее }.предлог:у{}.*:*{ падеж:род } }
then 2
}
// знакомая опасность казалась страшнее.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:казаться{}.прилагательное:*{ степень:сравн } }
then 2
}
// день будет становиться короче и немного тоскливее
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:становиться{}.прилагательное:*{ степень:сравн } }
then 2
}
// Снимаем омонимию кратких форм ЗАМЕТНЫЙ-ЗАМЕТЕННЫЙ:
// Юпитер заметен невооруженным взглядом
// ^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:заметный{}.<OBJECT>'взглядом' }
then 2
}
/*
// Студентка села за стол и начала читать журнал.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:начать{}.инфинитив:*{ вид:несоверш } }
then 2
}
*/
// Село должно отпраздновать окончание страды
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:должный{ КРАТКИЙ }.инфинитив:*{} }
then 2
}
// ПОРА с инфинитивом обычно является безличным глаголом:
// пора учиться мыслить шире.
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:пора{}.инфинитив:*{} }
then 2
}
// Быть сильным в чем-то неодушевленном:
// Он не силён в математике.
// ^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:сильный{КРАТКИЙ}.'в'.существительное:*{ одуш:неодуш } }
then 2
}
// дождаться сладкого
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дождаться{}.<OBJECT>НеодушОбъект{ падеж:род } }
then 2
}
// ---------------------------------------------------------------------------
// Дать+местоимение - обычно местоимение в дательном падеже:
// Я не дам им ничего
// ^^^^^^
// просто они дали выход злости.
// ^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:дать{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } }
then 5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:дать{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>*:*{ падеж:дат } } }
then 5
}
// Артиллерии дам много.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.{ <OBJECT>*:*{ ПАДЕЖ:РОД } наречие:много{} } }
then 6
}
// ---------------------------------------------------------------------------
// Подавим вариант с Генри/твор.п./
// Генри уловил кусочек фразы.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:уловить{}.<OBJECT>*:*{ одуш:одуш падеж:твор } }
then -5
}
// высокие колеса подняли тучи пыли.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поднять{}.<OBJECT>существительное:туча{ падеж:вин }.'пыли' }
then 3
}
// причинить животным страдания
// ^^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинить{}.<OBJECT>'страдания'{ падеж:вин } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинять{}.<OBJECT>'страдания'{ падеж:вин } }
then 2
}
// Зачерпывать пюре большой ложкой
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:зачерпывать{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// причинить животным страдания
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинять{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:причинять{}.<OBJECT>существительное:*{ одуш:одуш падеж:дат } }
then 1
}
// ТРЕБОВАТЬ обычно присоединяет неодушевленные в родительном падеже:
// наша честь требует свободы.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:требовать{}.<OBJECT>существительное:*{ одуш:неодуш падеж:род } }
then 1
}
// Предпочтительно такое связывание, чтобы подлежащее для ПРИВЫКНУТЬ было обушевленным,
// либо было прямое дополнение в виде неодуш. объекта
// мечом привык решать любой спор.
// ^^^^^^ ^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:привыкнуть{}.<SUBJECT>существительное:*{ одуш:неодуш } }
then -2
}
// всем нужно спать на мягкой кровати
// ^^^^^^^^^^
tree_scorer language=Russian
{
if context { 'нужно'.'всем'{ падеж:дат } }
then 1
}
// Для модального глагола, к которому прикреплен инфинитив, нежелательно
// прикреплять еще и прямое дополнение:
//
// хочу все это понять
// ^^^^ ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:хотеть{}.{
<INFINITIVE>*:*{}
<OBJECT>*:*{} } }
then -1
}
// чрезвычайная эмоциональная живость и легкомысленность партнера может меня обижать
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обижать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// происходящее теряет всякое значение.
// ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:терять{}.<OBJECT>существительное:значение{ падеж:вин } }
then 2
}
// пытаюсь не уснуть, выпивая много крепкого кофе, и заедая его шоколадом
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заедать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
} }
then 2
}
// Чтобы подавить распознавание БЫЛИ как существительного:
//
// Обвиняемые были освобождены в зале суда
// ^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { 'были'{ class:глагол }.{
<SUBJECT>прилагательное:*{ число:мн }
<RHEMA>прилагательное:*{ краткий страд число:мн }
} }
then 1
}
// кот спит и видит мышей во сне
// ^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// Одушевленные субъекты обычно СПЯТ, а не СПАДАЮТ
// кенгуру, свернувшись клубком, спал
// ^^^^^^^ ^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:спать{}.<SUBJECT>существительное:*{ одуш:одуш падеж:им } }
then 1
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:спасть{}.<SUBJECT>существительное:*{ одуш:одуш падеж:им } }
then -4
}
// ГРЕТЬ ожидает прямое дополнение в вин.п.:
// Я хочу попить чаю, греющего душу
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:греть{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// Кошки пили сливки несколько дней подряд
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пить{}.<OBJECT>существительное:*{ падеж:вин <в_класс>существительное:напиток{} } }
then 1
}
// Глагол БЫТЬ предпочинает паттер В+сущ в предл. падеже, а не в винительном:
// машина была в пути
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:быть{}.предлог:в{}.*:*{ падеж:предл } }
then 1
}
// настоящий смех приносит облегчение.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приносить{}.<OBJECT>существительное:облегчение{падеж:вин} }
then 2
}
// дважды раздался пронзительный свист.
// ^^^^^^^^ ^^^^^
wordentry_set То_Что_Раздается_Как_Звук=существительное:{
шум, свист, стук, звук, сигнал, рев, крик, бормотание, слово, фраза, гул, хохот, плач,
визг, хор, треск, смех, скрип, вопль, звон, выстрел
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:раздаться{}.<SUBJECT>То_Что_Раздается_Как_Звук }
then 1
}
// Обычно одушевленный субъект чешет неодушевленный предмет:
//
// Гарри почесал кончик носа.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:почесать{}.{
<SUBJECT>существительное:*{ падеж:им одуш:одуш }
<OBJECT>существительное:*{ падеж:вин одуш:неодуш }
} }
then 1
}
// цветок придал девушке уверенности.
// ^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придать{}.<OBJECT>существительное:*{ одуш:неодуш падеж:род } }
then 1
}
// глухой рев наполнил окрестности.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:наполнить{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// неторопливо допил прохладный сок.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:допить{}.<OBJECT>существительное:*{ одуш:неодуш падеж:вин <в_класс>существительное:напиток{} } }
then 1
}
/*
// Мы помогли ему влезть в лодку.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помочь{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
} }
then 5
}
*/
/*
// Разрешите вас пригласить?
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пригласить{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
*/
// неторопливо допил прохладный сок.
// ^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:допить{}.<OBJECT>существительное:*{ падеж:вин одуш:неодуш <в_класс>существительное:напиток{} } }
then 1
}
// Он научил меня играть в шахматы.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:научить{}.{
<OBJECT>*:*{ падеж:вин }
инфинитив:*{}
} }
then 5
}
// Миша допил чай
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:допить{}.существительное:*{ падеж:вин одуш:неодуш } }
then 1
}
// Миша выпил чай
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выпить{}.существительное:*{ падеж:вин одуш:неодуш } }
then 1
}
// Он смотрит на вещи просто.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.предлог:на{}.существительное:*{ падеж:вин } }
then 1
}
// Оставь книгу у Лены.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оставить{}.предлог:у{}.существительное:*{ одуш:одуш } }
then 1
}
// кенгуру наловил детенышам мышей своими лапами
// ^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:наловить{}.<OBJECT>*:*{ падеж:род } }
then 1
}
// Автор воскресил героя из небытия
// ^^^^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:воскресить{}.предлог:из{}.'небытия' }
then 1
}
// Коля вызвался помочь с математикой
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помочь{}.предлог:с{}.существительное:*{ одуш:неодуш } }
then 1
}
// Поищите это слово в словаре.
// ^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поискать{}.предлог:в{}.существительное:*{ одуш:неодуш падеж:предл } }
then 1
}
// Всё это нашло отражение в его книге.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>существительное:отражение{}.предлог:в{} }
then 3
}
// Я никого не встретил
// ^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { глагол:*{}.{ <NEGATION_PARTICLE>'не' 'никого'{падеж:вин} } }
then 1
}
// Никого не встретить
tree_scorer language=Russian
{
if context { инфинитив:*{}.{ <NEGATION_PARTICLE>'не' 'никого'{падеж:вин} } }
then 1
}
// Он никого не видел там кроме неё.
// ^^^^^^ ^^ ^^^^^
tree_scorer language=Russian
{
if context { глагол:*{}.{ <NEGATION_PARTICLE>'не' 'никого'{падеж:вин} } }
then 1
}
// напасть на спящих
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:напасть{}.предлог:на{}.*:*{ падеж:вин } }
then 1
}
// Мы с Мишей читали сказку
tree_scorer language=Russian
{
if context { местоимение:я{}.предлог:с{}.существительное:*{ падеж:твор одуш:одуш } }
then 1
}
// Мы с ней сидели за одной партой.
// ^^^^^^^^
tree_scorer language=Russian
{
if context { местоимение:я{}.предлог:с{}.местоимение:я{ падеж:твор } }
then 1
}
// Мы с ним были на концерте.
tree_scorer language=Russian
{
if context { местоимение:я{}.предлог:с{}.'ним'{ род:муж } }
then 1
}
// Аллах сотворил всякое животное из воды.
// ^^^^^^^^ ^^^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:сотворить{}.предлог:из{} }
then 2
}
// Аллегра не сводила глаз с мужа.
// ^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:сводить{}.{ <OBJECT>"глаз"{число:мн} предлог:с{}.*{падеж:твор} } }
then 2
}
// А вы были помолвлены с Лиллианой.
// ^^^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:помолвленный{}.предлог:с{}.*{падеж:твор} }
then 2
}
// А ты с ним плохо обращаешься?
// ^^^^^ ^^^^^^^^^^^
tree_scorer language=Russian
{
if context { rus_verbs:обращаться{}.предлог:с{}.*{падеж:твор} }
then 2
}
// Он относится к бедному товарищу с горячим участием.
// ^^^^^^^^^ ^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { глагол:*{}.'с'.'участием' }
then 1
}
tree_scorer language=Russian
{
if context { инфинитив:*{}.'с'.'участием' }
then 1
}
tree_scorer language=Russian
{
if context { деепричастие:*{}.'с'.'участием' }
then 1
}
tree_scorer language=Russian
{
if context { прилагательное:*{ причастие }.'с'.'участием' }
then 1
}
// Она оправдала неявку на занятия болезнью.
// ^^^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оправдать{}.<OBJECT>*{ падеж:твор } }
then 1
}
// жаждать мести
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:жаждать{}.<OBJECT>'мести'{ падеж:род } }
then 1
}
// Он доводится мальчику дядей
// ^^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:доводиться{}.<OBJECT>*:*{ падеж:твор } }
then 1
}
// принести в дом бездомного щенка
// ^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:принести{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// всадить пулю в сердце
// ^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:всадить{}.предлог:в{}.существительное:*{ падеж:вин } }
then 1
}
// Усиленная работа отразилась на его здоровье.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отразиться{}.предлог:на{}.существительное:здоровье{ падеж:предл } }
then 1
}
#define PreferAccusObject(v) \
#begin
tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:v{}.<OBJECT>*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:v{}.<OBJECT>*:*{ падеж:вин } } then 1 }
#end
// Поэты воспели в этой оде героев
PreferAccusObject(воспеть)
// встретить в классе старого приятеля (встретить+вин.п.)
PreferAccusObject(встретить)
// встречать в лесу голодного медведя (встречать+вин.п.)
PreferAccusObject(встречать)
// выписать из деревни нового скакуна
PreferAccusObject(выписать)
// регулярная армия вытесняет из пригородов повстанцев
PreferAccusObject(вытеснять)
// выводить с одежды пятна (вводить + вин.п.)
PreferAccusObject(выводить)
// выжать максимум из машины (выжать + вин.п.)
PreferAccusObject(выжать)
// собраться в аудитории
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:собраться{}.предлог:в{}.существительное:*{ одуш:неодуш падеж:предл <в_класс>существительное:помещение{} } }
then 1
}
// Глагол БОЯТЬСЯ обычно используется с прямым дополнением, причем одушевленное
// дополнение стоит в винительном падеже, а неодушевленное - в родительном.
// они должны научиться бояться нас.
// ^^^^^^^^^^^
// Дело мастера боится.
// ^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бояться{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бояться{}.<OBJECT>НеодушОбъект{ падеж:род } }
then 1
}
// сказал Холмс, снимая крышку с курицы
// ^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:снимать{}.предлог:с{}.*:*{ падеж:род } }
then 2
}
// Я послал книги по почте.
// ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:послать{}.предлог:по{}.'почте' }
then 2
}
// Он разложил книги по всему столу.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разложить{}.предлог:по{}.существительное:*{} }
then 1
}
// Мы покормили белок.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:покормить{}.существительное:*{ падеж:вин одуш:одуш } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:покормить{}.существительное:*{ падеж:вин одуш:одуш } }
then 2
}
// писатель пишет повести
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:писать{ aux stress="пис^ать" }.существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// Резкий порывистый ветер валит прохожих с ног.
// ^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:валить{}.предлог:с{}.'ног' }
then 1
}
// Резкий порывистый ветер свалит тебя с ног.
// ^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:свалить{}.предлог:с{}.'ног' }
then 1
}
// блоггер, написавший про детский приют
tree_scorer language=Russian
{
if context { прилагательное:написавший{ aux stress="напис^авший" }.предлог:про{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:написать{ aux stress="напис^ать" }.предлог:про{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:написать{ aux stress="напис^ать" }.предлог:про{} }
then 1
}
// Учительница ищет в карманах шпаргалки
// ^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искать{}.существительное:*{ падеж:вин } }
then 1
}
// заметившими косулю медведицами
// ^^^^^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заметить{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then -2
}
// стирать белье в реке
// ^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стирать{}.предлог:в{}.существительное:*{ одуш:неодуш падеж:предл } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:купить{}.предлог:у{}.существительное:*{ одуш:одуш } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:купить{}.предлог:у{}.местоимение:*{} }
then 2
}
// стирать прошлое из памяти
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стирать{}.предлог:из{}.существительное:память{} }
then 1
}
// Боль исказила его лицо.
// ^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:исказить{}.<OBJECT>существительное:лицо{ одуш:неодуш } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искажать{}.<OBJECT>существительное:лицо{ одуш:неодуш } }
then 1
}
// Подавим по возможности связывание глагола ЕСТЬ с предложным дополнением ИЗ
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:есть{}.предлог:из{}.существительное:*{ <в_класс>существительное:овощ{} } }
then -1
}
// Винительное дополнение:
// считать деньги
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:считать{}.*:*{падеж:вин} }
then 1
}
// Мы согласовали наши законы с беларусским законодательством
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:согласовать{ вид:соверш }.предлог:с{} }
then 1
}
// Я иду в кино.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:идти{}.{
'в'.'кино'{ падеж:вин }
<SUBJECT>местоимение:*{}
} }
then 1
}
// Он купил игрушки для детей.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:купить{}.*:*{ падеж:вин } }
then 1
}
// Он занял деньги под большие проценты.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:занять{}.'деньги'{ падеж:вин } }
then 1
}
// его осторожность взяла верх над его жадностью
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:взять{}.существительное:верх{}.предлог:над{} }
then 1
}
// Студенты долго ломали голову над задачей.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ломать{}.{
'голову'
предлог:над{} } }
then 1
}
// Я не хотел вас обидеть.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обидеть{}.*:*{ падеж:вин } }
then 2
}
// Я нашёл толк в этом деле.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.{
'толк'
предлог:в{}.существительное:*:*{ падеж:предл }
} }
then 1
}
// Я всюду искал письмо, но нигде не мог его найти.
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.*:*{ падеж:вин } }
then 2
}
// Я вовсе не хотел её оскорбить.
// ^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оскорбить{}.*:*{ падеж:вин } }
then 2
}
// Мы перебили врагов в бою.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:перебить{}.'в'.'бою' }
then 1
}
// Этот мотор делает 600 оборотов в минуту.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:делать{}.существительное:оборот{}.num_word:*{} }
then 3
}
// для ВЫУЧИТЬ желательно дополнение в винительном падеже
// Он выучил меня играть в шахматы.
// ^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выучить{}.*:*{ падеж:вин } }
then 2
}
// Будем считать, что ЭТО в роли подлежащего имеет приоритет:
// Это внесло разнообразие в мою жизнь.
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:*{ время:прошедшее число:ед род:ср }.<SUBJECT>'это' }
then 1
}
// Я принёс эту книгу для вас.
// ^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:принести{}.предлог:для{}.местоимение:*{} }
then 1
}
// Глагол ИЗБРАТЬ обычно требует прямое дополнение в винительном падеже:
// Академия наук избрала его почётным членом.
// ^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:избрать{}.*:*{ падеж:вин } }
then 1
}
// Глагол ПРИСЫЛАТЬ обычно требует прямое дополнение
// Он присылал к должнику своих головорезов
// ^^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:присылать{}.<OBJECT>существительное:*{ падеж:вин } }
then 1
}
// Я никого не встретил
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.{ частица:не{} 'никого'{ падеж:род } } }
then 1
}
// они затопили корабли в гавани
// ^^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:затопить{}.предлог:в{}.*:*{ падеж:предл } }
then 1
}
// Составьте предложение из этих слов.
// ^^^^^^^^^ ^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:составить{}.предлог:из{}.существительное:*{ одуш:неодуш падеж:род } }
then 1
}
// Согрейте руки у огня.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:согреть{}.предлог:у{}.существительное:*{ одуш:неодуш падеж:род } }
then 1
}
// Не оставь товарища в опасности.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оставить{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// Я принёс книгу с собой.
tree_scorer ВалентностьГлагола language=Russian
{
if context { Гл_С_Твор.'с'.'собой' }
then 1
}
// Наш пароход держал курс прямо на север.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:держать{}.<OBJECT>существительное:курс{ падеж:вин } }
then 1
}
// Антонио ни с кем не говорил
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.{
'не'
'с'.{ 'ни' 'кем' }
} }
then 1
}
// Я был знаком с вашим дядей.
// ^^^^^^^^
tree_scorer language=Russian
{
if context { 'был'.{ прилагательное:знакомый{ краткий } предлог:с{}.существительное:*{ одуш:одуш } } }
then 3
}
tree_scorer language=Russian
{
if context { 'был'.{ прилагательное:знакомый{ краткий } предлог:с{}.местоимение:*{} } }
then 3
}
// Подавим родительную валентность для местоимения.
// Вас требует заведующий.
// ^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ ПАДЕЖ:ВИН }.<OBJECT>'вас'{падеж:вин} }
then 1
}
// Я научил его английскому языку.
// ^^^^^^ ^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:научить{}.{ <OBJECT>местоимение:я{падеж:вин} <OBJECT>*:*{падеж:дат} } }
then 1
}
// Я учу его английскому языку.
// ^^^ ^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:учить{}.{ <OBJECT>местоимение:я{падеж:вин} <OBJECT>*:*{падеж:дат} } }
then 1
}
// Я велел ему прийти через час.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:велеть{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } }
then 1
}
// Дождь помешал нам прийти.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помешать{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } }
then 1
}
// Ведь вы сами посоветовали мне так сделать.
// ^^^^^^^^^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:посоветовать{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } }
then 1
}
// Антонио разрешил нам рассказать об этом
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разрешить{}.{ <OBJECT>местоимение:я{ падеж:дат } инфинитив:*{} } }
then 1
}
// кенгуру наловил детенышам мышей своими лапами
// ^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:наловить{}.<OBJECT>*:*{ падеж:род } }
then 1
}
// Характер писателя лучше всего выражается в его произведениях.
// ^^^^^^^^^^^
tree_scorer language=Russian
{
if context { наречие:всего{}.'лучше'{ class:наречие } }
then 1
}
// Этот город находится к западу от Москвы.
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:находиться{ вид:несоверш }.<SUBJECT>существительное:*{} }
then 1
}
// Он находится в весьма неприятном положении.
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:находиться{ вид:несоверш }.предлог:*{} }
then 1
}
// Подавим родительный падеж:
// Прошу вас.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:просить{}.местоимение:я{ падеж:вин } }
then 1
}
// Природа наградила его разнообразными способностями.
// ^^^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:наградить{}.местоимение:я{ падеж:вин } }
then 1
}
// Природа одарила его прекрасными способностями.
// ^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:одарить{}.местоимение:я{ падеж:вин } }
then 1
}
// Предпочтём винительный падеж местоимения, а не родительный.
// Вас спрашивает какой-то человек.
// ^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:спрашивать{}.'вас'{падеж:вин} }
then 1
}
// Примите мой искренний привет!
// ^^^^^^^ ^
tree_scorer language=Russian
{
if context { 'примите'{ наклонение:побуд }.'!' }
then 1
}
// Напишите фамилию полностью.
// ^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:написать{aux stress="напис^ать"}.наречие:полностью{} }
then 1
}
// Она обозвала его дураком.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обозвать{}.{
*:*{ падеж:вин }
*:*{ падеж:твор }
} }
then 1
}
// Понизим достоверность распознавания УРКА:
// Девочка вообще не пошла на урок
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пойти{}.предлог:на{}.'урок'{ одуш:неодуш } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:идти{}.предлог:на{}.'урок'{ одуш:неодуш } }
then 1
}
// Выбираем винительный падеж:
// Время работает на нас.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:работать{}.'на'.'нас'{падеж:вин} }
then 1
}
// Мы пришли к заключению, что он прав.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придти{}.'к'.'заключению' }
then 1
}
/*
tree_scorer language=Russian
{
if context { 'два'{ class:числительное род:муж }.существительное:*{род:жен} }
then -1
}
tree_scorer language=Russian
{
if context { 'два'{ class:числительное род:муж }.существительное:*{род:ср} }
then -1
}
tree_scorer language=Russian
{
if context { 'два'{ class:числительное род:ср }.существительное:*{род:муж} }
then -1
}
tree_scorer language=Russian
{
if context { 'два'{ class:числительное род:ср }.существительное:*{род:жен} }
then -1
}
tree_scorer language=Russian
{
if context { числительное:два{род:жен}.существительное:*{род:жен} }
then 1
}
tree_scorer language=Russian
{
if context { числительное:два{род:ср}.существительное:*{род:ср} }
then 1
}
*/
// Уберем вариант СТАТЬ для:
//
// Он написал статью на русском языке.
// ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:написать{ aux stress="напис^ать" }.<OBJECT>'статью'{ падеж:вин } }
then 1
}
// Антонио подарил ведьмёнышам пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подарить{}.{
<OBJECT>существительное:*{ падеж:вин одуш:неодуш }
<OBJECT>существительное:*{ падеж:дат одуш:одуш }
} }
then 1
}
// Дайте мне хлеба.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.<OBJECT>существительное:хлеб{ падеж:вин } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.<OBJECT>существительное:хлеб{ падеж:род } }
then 1
}
/*
wordentry_set НаречВремСуток=наречие:{ утром, вечером, днем, ночью }
// она вечером будет есть пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.{
НаречВремСуток
инфинитив:*{}
} }
then 1
}
*/
// Глаголы с семантикой поедания, присоединяющие прямое дополнение в вин. падеже
wordentry_set ГлаголыПоедания_Вин=
{
глагол:есть{}, инфинитив:есть{}
}
// Антонио ест пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<OBJECT>'пюре'{падеж:вин} }
then 1
}
/*
// она утром будет есть пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:утром{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.'утром'{ class:существительное } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.'днем'{ class:существительное } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.'вечером'{ class:существительное } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.'ночью'{ class:существительное } }
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:днем{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:вечером{} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ГлаголыПоедания_Вин.<ATTRIBUTE>наречие:ночью{} }
then 1
}
*/
// желая стать космонавтом
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стать{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then 1
}
// Царя над окрестностями
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:царить{}.'над'.'окрестностями' }
then 1
}
// Планета Юпитер не видна днём
// ^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:видный{ краткий }.<ATTRIBUTE>'днем'{} }
then 1
}
// Подавим распознавание ПОТОМ как существительного:
// вы едите пюре или суп, потом пьете чай
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.<OBJECT>'потом'{падеж:твор} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.<OBJECT>'потом'{падеж:твор} }
then -100
}
// Для глагола ЛОВИТЬ подавляем прямое дополнение в творительном падеже, если
// оно соответствует одушевленному:
// Антонио опять ловит мышь несколько ночей подряд
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ловить{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then -1
}
// продавать книги
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:продавать{}.<OBJECT>существительное:*{ падеж:вин } }
then 1
}
// мы не увидели тебя
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:увидеть{}.<OBJECT>местоимение:*{ падеж:вин } }
then 1
}
// Винительная валентность глагола ГОВОРИТЬ используется
// только с неодушевленным дополнением.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:говорить{}.<OBJECT>*{ падеж:вин } }
then -1
}
// кот не видит ее
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.<OBJECT>местоимение:я{ падеж:вин } }
then 1
}
// кот увидел кенгуру на полу
// ^^^^^^ ^^^^^^^
// Подавим вариант творительного падежа для любых дополнение, за исключением ГЛАЗ
// а неодушевленные пусть будут "увидел своими глазами"
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:увидеть{}.<OBJECT>существительное:глаз{ падеж:твор } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.<OBJECT>существительное:глаз{ падеж:твор } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:увидеть{}.<OBJECT>существительное:*{ падеж:твор } }
then -1
}
// Дмитрий Иванович Менделеев увидел периодическую таблицу элементов во сне
// ^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:увидеть{}.'во'.'сне' }
then 1
}
// аналогично для:
// кот видит кенгуру на полу
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.<OBJECT>существительное:*{ падеж:твор } }
then -1
}
// Для глагола ВСТРЕТИТЬ подавим прямое дополнение в творительном падеже, если
// оно - одушевленный объект:
// ведьмёныш встретил Антонио
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:встретить{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then -1
}
// Аналогично: ведьмёныш встречал Антонио веселым криком
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:встречать{}.<OBJECT>существительное:*{ падеж:твор одуш:одуш } }
then -1
}
wordentry_set ЧтоМожноДелатьСЧаем=
{
инфинитив:налить{},
глагол:налить{}
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { ЧтоМожноДелатьСЧаем.<OBJECT>'чаю'{падеж:парт} }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:ловить{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// мыть руки с мылом
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:мыть{}.'с'.'мылом' }
then 1
}
// Я мою руки с мылом
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:мыть{}.'с'.'мылом' }
then 1
}
// кошки собираются ловить хозяину в амбаре мышь
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:ловить{}.'в'.'амбаре' }
then 1
}
// Мы боремся все доступными средствами с ошибками в программе
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:бороться{}.'с'.'ошибками' }
then 1
}
// большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:высадиться{}.'для'.'поиска' }
then 1
}
// стипендия студента университета дружбы народов, живших в союзных республиках бывшего СССР
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:живший{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// студенты университета, построенного в СССР
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:построенный{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// группа студентов университета дружбы народов, основанного в СССР
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:основанный{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
// группа студентов университета дружбы народов, активно пропагандировавшейся в СССР
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:пропагандировавшийся{}.предлог:в{}.существительное:*{ падеж:предл } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { 'сыплет'{class:глагол}.<SUBJECT>существительное:дождь{ падеж:им } }
then 1
}
tree_scorer language=Russian
{
if context { безлич_глагол:стало{}.'всем'{ class:прилагательное падеж:дат} }
then 1
}
// давай-ка выпей молока
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:выпить{}.'молока'{class:существительное} }
then 1
}
// лежащий на полу
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:лежащий{}.предлог:на{}.'полу'{падеж:мест} }
then 1
}
// Подавим распознавание ДНЁМ как существительного в творительном падеже.
//
// кошки днем обычно ели и дремали
// ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:есть{}.<OBJECT>существительное:день{ падеж:твор } }
then -1
}
// Несмотря на появляющуюся родительную валентность в отрицательной форме глагола,
// местоимения её и его надо брать только в аккузативе.
// она её не съест
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:съесть{}.'ее'{ падеж:вин } }
then 1
}
/*
// Планета Марс видна утром
tree_scorer language=Russian
{
if context { прилагательное:видный{}.наречие:утром{} }
then 1
}
*/
/*
// Повысим достоверность безличного глагола.
//
// Грести стало труднее
// ^^^^^
tree_scorer language=Russian
{
if context { 'стало'{class:безлич_глагол} }
then 1
}
*/
// Для глагола КУПИТЬ надо подавлять связывание с прямым дополнением в родительным падеже
// для живых существ.
// Ну же, купите слона!
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:купить{}.<OBJECT>существительное:*{ ОДУШ:ОДУШ падеж:род } }
then -1
}
// купи кефиру
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:купить{}.<OBJECT>существительное:*{ ОДУШ:НЕОДУШ падеж:парт } }
then 4
}
// налей мне воды
// ^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:налить{}.<OBJECT>'воды'{ падеж:род } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:лежать{}.'в'.'углу' }
then 1
}
// ОСВЕТИТЬ можно обычно КОМУ-ТО, а не чему-то:
// отблеск молнии осветил часового.
// ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:осветить{}.существительное:*{ падеж:дат одуш:неодуш } }
then -10
}
// Он ездит на работу на автобусе.
// ^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ездить{}.предлог:на{}.существительное:*{ падеж:предл одуш:неодуш <в_класс>существительное:транспорт{} } }
then 2
}
// Его успех доставил ей радость.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:доставить{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 2
}
/*
// Предотвращаем отрыв слова ЭТОТ, ЭТОЙ и т.д. от существительного.
// Роберт улыбнулся этой мысли.
// ^^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:*{}.<ATTRIBUTE>прилагательное:этот{} }
then 2
}
*/
// Речки разлились и дороги стали непроходимы.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:стать{}.прилагательное:*{ краткий } }
then 1
}
// укрыться от дождя под навесом
// ^^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:укрыться{}.предлог:под{}.НеодушОбъект }
then 2
}
// Мул - помесь осла и лошади.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { существительное:помесь{}.существительное:*{}.союз:и{} }
then 1
}
// Олег обвел взглядом окрестности.
// ^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обвести{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// Олег хмуро окинул взглядом убитого.
// ^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:окинуть{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// мои предки построили его собственными руками.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:построить{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 5
}
// иначе им грозит беда.
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:грозить{}.<OBJECT>*:*{ падеж:дат } }
then 1
}
// Джим поискал глазами своего коня.
// ^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поискать{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then 1
}
// вера дает им силу.
// ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:давать{}.<OBJECT>*:*{ падеж:дат } }
then 1
}
// им дорого обойдется сегодняшний бой.
// ^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обойтись{}.<OBJECT>*:*{ падеж:дат } }
then 1
}
// киммериец молча пожал ей руку.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожать{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 1
}
// ей ответил пронзительный яростный визг.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ответить{2}.<OBJECT>местоимение:я{ 1 падеж:дат } }
then 1
}
// Он ответил Джо
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ответить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } }
then 2
}
// зачем давать им пустую надежду.
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожать{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 2
}
// тебе следовало оставить ей записку.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оставить{}.{ <OBJECT>ОдушОбъект{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 2
}
// маленький желтый череп улыбнулся ей.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:улыбнуться{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } }
then 2
}
// Томас швырнул ей птицу.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:швырнуть{1}.{ <OBJECT>ОдушОбъект{ 2 падеж:дат } <OBJECT>*:*{ падеж:вин } } }
then 2
}
// дом чрезвычайно понравился ей.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:понравиться{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// меч им явно нравился.
// ^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:нравиться{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// некоторым действительно нравится моя работа.
// ^^^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:нравиться{}.<OBJECT>прилагательное:*{ падеж:дат число:мн ~краткий } }
then 4
}
// лунный свет помогал им.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помогать{}.<OBJECT>*:*{ падеж:дат } }
then 3
}
// им необходимо было помочь.
// ^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помочь{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помогать{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// мой отец убит им.
// ^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:убитый{}.<OBJECT>*:*{ падеж:твор } }
then 1
}
// ей надо уйти отсюда.
// ^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:надо{}.{ ОдушОбъект{ падеж:дат } инфинитив:*{} } }
then 1
}
// ей вдруг захотелось уйти.
// ^^^ ^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:захотелось{}.{ ОдушОбъект{ падеж:дат } инфинитив:*{} } }
then 1
}
// капитан пожал им руки.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожать{}.{ <OBJECT>*:*{ падеж:дат } <OBJECT>НеодушОбъект{ падеж:вин } } }
then 2
}
// хозяин жеребца снова закричал. (закричать можно ЧТО-ТО, но не КОГО-ТО)
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:закричать{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then -100
}
// ей явно понравился ответ.
// ^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:понравиться{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 1
}
// остальным предстояло помогать им.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:помогать{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 1
}
// им стало вдруг зябко.
// ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:стало{}.ОдушОбъект{ падеж:дат } }
then 1
}
// нам стало жалко бедного котенка
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:жалко{}.ОдушОбъект{ падеж:дат } }
then 2
}
// император осторожно коснулся пальцами белой перчатки.
// ^^^^^^^^ ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:коснуться{}.<OBJECT>*:*{ падеж:род } }
then 1
}
// обычно ПРОТЯНУТЬ кому-то, а не чему-то:
// тот протянул руку помощи.
// ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:протянуть{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -5
}
// возле всякой двери тебя ждала такая же ловушка.
// ^^^^^^^^^^
// однако сперва ее ждало глубокое разочарование.
// ^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ждать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подождать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
// однако ему удалось открыть нечто интересное.
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:открыть{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 1
}
// однако название мне удалось прочитать.
// ^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прочитать{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 1
}
// пройти можно ЧТО-ТО:
// ты уже прошел его так много раз.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then -1
}
/*
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 1
}
*/
// злость прошла довольно давно.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<SUBJECT>НеодушОбъект }
then 1
}
// затем стал внимательно изучать глаз юноши.
// ^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:изучать{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// комната ожидания полна народу.
// ^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:полный{ краткий }.существительное:*{ падеж:род } }
then 1
}
tree_scorer language=Russian
{
if context { прилагательное:полный{ краткий }.существительное:*{ падеж:парт } }
then 1
}
// развалиться на части
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:развалиться{}.'на'.'части'{ падеж:вин } }
then 2
}
// ВЗЯТЬ можно КОМУ-ТО, а не ЧЕМУ-ТО:
// полковник взял микрофон внутренней связи.
// ^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:взять{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -5
}
// оставался единственный способ проверить корабль.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:проверить{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// ТРЕБОВАТЬ можно кому-то, а не чему-то:
// моя месть требует радости охоты.
// ^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:требовать{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -5
}
// ПРОДОЛЖИТЬ можно ЧТО-ТО неодушевленное:
// вскоре отряд продолжил путь.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продолжить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продолжить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then -1 }
// Ломать душу
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ломать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ломать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 1 }
// я доволен им
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:довольный{ краткий }.<OBJECT>*:*{ падеж:твор } }
then 2
}
// Обычно получить можно кому-то, а не чему-то:
// поэтому хотим получить максимум информации.
// ^^^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:получить{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -2
}
// пришла пора сделать следующий шаг.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:прийти{}.<SUBJECT>существительное:пора{}.инфинитив:*{} }
then 1
}
// убить КОГО-ТО:
// ты должен его убить!
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убивать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:убивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// мне едва удалось его спасти.
// ^^^ ^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:удалось{}.<SUBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// им удалось вытащить его из озера.
// ^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:удалось{}.<SUBJECT>*:*{ падеж:дат } }
then 1
}
// ЕДА не может быть продавцом:
// В булочной продают хлеб, булки, печенье.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:продавать{}.<SUBJECT>существительное:*{ <в_класс>существительное:еда{} } }
then -100
}
// ОБЪЯСНИТЬ можно обычно кому-то:
// происхождение информации объясню позднее.
// ~~~~~~~~~~ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:объяснить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:объяснить{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 1 }
#region СОЗДАВАТЬ
// если получатель действия находится слева от глагола, то штрафуем:
// банки памяти создавали самую большую проблему.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:создавать{ 2 }.<OBJECT>*:*{ падеж:дат 1 } }
then -1
}
// Но компенсируем предыдущее правило, если получатель - одушевленный:
// нам создали тепличные условия
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:создавать{ 2 }.<OBJECT>ОдушОбъект{ падеж:дат 1 } }
then 1
}
#endregion СОЗДАВАТЬ
// Обычно ПОКАЗАТЬСЯ можно КОМУ-ТО:
// показалась машина местной полиции.
// ^^^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 1 }
// БЕЖАТЬ можно чем-то неодушевленным, например - БЕРЕГОМ:
// бегущим по берегу псом
// ^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бежать{}.<OBJECT>ОдушОбъект{ падеж:твор } } then -100 }
// Чтобы подавить распознавание существительным "БЫЛЬ":
// "Обвиняемые были освобождены в зале суда"
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{ 2 }.<SUBJECT>прилагательное:*{ падеж:им ~краткий степень:атриб 1 } }
then 2
}
// ПОИСКАТЬ обычно можно КОМУ-ТО:
// Давайте поищем примеры реализации этой функции
// ^^^^^^ ~~~~~~~~~~ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поискать{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -1
}
// Обычно ПРИХОДИТ КОМУ-ТО, а неодушевленный реципиент возможет лишь в
// особых оборотах типа КОНЕЦ ПРИШЕЛ ЭТОЙ АФЕРЕ.
// неизвестно откуда пришло вдруг чувство опасности.
// ^^^^^^ ~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прийти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -3 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -3 }
// советую вам исправить свою ошибку.
// ^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:советовать{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 2
}
// Подавим связывание ПРИШЛО и ПОЗАБОТИТЬСЯ исходя из того, что обычно
// только одушевленные субъекты приходят сделать что-то:
// однако пришло время позаботиться о собственной безопасности.
// ^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:придти{}.{ <SUBJECT>НеодушОбъект инфинитив:*{} } } then -1 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:прийти{}.{ <SUBJECT>НеодушОбъект инфинитив:*{} } } then -1 }
// Зайти можно КОМУ-ТО
// сам зашел снаружи конструкции противника.
// ^^^^^ ~~~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:зайти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// обычно глагол ЗАНЯТЬ идет с винительным дополнением:
// эти приготовления заняли целый день.
// ^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:занять{}.<OBJECT>*:*{ падеж:вин } } then 1 }
// Сжать обычно можно КОМУ-ТО:
// Олег изо всех сил сжал челюсти.
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:сжать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// после начала битвы прошли считанные секунды.
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:пройти{}.<SUBJECT>ИнтервалВремени{ ПАДЕЖ:ИМ } }
then 1
}
// желаю тебе найти принца.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:желать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// Он рекомендовал мне сделать это.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рекомендовать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// Он угрожал мне бросить работу.
// ^^^^^^^ ^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:угрожать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// позволю себе напомнить историю вопроса.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:позволить{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// Олег хмуро окинул взглядом убитого.
// ^^^^^^ ^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:окинуть{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>'взглядом' } }
then 1
}
// где же моя благодарность?
// ^^^^^^ ^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { наречие:где{}.{ частица:же{} существительное:*{ падеж:им } } }
then 1
}
// кому хочется есть
// ^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:хочется{}.<SUBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 1
}
// нам нужно только доставить его туда.
// ^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:нужно{}.<SUBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 2
}
// ТОРЖЕСТВОВАТЬ можно ЧТО-ТО неодушевленное:
// Весь день и весь вечер шумел и торжествовал народ по всему королевству
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:торжествовать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } }
then -100
}
// МЕШАТЬ кому-то ДЕЛАТЬ что-то
// страх мешал ей плакать.
// ^^^^^ ^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:мешать{}.{ <OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } инфинитив:*{} } }
then 2
}
// ПОВТОРИТЬ можно обычно КОМУ-ТО, а не ЧЕМУ-ТО
// мастер песни повторил вопрос.
// ~~~~~ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:повторить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// вскоре подошел поезд метро.
// ^^^^^^^ ~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подойти{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// ОТКРЫВАТЬСЯ можно обычно КОМУ-ТО
// новый мир открывался после каждой мили пути.
// ^^^^^^^^^^ ~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:открываться{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// Обычно СЛОЙ покрывает что-то, даже если порядок слов обратный нормальному:
// пол покрывал толстый слой пыли.
// ^^^^^^^^ ^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:покрывать{}.{ <SUBJECT>существительное:слой{} НеодушОбъект{ ПАДЕЖ:ВИН } } }
then 2
}
// Ей нравится ходить туда.
// ^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:нравилось{}.<SUBJECT>*:*{ ПАДЕЖ:ДАТ } }
then 2
}
// оставался единственный способ проверить корабль.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:проверить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 2
}
// кому вы отдали его?
// ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:*{}.<OBJECT>'кому'{ падеж:дат class:местоим_сущ } }
then 2
}
// кому может понадобиться старая чужая лодка?
// ^^^^ ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:*{}.<OBJECT>'кому'{ падеж:дат class:местоим_сущ } }
then 2
}
// Не смей мне врать!
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:врать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } }
then 2
}
// меня все здесь боятся!
// ^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бояться{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } }
then 1
}
// Он мучает её своим бесчувствием.
// ^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:мучить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 1
}
// почему ты позволил им упасть?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:позволить{}.<OBJECT>*:*{ падеж:дат } }
then 2
}
// разве обычные люди могут читать мысли?
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:читать{}.<OBJECT>НеодушОбъект{ падеж:вин } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:читать{}.<OBJECT>ОдушОбъект{ падеж:дат } }
then 1
}
// НАЗЫВАТЬ обычно идет с винительным дополнением:
// все его называют сегодня мальчиком.
// ^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:называть{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Подавляем присоединение послелогов к существительным:
// недалеко от него лежал человек лицом вниз.
// ~~~~~~~ ^^^^^^^^^^
tree_scorer language=Russian { if context { существительное:*{}.послелог:вниз{} } then -10 }
tree_scorer language=Russian { if context { существительное:*{}.послелог:вверх{} } then -10 }
tree_scorer language=Russian { if context { существительное:*{}.послелог:вперед{} } then -10 }
// Показывать на одушевленного (вин) - это важно, если объект несклоняемый:
// Вадим показал на Элен
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:показать{}.предлог:на{}.ОдушОбъект{ падеж:вин } }
then 1
}
// пора им всем возвращаться домой.
// ~~~~~~~ ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:возвращаться{}.ОдушОбъект{ падеж:твор } }
then -10
}
// мама души не чаяла в своих детях
// ~~~~ ^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:чаять{}.<OBJECT>существительное:душа{} }
then 30
}
// Комар носа не подточит.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подточить{}.{ частица:не{} <OBJECT>существительное:нос{} } }
then 30
}
/*
// с тех пор ты видел его всего несколько раз.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { наречие:всего{}.наречие:несколько{}.существительное:раз{} }
then 2
}
*/
// Руперт вопреки себе улыбнулся.
// ^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.предлог:вопреки{} }
then 2
}
// вам следует проверить Марину согласно инструкции.
// ^^^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.предлог:согласно{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.предлог:согласно{} } then 2 }
// убийство для них естественно.
tree_scorer language=Russian { if context { прилагательное:естественный{}.предлог:для{} } then 2 }
// Пусть предложное дополнение с У присоединяется к глаголу, а не к существительному:
// ноги у меня болели.
// ^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.предлог:у{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.предлог:у{} } then 2 }
// Антон ее так назвал.
// ^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:назвать{}.<OBJECT>*:*{ падеж:вин } }
then 1
}
// Наречие ЧАСТО служит косвенным признаком изъявительной, а не императивной формы глагола:
// ты часто ешь хлеб
// ^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.наречие:часто{} }
then -2
}
// Наречие ОЧЕНЬ служит косвенным признаком изъявительной, а не императивной формы глагола:
// вы очень любите ягоды
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.наречие:очень{} }
then -2
}
// несколько дней спустя путников ожидал приятный сюрприз.
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ожидать{}.ОдушОбъект{ ПАДЕЖ:ВИН } }
then 1
}
// ПРИВЛЕЧЬ обычно можно КОГО-ТО одушевленного:
// Его привлекли к ответственности за нарушение порядка.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:привлечь{}.ОдушОбъект{ ПАДЕЖ:ВИН } }
then 1
}
// Его целый год держали в тюрьме.
// ^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:держать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 4
}
// ОБЕЩАТЬ КОМУ-ТО СДЕЛАТЬ что-то:
// ты обещал мне показать корабль!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обещать{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } }
then 2
}
// чиновник приказал ему открыть два кожаных мешка.
// ^^^^^^^^ ^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приказать{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } }
then 5
}
// ++++++++++++++++++++++++++++++++++++++++
// мне обещали все вернуть назад
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обещать{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } }
then 5
}
// ++++++++++++++++++++++++++++++++++++++++
// мне обещали все вернуть назад
// Его гордость не позволяла ему просить об одолжении.
// ^^^^^^^^^ ^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:позволять{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:позволить{}.{ <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} инфинитив:*{} } } then 2 }
// такое устройство для моих целей бесполезно.
// ~~~~~~~~~~ ^^^ ^^^^^^^^^^
tree_scorer language=Russian { if context { прилагательное:бесполезный{}.предлог:для{} } then 2 }
// ДАТЬ отчет можно обычно КОМУ-ТО, а не чему-то:
// Он дал подробный отчёт о своей поездке.
// ^^^ ^^^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.{ <OBJECT>существительное:отчет{} <OBJECT>НеодушОбъект{ПАДЕЖ:ДАТ} } }
then -10
}
// отстегнуть маме денег
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отстегнуть{}.{ <OBJECT>НеодушОбъект{ падеж:род } <OBJECT>ОдушОбъект{ПАДЕЖ:ДАТ} } }
then 5
}
// все вас боятся
// ~~~~~~~
tree_scorer language=Russian
{
if context { 'вас'.'все'{class:прилагательное} }
then -100
}
// Я работаю учителем в сельской школе
// ^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:работать{}.предлог:в{}.*:*{падеж:предл} } then 2 }
// небеса для меня закрыты.
// ^^^ ^^^^^^^^
tree_scorer language=Russian { if context { прилагательное:закрытый{}.предлог:для{} } then 2 }
// Это такое трудное слово, что он не может его запомнить.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:запомнить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// Его утомляла долгая ходьба.
// ^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:утомлять{}.ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:утомить{}.ОдушОбъект{ падеж:вин } } then 2 }
// но где удалось его добыть?
// ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:добыть{}.НеодушОбъект{ падеж:вин } } then 2
}
// кладбище от моря довольно далеко
// ~~~~~~~~ ^^ ^^^^^^
tree_scorer language=Russian { if context { прилагательное:далекий{}.предлог:от{} } then 2 }
// мы внедряем в жизнь идеи великих ученых
// ^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:внедрять{}.<OBJECT>НеодушОбъект{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:внедрить{}.<OBJECT>НеодушОбъект{ПАДЕж:ВИН} } then 2 }
// неужели разговор его окончательно сломал?
// ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:переломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обломать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обламывать{}.<OBJECT>*:*{ПАДЕж:ВИН} } then 2 }
// Критика должна составлять душу журнала.
// ^^^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:составлять{1}.<OBJECT>НеодушОбъект{ 2 ПАДЕж:ВИН} } then 1 }
// ПОРАЗИТЬ обычно можно КОГО-ТО, а не чего-то:
// однако его глубоко поразило одно событие.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поразить{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } }
then 2
}
// такое положение вещей его вполне устраивает.
// ^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:устраивать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:устроить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// Обычно ПОИСКАТЬ можно КОМУ-ТО, а не чему-то:
// Давайте поищем примеры реализации этой функции
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поискать{}.<OBJECT>НеодушОбъект{ПАДЕж:ДАТ} } then -1 }
// Давать КОМУ-ТО ЧЕГО-ТО:
// Рита дает девочке хлеба.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:давать{}.{
<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ }
<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД }
}
}
then 5
}
// Я дам им чаю
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.{
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
<OBJECT>*:*{ ПАДЕЖ:ПАРТ }
}
}
then 5
}
// попросил передать управление станции.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:передать{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
}
}
then 5
}
// ЕСТЬ могут обычно только одушевленные:
// Антонио ест суп и пюре
// ^^^^^^^ ^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:есть{}.{ <SUBJECT>ОдушОбъект{} <OBJECT>*:*{ падеж:вин } } }
then 1
}
/*
// есть несколько возможных вариантов.
tree_scorer language=Russian
{
if context { rus_verbs:быть{}.наречие:несколько{}.существительное:*{} }
then 1
}
*/
// Мы можем использовать эти сюжеты в молитвах.
// ^^^^^^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:использовать{}.предлог:в{}.*:*{ падеж:предл } }
then 2
}
// ЛУЧШЕ+инфинитив является очень частотным паттерном, в отличие от использования ЛУЧШЕ в качестве
// простого атрибута глагола (как в СТАРАЙСЯ ЛУЧШЕ!)
// лучше избавиться от обезьяны
// ^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:лучше{1}.инфинитив:*{2} } then 2
}
// ПОКОРМИТЬ можно кого-то одушевленного:
// Мы покормили белок.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:покормить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:кормить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:накормить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// СЛУШАТЬСЯ кого-то/вин:
// слушаться родителей
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:слушаться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:послушаться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// ПОЛОЖИТЬ кого-то/вин/:
// Нам придётся положить его в больницу.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:положить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ложить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// ХОТЕТЬ кому-то одуш
// хочу кофе
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хотеть{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// КАК обычно является наречием, модифицирующим глаголы и инфинитивы
// однако как остановить профессора?
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{2}.<ATTRIBUTE>наречие:как{1}.[not]*:*{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{2}.<ATTRIBUTE>наречие:как{1}.[not]*:*{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { безлич_глагол:*{2}.<ATTRIBUTE>наречие:как{1}.[not]*:*{} } then 2 }
// кроме того, КАК может атрибутировать наречия:
tree_scorer language=Russian { if context { наречие:*{ степень:атриб }.<ATTRIBUTE>наречие:как{} } then 1 }
// как будто они нас понимают
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:как будто{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:как будто{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { прилагательное:*{ причастие краткий }.<ATTRIBUTE>наречие:как будто{} } then 7 }
// внутри все выглядело как всегда
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:как всегда{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:как всегда{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { прилагательное:*{ причастие краткий }.<ATTRIBUTE>наречие:как всегда{} } then 7 }
// сегодня все было как обычно
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:как обычно{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:как обычно{} } then 7 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { прилагательное:*{ причастие краткий }.<ATTRIBUTE>наречие:как обычно{} } then 7 }
/*
// наречие КАК обычно не стоит справа от глагола в одиночку.
// убью как собаку.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{1}.<ATTRIBUTE>наречие:как{2}.[not]*:*{} }
then -10
}
*/
// Олег вытянул вперед руки
// ^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вытянуть{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вытягивать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
// теперь она могла его толком рассмотреть.
// ^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:толком{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian generic { if context { глагол:*{}.<ATTRIBUTE>наречие:толком{} } then 2 }
// они быстро пересекли плато
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пересечь{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:пересекать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
// Как вызвать такси?
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызвать{}.<OBJECT>*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызывать{}.<OBJECT>*:*{ падеж:вин } } then 1 }
// наверху их охватил морской ветер.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:охватить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// Чиновник уже пообещал, что не будет покрывать своего родственника
// ^^^^^^^^^ ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:покрывать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 2
}
// Толстые линии показывают связи между участками коры
// ^^^^^^^^^^ ~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показывать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показывать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ДАТ } } then 2 }
// Олег хмуро окинул взглядом убитого.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окинуть{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// по левой стороне груди текла кровь.
// ~~~~~ ^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:течь{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -2 }
// это может лишить наше общество работы
// ^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:лишить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:лишать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } } then 2 }
// сбивая их сильной струей воды с надводной растительности
// ^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сбивать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сбить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// Лидеры организации хасидов заявили, что деньги их не интересуют
// ^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:интересовать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// как радостно за руку ее схватили!
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:схватить{}.<OBJECT>местоимение:я{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хватать{}.<OBJECT>местоимение:я{ ПАДЕЖ:ВИН } } then 2 }
// Антон поднес ладони к горлу
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поднести{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подносить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// оставшиеся вынуждены по очереди помогать ей двигаться вперед
// ^^^^^^^^^ ^^^^^^^^
tree_scorer language=Russian { if context { прилагательное:вынужденный{}.инфинитив:*{} } then 2 }
// Артур погладил по носу старого коня
// ^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:погладить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:гладить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// ты можешь нас туда провести?
// ^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провести{}.<OBJECT>местоимение:я{ ПАДЕЖ:ВИН } } then 1 }
// провожают обычно одушевленные объекты,
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:проводить{ вид:соверш }.<OBJECT>НеодушОбъект{ падеж:вин } } then -5 }
tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:проводить{ вид:соверш }.<OBJECT>НеодушОбъект{ падеж:вин } } then -5 }
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:проводить{ вид:несоверш }.<OBJECT>ОдушОбъект{ падеж:вин } } then -5 }
tree_scorer ВалентностьГлагола language=Russian { if context { инфинитив:проводить{ вид:несоверш }.<OBJECT>ОдушОбъект{ падеж:вин } } then -5 }
// у ворот всадников проводили жесткие темные глаза стражи
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:проводить{ вид:соверш }.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// но это мешало им
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:мешать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помешать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:препятствовать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// его можно предотвратить
// ^^^ ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвратить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвращать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвратить{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } } then -10 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предотвращать{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН } } then -10 }
// им хорошо платят
// ^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:платить{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заплатить{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// Гарри взял
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:взять{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:РОД } } then -1 }
// сигареты у него забрали
tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:забрать{}.<SUBJECT>НеодушОбъект } then -1 }
tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:брать{}.<SUBJECT>НеодушОбъект } then -1 }
tree_scorer ВалентностьПредиката language=Russian { if context { rus_verbs:забирать{}.<SUBJECT>НеодушОбъект } then -1 }
// тот принял ее мертвой рукой.
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принять{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принимать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// В США миллионера осудили за попытку продать Ирану детали для ракет ПВО
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:осудить{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:осуждать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// Африканский союз позвал войска НАТО в Мали
// ^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:позвать{}.предлог:в{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:звать{}.предлог:в{}.*:*{ падеж:вин } } then 2 }
// вряд ли это им понравится.
// ^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:понравиться{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// слушайся меня
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:слушаться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:послушаться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 }
// все это ее непосредственно касалось.
// ^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:коснуться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:касаться{}.<OBJECT>*:*{ ПАДЕЖ:РОД } } then 2 }
// а громадный глаз подмигнул им
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подмигнуть{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:подмигивать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// ты мог бы им помочь.
// ^^ ^^^^^^
//tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помочь{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
//tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:помогать{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } } then 2 }
// воины окружили их кольцом.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окружить{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>НеодушОбъект{ ПАДЕЖ:ТВОР } } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:окружать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>НеодушОбъект{ ПАДЕЖ:ТВОР } } } then 2 }
// кому теперь нужны новые программы?
// ^^^^ ^^^^^
tree_scorer language=Russian { if context { прилагательное:нужный{}.<OBJECT>местоим_сущ:кто{ ПАДЕЖ:ДАТ } } then 2 }
// именно твое мнение для нас крайне важно.
// ^^^ ^^^^^
tree_scorer language=Russian { if context { прилагательное:важный{}.предлог:для{} } then 2 }
// от него ждали реакции.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ждать{}.{ <OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } предлог:от{} } } then 2 }
// протер от пыли глаза.
// ^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:протереть{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:притирать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } } then 2 }
// ты предпочел камни моей жизни.
// предпочесть ЧТО-ТО ЧЕМУ-ТО
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:предпочесть{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
}
} then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:предпочитать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
}
} then 2
}
// мы вынуждены просить вашей помощи.
// ^^^^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:просить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:запросить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// Наречие ТАК обычно не модифицирует наречия места и времени:
// так где ты был?
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:МЕСТО }.наречие:так{} } then -100 }
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:НАПРАВЛЕНИЕ }.наречие:так{} } then -100 }
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:НАПРАВЛЕНИЕ_ОТКУДА }.наречие:так{} } then -100 }
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:МОМЕНТ_ВРЕМЕНИ }.наречие:так{} } then -100 }
tree_scorer language=Russian { if context { наречие:*{ ОБСТ_ВАЛ:КРАТНОСТЬ }.наречие:так{} } then -100 }
// равнина напоминала поле битвы.
// ^^^^^^^^^^ ~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:напоминать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:напомнить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// Дети угостили белок орешками.
// УГОСТИТЬ можно КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угостить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угощать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угостить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:угощать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// хочешь кофе?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:хотеть{}.<OBJECT>существительное:*{ падеж:род <в_класс>существительное:напиток{} } }
then 1
}
// мы встретили охотника, способного догнать и поймать кенгуру
// ^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поймать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ловить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// протестующие начали собираться на площади
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:собираться{}.предлог:на{}.*:*{ падеж:предл } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:собраться{}.предлог:на{}.*:*{ падеж:предл } }
then 1
}
// Когда он вошел, все стаканы попадали с полки.
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:падать{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:попадать{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:упасть{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:свалиться{}.предлог:с{}.*:*{ падеж:род } } then 2 }
// подруга Иды не пришла на урок
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придти{}.предлог:на{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прийти{}.предлог:на{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приходить{}.предлог:на{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зайти{}.предлог:на{}.*:*{ падеж:вин } } then 2 }
// Английская традиция акварели оказала сильное влияние на русских художников
// ~~~~~~~~ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оказать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оказывать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
// одна из женщин показалась ему знакомой.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// две женщины вывели из темноты раненого.
// ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вывести{}.*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выводить{}.*:*{ падеж:вин } } then 2 }
// она часто просила меня рассказывать истории.
// ^^^^^^^^^^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:рассказать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:рассказывать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// Мы рассказывали о тех, кто менял мир
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рассказывать{}.предлог:о{}.*:*{ падеж:вин } } then -10
}
// к вечеру жара спала.
// ^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { глагол:спать{}.<SUBJECT>НеодушОбъект } then -2 }
// Доллар снова сдает позиции
// ^^^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сдавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сдать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// жена полковника смотрела им вслед
// ^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:смотреть{}.послелог:вслед{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:посмотреть{}.послелог:вслед{} } then 2 }
// можно попытаться заменить собой стражу.
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заменить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заменять{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// двое крестьян схватили за руки своего господина.
// ^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:схватить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:хватить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// тебя вызывает начальник станции.
// ^^^^^^^^ ~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызывать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вызвать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// тот молча сунул ей два факела.
// ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сунуть{}.<OBJECT>*:*{ падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:совать{}.<OBJECT>*:*{ падеж:дат } } then 2 }
// Михаил зажал себе ладонью рот.
// ^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зажать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зажимать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// им оставалось преодолеть около тридцати футов.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { 'оставалось'{2 class:безлич_глагол}.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { 'остается'{2 class:безлич_глагол}.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
// ей приходилось идти очень медленно.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { 'приходилось'{ 2 class:безлич_глагол }.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { 'приходится'{2 class:безлич_глагол}.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
// кого интересует мнение машины?
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:интересовать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// Газета сообщает об открытии сессии парламента.
// ^^^^^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сообщить{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// ей довелось увидеть только последствия.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { 'довелось'{2}.<OBJECT>*:*{ 1 падеж:дат } } then 2 }
// Геолог недавно открыл залежи руды.
// ^^^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:открыть{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:открывать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// Дети не дают матери покоя.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:давать{}.{
частица:не{}
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:род }
}
} then 2
}
// Директор заявил, что уходит на пенсию.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заявить{}.союз:что{} } then 2
}
// Люди провозгласили его гениальным писателем.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провозгласить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:провозглашать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// они создали магию крови.
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:создать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:создавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// они боятся меня теперь.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:бояться{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// они называли ее железной.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:называть{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:назвать{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// он отнес коробку к дедушке
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отнести{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:относить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:отнести{}.<OBJECT>*:*{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:относить{}.<OBJECT>*:*{ падеж:вин } } then 2 }
// какой вес имеют эти вещи искусства?
// ^^^^^ ~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:иметь{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -100 }
// но прежде нам необходимо найти тело
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context {
безлич_глагол:необходимо{}.{
<SUBJECT>*:*{ падеж:дат }
<INFINITIVE>инфинитив:*{}
}
} then 2
}
// вы можете предоставить ему другую работу?
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставлять{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставить{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:предоставлять{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// Никто из присутствующих при этом не пострадал.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer language=Russian { if context { местоим_сущ:никто{}.предлог:из{} } then 5 }
// она протянула к огню руки.
// ^^^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:протянуть{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:протягивать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
// почему она ему поверила?
// ^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поверить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:верить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
// человек впервые показал эмоции.
// ^^^^^^^ ~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показывать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// хочешь передать ему новость?
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:передать{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:передавать{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
// они зашли за угол крепости.
// ^^^^^ ~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:зайти{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заходить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// ты достаточно заплатил ему?
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:заплатить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:платить{1}.<OBJECT>ОдушОбъект{ 2 падеж:дат } } then 2 }
// их тоже стало меньше?
// ^^ ^^^^^
tree_scorer language=Russian { if context { 'стало'.<OBJECT>*:*{ падеж:род } } then 1 }
tree_scorer language=Russian { if context { 'станет'.<OBJECT>*:*{ падеж:род } } then 1 }
// ему хотелось выпить все озеро.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { безлич_глагол:хочется{}.<SUBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// как им хочется меня убить!
// ^^^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:хочется{}.{ <SUBJECT>ОдушОбъект{ падеж:дат } инфинитив:*{} } }
then 2
}
// нам следует передать им это дело
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { безлич_глагол:следует{}.<SUBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// все данные у него есть.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { 'есть'{ class:глагол 2 }.предлог:у{ 1 } } then 2 }
// сколько уверенности принесли они мне.
// ^^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:принести{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приносить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// возьмут ли меня туда?
// ^^^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:взять{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:брать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
// она обхватила его руками за шею.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обхватить{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обхватывать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
// один из гномов ткнул его палкой.
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:ткнуть{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:тыкать{}.<OBJECT>местоимение:я{ падеж:вин } } then 2 }
// такое обращение может его сильно обидеть.
// ^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обидеть{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обижать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обидеть{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:обижать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then -2 }
// дай мне прикончить его!
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:прикончить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:приканчивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// теперь она может выслушать его.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выслушать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выслушивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// внешность этой женщины поразила его.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поразить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поражать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// ты его недавно сделал?
// ^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:сделать{}.<OBJECT>местоимение:*{ падеж:вин } } then 2 }
// не смей вовлекать его в свои делишки
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вовлекать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:вовлечь{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// дилер выгодно продал акции
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:продавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
// мы выдали ему костюм
// --> выдать обычно можно кому-то
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдавать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдавать{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:выдавать{}.<OBJECT>ОдушОбъект{ падеж:дат } } then 2 }
// я доверяю ему в этих вопросах
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверять{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверить{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверять{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:доверить{}.<OBJECT>НеодушОбъект{ падеж:вин } } then 2 }
// Она хотела побыстрее его женить
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:женить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// его избили
// --> ИЗБИТЬ КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:избить{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:избивать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 2 }
// собственные слова тут же показались верхом глупости.
// ПОКАЗАТЬСЯ можно КОМУ-ТО, а не ЧЕМУ-ТО
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:показаться{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:казаться{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// мы продолжали поднимать тяжести
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:поднимать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// Круче не придумаешь
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:придумать{}.<OBJECT>НеодушОбъект{ падеж:дат } } then -1 }
// Ключевая валютная пара останется волатильной
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:остаться{}.прилагательное:*{ падеж:дат } } then -1 }
tree_scorer ВалентностьГлагола language=Russian { if context { rus_verbs:оставаться{}.прилагательное:*{ падеж:дат } } then -1 }
// остальные были заняты тем же
tree_scorer language=Russian { if context { прилагательное:занятый{ краткий }.*:*{ падеж:твор } } then 2 }
// записи мы посмотрим потом
// ^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:посмотреть{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -1
}
// целенаправленно обеспечивали его свежей продуктовой массой
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:обеспечивать{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// Олег потрогал его ногой
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:потрогать{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// хозяин пнул его ногой
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:пнуть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// Иван отодвинул его рукой
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:отодвинуть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// слуга вновь наполнил его вином
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:наполнить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// многие горожане сочли его попыткой скрыть преступление под давлением евреев
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:счесть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// Суд признал его виновным.
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:признать{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// отец остановил ее жестом руки.
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:остановить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// молодой человек оттолкнул его взглядом!
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:оттолкнуть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// тот ловко подхватил его левой рукой.
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:подхватить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// младший толкнул его ногой
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:толкнуть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// капитан прикрыл ладонью глаза
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:прикрыть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
// Пол удивленно поднял брови.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поднять{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -1
}
// ты должна ненавидеть ее всей душой
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context
{ rus_verbs:ненавидеть{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
} then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:попытаться{}.<OBJECT>*:*{ ПАДЕЖ:ДАТ } }
then -1
}
// кенгуру не умеет петь песни
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:петь{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -1
}
// они называли ее железной.
// ^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:называть{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 1
}
// Ударил ли Артур копьем дракона?
// тогда ударил ее кулаком по голове
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ударить{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
// УДАРИТЬ можно либо что-то, либо по чему-то:
// тот ударил по ней кулаком
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ударить{}.{
<OBJECT>*:*{ падеж:вин }
<PREPOS_ADJUNCT>предлог:по{}
}
}
then -5
}
// +++++++++++++++++++++++++++++++++++++++++++++++++=
// Самый западный и самый большой полуостров Азии - Аравийский
// ^^^^^^^^^^^^^
tree_scorer language=Russian
{
if context { прилагательное:самый{}.прилагательное:*{} }
then 1
}
// Даже сторонники экс-премьера не смогли поприветствовать своего кумира
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смочь{}.{
<OBJECT>*:*{ падеж:вин }
инфинитив:*{}.<OBJECT>*:*{ падеж:вин }
}
}
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смочь{}.{
<OBJECT>*:*{ падеж:род }
инфинитив:*{}.<OBJECT>*:*{ падеж:вин }
}
}
then -1
}
// ресницы ее начали опускаться
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:начать{}.{
<OBJECT>*:*{ падеж:вин }
инфинитив:*{}
}
}
then -1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:начать{}.{
<OBJECT>*:*{ падеж:род }
инфинитив:*{}
}
}
then -1
}
// Завершаем 83-й женевский автосалон масштабным обзором новинок в лидирующих сегментах автопрома
// ^^^^^^^^^ ^^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:завершать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
/*
// В День Воли белорусов призвали побороть страх и лень
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:призвать{}.{
ОдушОбъект{ падеж:вин }
инфинитив:*{}
}
}
then 5
}
// РФ призывает США воздержаться от линии силового давления на Дамаск.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:призывать{}.{
<OBJECT>*:*{ падеж:вин }
инфинитив:*{}
}
}
then 5
}
*/
// Он не произнёс ни слова.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.{
частица:не{}
существительное:*{ падеж:род }.частица:ни{}
}
}
then 5
}
// США хотят нормализовать отношения с Россией
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:хотеть{}.{
<SUBJECT>*:*{}
инфинитив:*{}
}
}
then 1
}
// их стали делать
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:стать{1}.инфинитив:*{ вид:несоверш } }
then 2
}
// Понизим достоверность связывания ПООБЕЩАТЬ с дательным падежом слева, чтобы не
// возникала ошибка в предложениях типа:
// Президент Ингушетии пообещал ...
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пообещать{2}.{
<OBJECT>*:*{ 1 падеж:дат }
}
}
then -1
}
// ========================================================================
// Некоторые модальные глаголы не могут присоединять прямое дополнение в
// винительном падеже, если присоединен инфинитив:
//
// Я ничего не смог из него выжать
// ^^^^^^ ~~~~
// Я яблоко ему не смог отдать
// ^^^^^^ ~~~~
wordentry_set МодальнБезДоп={
rus_verbs:советовать{}, // Общество потребителей советует аккуратно использовать банковские карты
rus_verbs:рекомендовать{},
rus_verbs:мочь{}, // Комментарии можете оставить при себе
rus_verbs:позволять{}, // Островное положение города позволяет смягчить колебания температур
rus_verbs:требовать{}, // долг чести требовал освободить ее.
rus_verbs:продолжать{}, // глаза его продолжали оставаться широко раскрытыми.
rus_verbs:захотеть{}, // он споры захочет решать мечом
rus_verbs:смочь{}, // ты сможешь ее удержать?
rus_verbs:начинать{}, // голос ее начинал дрожать
rus_verbs:принуждать{}, // Полицейских принуждают покупать лотерейные билеты
rus_verbs:продолжить{}, // США продолжат распространять демократию по всему миру
rus_verbs:позволить{}, // Курс нового Советского правительства на индустриализацию страны позволил создать мощную промышленную базу
rus_verbs:закончить{}, // Я только что закончил писать письмо.
rus_verbs:заканчивать{},
rus_verbs:начать{},
rus_verbs:пробовать{},
rus_verbs:попробовать{},
rus_verbs:дозволять{},
rus_verbs:дозволить{},
rus_verbs:разрешать{},
rus_verbs:разрешить{},
rus_verbs:запрещать{},
rus_verbs:запретить{},
rus_verbs:предписывать{},
rus_verbs:предписать{},
rus_verbs:присоветывать{},
rus_verbs:обожать{},
rus_verbs:поручать{},
rus_verbs:поручить{},
rus_verbs:предпочитать{},
rus_verbs:предпочесть{},
rus_verbs:бояться{},
rus_verbs:побояться{},
rus_verbs:бросать{},
rus_verbs:бросить{},
rus_verbs:давать{},
rus_verbs:дать{},
rus_verbs:доверять{},
rus_verbs:доверить{},
rus_verbs:желать{},
rus_verbs:хотеть{},
rus_verbs:забывать{},
rus_verbs:забыть{},
rus_verbs:задумывать{},
rus_verbs:задумать{},
rus_verbs:кончать{},
rus_verbs:кончить{},
rus_verbs:любить{},
rus_verbs:полюбить{},
rus_verbs:мешать{},
rus_verbs:помешать{},
rus_verbs:ожидать{},
rus_verbs:планировать{},
rus_verbs:запланировать{},
rus_verbs:предлагать{},
rus_verbs:предложить{},
rus_verbs:пытаться{},
rus_verbs:попытаться{},
rus_verbs:рассчитывать{},
rus_verbs:посоветовать{},
rus_verbs:потребовать{},
rus_verbs:уметь{},
rus_verbs:суметь{},
rus_verbs:успевать{},
rus_verbs:успеть{},
rus_verbs:решать{},
rus_verbs:решить{},
rus_verbs:напоминать{},
rus_verbs:напомнить{},
rus_verbs:обещать{},
rus_verbs:пообещать{},
rus_verbs:прекращать{},
rus_verbs:прекратить{},
rus_verbs:указывать{},
rus_verbs:указать{}
}
// Попробуй ты ее успокоить
tree_scorer ВалентностьГлагола language=Russian
{
if context { МодальнБезДоп.{ <OBJECT>*:*{ падеж:вин } инфинитив:*{} } }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { МодальнБезДоп.{ <OBJECT>*:*{ падеж:род } инфинитив:*{} } }
then -100
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.<LEFT_AUX_VERB>МодальнБезДоп.<OBJECT>*:*{ падеж:вин } }
then -100
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.<LEFT_AUX_VERB>МодальнБезДоп.<OBJECT>*:*{ падеж:род } }
then -100
}
// ========================================================================
// ===========================================================================================
// Некоторые модальные глаголы обычно требуют присоединения и прямого дополнения, и инфинитива
// ===========================================================================================
#define МодальнСВинДоп(v) \
#begin
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{3 }.{ <OBJECT>*:*{ падеж:вин 2 } rus_verbs:v{1} } }
then 4
}
#end
МодальнСВинДоп(заставить) // путь заставит тебя принять это
МодальнСВинДоп(заставлять) // оно заставляет меня вспоминать
МодальнСВинДоп(выучить) // Он выучил меня играть в шахматы.
МодальнСВинДоп(учить)
МодальнСВинДоп(научить)
МодальнСВинДоп(попросить)
МодальнСВинДоп(просить)
МодальнСВинДоп(умолять)
МодальнСВинДоп(упрашивать)
МодальнСВинДоп(упросить)
// ==========================================================
// или научились ей пользоваться
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:научиться{}.{
<OBJECT>*:*{}
инфинитив:*{}
}
}
then -10
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:научиться{}.{
<OBJECT>*:*{}
инфинитив:*{}
}
}
then -10
}
// Чтобы причастие или прилагательное, прикрепленное к БЫТЬ,
// было согласовано с подлежащим по роду:
//
// а сегодняшний день обещал быть именно таким
// лето должно быть именно таким
/*
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{ модальный }.{
<SUBJECT>*:*{ род:муж число:ед }
инфинитив:быть{}.прилагательное:*{ род:муж число:ед }
} }
then 1
}
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{ модальный }.{
<SUBJECT>*:*{ род:ср число:ед }
инфинитив:быть{}.прилагательное:*{ род:ср число:ед }
} }
then 1
}
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{ модальный }.{
<SUBJECT>*:*{ род:жен число:ед }
инфинитив:быть{}.прилагательное:*{ род:жен число:ед }
} }
then 1
}
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{ модальный }.{
<SUBJECT>*:*{ число:мн }
инфинитив:быть{}.прилагательное:*{ число:мн }
} }
then 1
}
*/
// --------------------------------------------------
// подавляем присоединение одновременно прямого дополнения и инфинитива:
// Я ХОЧУ ЭТО СДЕЛАТЬ
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:хотеть{}.{
инфинитив:*{}
<OBJECT>*:*{ падеж:вин }
}
}
then -100
}
// приказывать секретарше принести кофе
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приказывать{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// руководитель приказал пилоту начать снижение
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приказать{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 10
}
// посоветовал ему купить лопату
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:посоветовать{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 10
}
// позволять другим найти ход
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:позволять{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// позволить компьютеру найти решение
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:позволять{}.{
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// лицо незнакомца было покрыто потом
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:покрытый{}.<OBJECT>НеодушОбъект{ падеж:твор } }
then 2
}
// Но последний -- тот, кого называли Табююзом -- прошел через врата на Землю.
// ^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:называть{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
// В рядах оппозиции нашли «агентов Кремля»
// На обломках метеорита нашли скрюченных пришельцев
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>ОдушОбъект{ падеж:род } }
then -10
}
// их нашли уже через час
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>местоимение:я{ падеж:род } }
then -10
}
// Российские ученые нашли челюсти чудовища на дне ледяного озера
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:найти{}.<OBJECT>НеодушОбъект{ падеж:род } }
then -1
}
// скоро она начнет искать меня
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искать{}.<OBJECT>ОдушОбъект{ падеж:род } }
then -10
}
// мне придется искать помощи
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искать{}.<OBJECT>НеодушОбъект{ падеж:род } }
then -2
}
// родителям пришлось искать его в одной из соседних станиц
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:искать{}.<OBJECT>местоимение:*{ падеж:род } }
then -10
}
// Подавим появление императива для НАСЛАТЬ, когда к нему прикреплен В+предл
// В рядах оппозиции нашли «агентов Кремля»
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:в{}.*:*{ падеж:предл } } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:на{}.*:*{ падеж:предл } } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:у{} } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:под{} } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:наслать{ наклонение:побуд }.предлог:над{} } then -10 }
// ИНТЕРЕСОВАТЬ - обычно кого-то, а не что-то
// Наравне с литературой его интересует и живопись.
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:интересовать{}.<OBJECT>НеодушОбъект } then -2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:интересовать{}.<OBJECT>ОдушОбъект{ падеж:род } } then -10 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:интересовать{}.<OBJECT>ОдушОбъект{ падеж:вин } } then 1 }
// Модальный ХОТЕТЬ, присоединив инфинитив, уже не может
// присоединять некоторые предложные дополнения:
// она хотела освободиться от меня
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:хотеть{}.{
<INFINITIVE>*:*{}
предлог:от{} }
}
then -100
}
// Обычно КОМУ-ТО идет ОДЕЖДА.
// по всему берегу шла работа
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:идти{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } } then -10 }
// Подавим присоединение наречия КАК справа к БЫТЬ:
// это было как волшебство
// ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:быть{1}.наречие:как{2} } then -10 }
// Для ПАХНУТЬ - либо ОТ+род, либо КТО-ТО.
// а от вас слишком уж пахнет
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:пахнуть{ вид:несоверш }.{
<SUBJECT>*:*{}
предлог:от{}
}
}
then -100
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:пахнуть{ вид:соверш }.{
<SUBJECT>*:*{}
предлог:от{}
}
}
then -100
}
// Обычно время суток не может являться именным сказуемым (вместе со связкой)
// где ж ты был прошлой ночью?
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{}.<RHEMA>ЧастьСуток{ ПАДЕЖ:ТВОР } }
then -2
}
// обычно ГОВОРЯТ КОМУ-ТО:
// пару минут пытался говорить.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:говорить{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -2
}
// вещи мы забрали без шума
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:забрать{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// их кони шли легким шагом
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:идти{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -10
}
// послушай лучше меня!
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:послушать{ наклонение:побуд }.{
<ATTRIBUTE>'лучше'{ class:наречие }
<OBJECT>*:*{ ПАДЕЖ:ВИН }
}
}
then 5
}
// нет больше вашего дракона
tree_scorer language=Russian
{
if context { частица:нет{}.{
<ATTRIBUTE>'больше'{ class:наречие }
существительное:*{ падеж:род }
}
}
then 5
}
// обычно КЕМ-ТО не едят:
// Антонио ел пюре каждый день
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:есть{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:ТВОР } }
then -10
}
// только как это сделать?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сделать{}.{
<ATTRIBUTE>наречие:как{}.[not]*:*{}
<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН }
} }
then 1
}
// Мозг этих существ сходен по размерам с мозгом динозавра
// ^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:сходный{}.предлог:с{}.*:*{ падеж:твор } }
then 2
}
// Я пришёл сюда раньше его
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придти{}.предлог:раньше{}.*:*{ падеж:род } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прийти{}.предлог:раньше{}.*:*{ падеж:род } }
then 2
}
// В США миллионера осудили за попытку продать Ирану детали для ракет ПВО
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:продать{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:вин }
} }
then 2
}
// ты можешь отдать его своему другу.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отдать{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
} }
then 2
}
// тратить время на пустяки
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:тратить{}.{
<OBJECT>НеодушОбъект{ падеж:вин }
предлог.*:*{ падеж:вин }
} }
then 2
}
// а каким же образом о нем узнали вы?
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.предлог:о{}.*:*{ падеж:предл } }
then 2
}
// еще четверо тащили под руки своих раненых
// ^^^^^^ ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:тащить{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// некоторые из них тащили за собой платформы
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:тащить{}.{
предлог:из{}
предлог:за{}
} }
then -10
}
// ты можешь узнать подробности у нее
// Узнав его, они закричали
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.<OBJECT>*:*{ падеж:род } }
then -1
}
// мне бы хотелось узнать о судьбе своего кота.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.{
предлог:о{}
<OBJECT>ОдушОбъект{ падеж:вин }
} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.{
предлог:об{}
<OBJECT>ОдушОбъект{ падеж:вин }
} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.{
предлог:о{}
<OBJECT>ОдушОбъект{ падеж:вин }
} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.{
предлог:об{}
<OBJECT>ОдушОбъект{ падеж:вин }
} }
then -100
}
// меня называли прекрасным человеком
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:называть{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:твор }
} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:назвать{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:твор }
} }
then -100
}
// Мы выбрали его секретарём нашей организации.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выбрать{}.{
<OBJECT>ОдушОбъект{ падеж:вин }
<OBJECT>ОдушОбъект{ падеж:твор }
} }
then 2
}
// отдал бы пару лет жизни
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.<OBJECT>НеодушОбъект{ падеж:дат } }
then -1
}
// Предпочитаем одушевленный объект в конструкции:
//
// Узнать от соседей
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:узнать{}.<PREPOS_ADJUNCT>предлог:от{}.<OBJECT>НеодушОбъект{ падеж:род } }
then -2
}
// Общее правило для побудительного наклонения: явный субъект не
// может быть в "сослагательном наклонении", то есть иметь частицу БЫ:
//
// меня бы непременно нашли
// ^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.<SUBJECT>*:*{}.частица:бы{} }
then -100
}
// -----------------------------------------------------------------
// Некоторые наречия не сочетаются с императивом, и это позволяет
// снимать омонимию:
//
// где мой револьвер?
// ^^^ ~~~
wordentry_set СловаНеДляИмператива=
{
наречие:где{},
наречие:когда{},
наречие:почему{},
наречие:зачем{},
наречие:отчего{},
местоим_сущ:кто{},
местоим_сущ:кто-то{},
местоим_сущ:что{},
местоим_сущ:что-то{}
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.СловаНеДляИмператива }
then -10
}
// -----------------------------------------------------------------
// она ждала от него совсем другого
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ждать{}.наречие:совсем{} }
then -100
}
// теперь было совсем другое дело
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:быть{}.наречие:совсем{} }
then -100
}
// она могла вполне оказаться правой
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оказаться{}.наречие:вполне{} }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оказаться{}.наречие:совсем{} }
then -100
}
// Для отрицательной формы переходного глагола
// подавим родительный падеж для прямого одушевленного дополнения:
// Самого богатого француза не пустили в Бельгию
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПАДЕЖ:ВИН }.{
частица:не{}
<OBJECT>ОдушОбъект{ ПАДЕЖ:РОД }
} }
then -2
}
// Придавим вариант прошедшего времени для несовершенного глагола, если
// есть наречие настоящего или будущего времени:
// уж больно ты сейчас слаб
// ^^^^^^^^^^^
wordentry_set НаречиеНастБуд=наречие:{ сейчас, завтра, послезавтра }
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:слабнуть{ ВРЕМЯ:ПРОШЕДШЕЕ }.{
НаречиеНастБуд
} }
then -1
}
// Подавляем наречие ДОСТАТОЧНО справа от БЫТЬ:
// она была достаточно влажной
// есть достаточно благополучные северные территории
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:быть{}.наречие:достаточно{} }
then -10
}
// нам всем очень жаль тебя
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:жаль{}.<OBJECT>ОдушОбъект{ ПАДЕЖ:РОД } }
then -2
}
// извивалась под его длинными усами
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:извиваться{}.предлог:под{}.*:*{ падеж:вин } }
then -100
}
// а результаты могли быть куда хуже
// ^^^^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:мочь{1}.наречие:куда{2} }
then -2
}
// модальный глагол МОЧЬ обычно не присоединяет предложное дополнение:
// мы можем без купюр поговорить
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:мочь{}.предлог:*{} }
then -1
}
// когда мне смотреть новости?
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.<OBJECT>существительное:*{ падеж:дат одуш:неодуш } }
then -2
}
// знаешь холм позади лагеря?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.предлог:позади{} }
then -2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.предлог:впереди{} }
then -2
}
// шли вчера по тропинке
// ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { 'шли'{ наклонение:побуд }.наречие:вчера{} }
then -2
}
// кругом была полная тишина
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context {
глагол:быть{1}.
{
прилагательное:*{ ~краткий падеж:им 2 }
существительное:*{ падеж:им 3 }
}
}
then -10
}
// Если ПОДОШЕЛ кому-то, то запрещаем предложное дополнение "К ЧЕМУ-ТО"
// Вольф широким шагом подошел к ним
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:подойти{}.
{
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
предлог:к{}
}
}
then -100
}
/*
// ------------------------------------------
// некоторые связочные глаголы требуют, чтобы объект был согласован с
// подлежащим по роду и числу:
// Он оказался сломанным
#define СвязочнГлагол(v) \
#begin
tree_scorer ВалентностьГлагола language=Russian
{
if context {
глагол:v{}.
{
sbj=<SUBJECT>*:*{}
obj=<OBJECT>прилагательное:*{ падеж:твор }
}
}
//constraints { НесогласСущПрил(sbj,obj) }
//constraints { sbj:РОД!=obj:РОД }
then -100
}
#end
СвязочнГлагол(оказаться)
оставаться
остаться
оказываться
стать
становиться
притворяться
притвориться
прикинуться
прикидываться
*/
// а результаты могли быть куда хуже
// ^^^^ ~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:быть{}.наречие:куда{} }
then -2
}
// ОКАЗАТЬСЯ надо подавлять справа любые наречия, кроме ГДЕ и КОГДА:
//
// Засада оказалась наполовину успешной
//
// все оказалось гораздо хуже
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оказаться{1}.наречие:*{ 2 ~ОБСТ_ВАЛ:МЕСТО ~ОБСТ_ВАЛ:МОМЕНТ_ВРЕМЕНИ ~СТЕПЕНЬ:СРАВН } }
then -2
}
// объединение их в единую работающую систему составляет сверхзадачу построения искусственного интеллекта.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:составлять{}.{
предлог:в{}.*:*{ падеж:вин }
<OBJECT>*:*{ падеж:вин }
} }
then -2
}
wordentry_set ПритяжМестТворЗапрет=притяж_частица:{ ее, его, их }
// прилагательные ЕЁ, ЕГО, ИХ обычно не употребляются в качестве дополнения
// творительного падежа:
// силы явно оставляли ее
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{}.<OBJECT>ПритяжМестТворЗапрет }
then -5
}
// вы же ее давно знаете!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.<OBJECT>местоимение:я{ падеж:род } }
then -2
}
// вы делаете из мухи слона
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:делать{1}.{
предлог:из{2}
<OBJECT>*:*{ 3 падеж:вин }
} }
then 1
}
// Британец, спасший от акулы детей в Австралии, потерял работу (СПАСШИЙ ОТ КОГО-ТО КОГО-ТО)
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:спасти{1}.{
предлог:от{2}
<OBJECT>*:*{ 3 падеж:вин }
} }
then 1
}
// небольшой штраф за родительное дополнение:
// мы оба знали правила игры.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.<OBJECT>*:*{ падеж:род } }
then -1
}
// Придаточное ", ЧТО ..." конкурирует за ту же валентность, что и прямое винительное/родительное
// дополнение, поэтому гасим одновременное наличие.
// Маленький квадратик на линии между блоком оценки награды и блоком выбора действия показывает, что эта связь модулирует значимость действия
// ~~~~~~~~ ^^^^^^^^^^^^^^^^
tree_scorers ВинРодДопГл
tree_scorer ВинРодДопГл language=Russian { if context { *:*{ падеж:вин } } then 1 }
tree_scorer ВинРодДопГл language=Russian { if context { *:*{ падеж:род } } then 1 }
tree_scorer ВалентностьСложнСказ language=Russian generic
{
if context { *:*{}.{
<OBJECT>ВинРодДопГл
<NEXT_CLAUSE>','.союз:что{}
}
}
then -5
}
wordentry_set Прелог_О_Об={ предлог:о{}, предлог:об{} }
// Универсальный принцип: косвенное дополнение О+чем-то заполняет тот же слот, что
// и вин/род дополнение:
// О появлении свежей лавы свидетельствует мощная подсветка в вершинном кратере вулкана
// ^^^^^^^^^^^ ~~~~~~~~~~~
tree_scorer ВалентностьСложнСказ language=Russian generic
{
if context { *:*{}.{
<OBJECT>ВинРодДопГл
Прелог_О_Об.*:*{ падеж:предл }
}
}
then -10
}
// их даже стали из бумаги делать
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:делать{}.{
<OBJECT>ВинРодДопГл
предлог:из{}
}
}
then 1
}
// только пустое пространство - космос
tree_scorer ВалентностьСложнСказ language=Russian generic
{
if context { '-'.<ATTRIBUTE>наречие:только{} }
then -2
}
// Подавим присоединение одушевленного родительного дополнения
// к глаголам в случае, если глагол может присоединить винительное:
// Я хочу тебя
// ^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{ переходность:переходный падеж:вин падеж:род }.
ОдушОбъект{ падеж:род }
}
then -1
}
// Дмитрий сказал ей об этом
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сказать{}.<OBJECT>местоимение:я{ падеж:твор } }
then -2
}
// пожелать спортсменам удачи
// ^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожелать{}.<OBJECT>*:*{ падеж:род одуш:неодуш } }
then 1
}
// пожелать спортсменам удачи
// ^^^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожелать{}.<OBJECT>*:*{ падеж:дат одуш:одуш } }
then 1
}
// желать спортсменам удачи
// ^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:желать{}.<OBJECT>*:*{ падеж:род одуш:неодуш } }
then 1
}
// желать спортсменам удачи
// ^^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:желать{}.<OBJECT>*:*{ падеж:дат одуш:одуш } }
then 1
}
// Мама налила чай
// ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:налить{}.<OBJECT>существительное:*{ падеж:вин <в_класс>существительное:напиток{} } }
then 1
}
// Оля съела пюре
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:съесть{}.<OBJECT>существительное:*{ падеж:вин <в_класс>существительное:еда{} } }
then 1
}
// испросить разрешения
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:испросить{}.<OBJECT>*:*{ падеж:род одуш:неодуш } }
then 3
}
// наделать в решении ошибок
// ^^^^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:наделать{}.<OBJECT>существительное:*{ падеж:род } }
then 2
}
// дракон смотрит вслед человеку.
// ^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.предлог:вслед{}.*:*{ падеж:дат } }
then 1
}
// нажимать на все кнопки
// ^^^^^^^^ ^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:нажимать{}.предлог:на{}.существительное:*{ одуш:неодуш падеж:вин } }
then 1
}
// предикатив МОЖНО обычно присоединяет только одушевленный дательный агенс:
// на этой удивительно четкой фотографии можно увидеть рассеянное скопление
// ~~~~~~~~~~ ^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:можно{}.<SUBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ } }
then -2
}
// поэтому - очень легкий спуск
tree_scorer ВалентностьПредиката language=Russian
{
if context { '-'.<ATTRIBUTE>наречие:очень{} }
then -10
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { '–'.<ATTRIBUTE>наречие:очень{} }
then -10
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { '—'.<ATTRIBUTE>наречие:очень{} }
then -10
}
// Мужчина, взявший в заложники пожарных в США, убит при штурме
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:взять{}.{
<OBJECT>*:*{ падеж:вин }
предлог:в{}.*:*{ падеж:им }
}
}
then 2
}
// отчего же получается такая разница?
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { глагол:получаться{1}.{
прилагательное:*{2 падеж:им }
<SUBJECT>*:*{ 3 }
}
}
then -2
}
// отчего же получилась такая разница?
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { глагол:получиться{1}.{
прилагательное:*{2 падеж:им }
<SUBJECT>*:*{ 3 }
}
}
then -2
}
// черный кожаный костюм делал его почти невидимым
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:делать{}.{
<OBJECT>*:*{ падеж:вин }
прилагательное:*{ падеж:твор }
}
}
then 1
}
// Общее правило для глаголов - два наречия подряд прикрепляются
// достаточно редко.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.@sequence_pos(НАРЕЧИЕ) }
then -1
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.@sequence_pos(НАРЕЧИЕ) }
then -1
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { деепричастие:*{}.@sequence_pos(НАРЕЧИЕ) }
then -1
}
// как это все объяснить?
// ^^^^^^^^^^^
tree_scorer language=Russian generic
{
if context { наречие:как{1}.местоим_сущ:все{} }
then -1
}
tree_scorer language=Russian
{
if context { наречие:как{1}.местоим_сущ:это{} }
then -1
}
// *******************************************************************************
// Подавляем одновременное присоединение винительного и родительного дополнения
//
// я буду ждать результаты проверки
// ^^^^^^^^^^^^^^^^^^^^^^^^^
// *******************************************************************************
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:род }
}
}
then -10
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:парт }
}
}
then -10
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{}.{
<OBJECT>*:*{ падеж:род }
<OBJECT>*:*{ падеж:парт }
}
}
then -10
}
// ------------------------------------------------------
// Немного придавим использование прилагательного в роли
// творительного дополнения:
// нога жреца коснулась первой ступеньки.
// ^^^^^^
wordentry_set ГлаголыСвязки=
{
rus_verbs:остаться{}, // вроде бы их количество осталось прежним.
rus_verbs:оставить{}, // дверь туда оставим открытой.
rus_verbs:оставлять{},
rus_verbs:оставаться{},
rus_verbs:становиться{},
rus_verbs:стать{},
rus_verbs:представляться{}, // оно всегда представлялось ей пронзительно голубым.
rus_verbs:притвориться{},
rus_verbs:притворяться{},
rus_verbs:прикинуться{},
rus_verbs:прикидываться{},
rus_verbs:делаться{},
rus_verbs:объявить{},
rus_verbs:объявлять{},
rus_verbs:назвать{},
rus_verbs:называть{},
rus_verbs:являться{},
rus_verbs:казаться{},
rus_verbs:оказаться{},
rus_verbs:показаться{},
rus_verbs:быть{},
rus_verbs:бывать{},
rus_verbs:найти{}, // Он был найден виновным.
rus_verbs:сделаться{}
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{ ~ГлаголыСвязки }.<OBJECT>прилагательное:*{ падеж:твор } }
then -2
}
// Желать вам всем удачи
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { *:*{ ~ГлаголыСвязки }.<OBJECT>местоим_сущ:всё{ падеж:твор } }
then -2
}
// ------------------------------------------------------
// забористый бас Константина делал его легко узнаваемым
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:делать{}.<OBJECT>прилагательное:*{ падеж:дат }
}
then -2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сделать{}.<OBJECT>прилагательное:*{ падеж:дат }
}
then -2
}
// ------------------------------------------------------
// злодей схватил нож и несколько раз всадил его оппоненту в спину
// ^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:всадить{}.{
<OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН}
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
}
}
then 1
}
// ------------------------------------------------------
// Обычно глагол не может одновременно присоединять и винительный,
// и родительный падеж, но некоторые глаголы - могут:
// это может лишить наше общество работы
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:лишить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД }
}
}
then 12
}
// ------------------------------------------------------
// она обхватила его руками за шею
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обхватить{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
<OBJECT>*:*{ ПАДЕЖ:ТВОР }
}
}
then 1
}
// ------------------------------------------------------
// Подавляем для модального ХОТЕТЬ присоединение дополнений,
// когда присоединен инфинитив:
// ты это хотел мне рассказать?
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:хотеть{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } } then -10 }
// ------------------------------------------------------
// Однако их ярость уступила место страху
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:уступить{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:дат }
}
}
then 1
}
// --------------------------------------------------------------
// глагол ПОМОЧЬ обычно присоединяет дательную валентность.
// мне надо им помочь
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:помочь{}.[not]<OBJECT>*:*{ падеж:дат } } then -2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:помогать{}.[not]<OBJECT>*:*{ падеж:дат } } then -2 }
// -------------------------------
// злодей схватил нож и несколько раз всадил его оппоненту в спину
tree_scorer ВалентностьСложнСказ language=Russian
{
if context { rus_verbs:всадить{}.{
<OBJECT>НеодушОбъект{ падеж:вин }
<OBJECT>ОдушОбъект{ падеж:дат }
}
}
then 1
}
// ------------------------------------
// за деревьями леса не видеть
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеть{}.{
частица:не{}
<OBJECT>*:*{ падеж:род }
}
}
then 1
}
// ------------------------------------
// Подавляем компаратив наречия справа от ОКАЗАТЬСЯ, если
// у глагола есть прямое дополнение:
// эта задача оказалась гораздо легче первой.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:оказаться{}.{
наречие:*{ степень:сравн }
*:*{ падеж:твор }
}
}
then -10
}
// ----------------------------------------------
// Обычно рассказывают либо ЧТО-ТО, либо о ЧЕМ-ТО
// Набив рот, он попросил ее рассказать о вторжении.
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рассказать{}.{
*:*{ падеж:вин }
предлог:о{}
}
}
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:рассказать{}.{
*:*{ падеж:род }
предлог:о{}
}
}
then -5
}
// Набив рот, он попросил ее рассказать о вторжении.
// ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:попросить{}.{
инфинитив:*{}
предлог:о{}
}
}
then -5
}
// Предприниматели ФРГ выступают за добычу сланцевого газа
// ^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:выступать{2}.<OBJECT>*:*{ 1 падеж:твор } } then -2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:выступать{}.<OBJECT>*:*{ падеж:твор <в_класс>существительное:страна{} } } then -2 }
// Обычно ВОСПОЛЬЗОВАТЬСЯ имеет заполненный слот творительного дополнения:
// этим мгновением надо было воспользоваться
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:воспользоваться{}.<OBJECT>*:*{ падеж:твор } } then 2 }
// откуда ее черт принес?
// Откуда её ветер принёс?
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:принести{}.{
<SUBJECT>*:*{}
<OBJECT>*:*{ падеж:вин }
}
}
then 1
}
// ей доводилось встречать эти существа
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:доводилось{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 3
}
// Есть у нас в лесу место
tree_scorer ВалентностьГлагола language=Russian
{
if context { 'есть'{ class:инфинитив }.предлог:у{} }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заняться{}.<OBJECT>*:*{ падеж:твор } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:заниматься{}.<OBJECT>*:*{ падеж:твор } }
then 1
}
// Майкл способен попасть в кольцо с десятиметровой дистанции пять раз подряд
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:попасть{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:попадать{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
// Я спустил собаку с цепи.
// ^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спустить{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спускать{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
// Гоша опустил ногу со стола.
// ^^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:опустить{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:опускать{}.предлог:с{}.*:*{ ПАДЕж:РОД } } then 2 }
// тебе доводилось использовать силы магии против другого человека?
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:использовать{ вид:соверш }.предлог:против{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { глагол:использовать{ вид:несоверш }.предлог:против{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { инфинитив:использовать{ вид:соверш }.предлог:против{} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { инфинитив:использовать{ вид:несоверш }.предлог:против{} } then 2 }
// лесом от него пахло
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:пахнуть{ вид:несоверш }.предлог:от{} }
then 2
}
// Дождь должен смыть всю пыль с листьев.
// ^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:смыть{}.предлог:с{}.*:*{ падеж:род} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:смывать{}.предлог:с{}.*:*{ падеж:род} } then 2 }
// он смел крошки со стола
// ^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:смести{}.предлог:с{}.*:*{ падеж:род} } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:сметать{}.предлог:с{}.*:*{ падеж:род} } then 2 }
// Мальчики съехали на санках с горы.
// ^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:съехать{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:съезжать{}.предлог:с{}.*:*{ падеж:род } } then 2 }
// Дети бросались в воду с моста
// ^^^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:броситься{}.предлог:с{}.*:*{ падеж:род } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:бросаться{}.предлог:с{}.*:*{ падеж:род } } then 2 }
// отнестись к животным с сочуствием
// ^^^^^^^^^ ^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:отнестись{}.предлог:с{}.*:*{ падеж:твор } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:относиться{}.предлог:с{}.*:*{ падеж:твор } } then 2 }
// Элис разинула от удивления рот.
// ^^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:разинуть{}.НеодушОбъект{ падеж:вин } } then 2 }
// --------------------------------------
// ВЛЮБЛЯТЬСЯ В КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбляться{}.предлог:в{}.*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбляться{}.предлог:в{}.существительное:*{ одуш:одуш падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбляться{}.предлог:в{}.существительное:*{ падеж:вин <в_класс>существительное:имя{} } } then 3 }
// --------------------------------------
// ВЛЮБИТЬСЯ В КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбиться{}.предлог:в{}.*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбиться{}.предлог:в{}.существительное:*{ одуш:одуш падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:влюбиться{}.предлог:в{}.существительное:*{ падеж:вин <в_класс>существительное:имя{} } } then 3 }
// --------------------------------------
// ВТЮРИТЬСЯ В КОГО-ТО
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:втюриться{}.предлог:в{}.*:*{ падеж:вин } } then 1 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:втюриться{}.предлог:в{}.существительное:*{ одуш:одуш падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:втюриться{}.предлог:в{}.существительное:*{ падеж:вин <в_класс>существительное:имя{} } } then 3 }
// ------------------------------------------------
// **** Глаголы перемещения с топонимами ****
tree_scorers ЛюбойТопонимНеизв
// для неизвестных топонимов
tree_scorer ЛюбойТопонимНеизв language=Russian
{
if context { существительное:???{ charcasing:FirstCapitalized } }
then 1
}
tree_scorer ЛюбойТопонимНеизв language=Russian
{
if context { существительное:*{ <в_класс>существительное:страна{} } }
then 1
}
tree_scorer ЛюбойТопонимНеизв language=Russian
{
if context { существительное:*{ <в_класс>существительное:город{} } }
then 1
}
// +++++
// для слов типа ТАКСИ
tree_scorers ЛюбойТранспорт
tree_scorer ЛюбойТранспорт language=Russian
{
if context { существительное:*{ <в_класс>существительное:транспорт{} } }
then 1
}
// +++++
tree_scorers ЛюбойЧеловек
tree_scorer ЛюбойЧеловек language=Russian
{
if context { существительное:*{ <в_класс>существительное:профессия{} } }
then 1
}
tree_scorer ЛюбойЧеловек language=Russian
{
if context { существительное:*{ <в_класс>существительное:имя{} } }
then 1
}
// +++++
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:улететь{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:улететь{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 }
// ++++
// он уехал в Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:уехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// он уехал в такси
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:уехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 }
// ++++
// Мы эмигрировали в США
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:эмигрировать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Виктор перебрался в Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:перебраться{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Мафиози сбежали из Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:сбежать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Они едут в Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:ехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// мы ехали в такси
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:ехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 }
// ++++
// туристы поехали в Киото
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:предл } } then -10 }
// группа туристов поехала в такси
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:предл } } then 2 }
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поехать{}.предлог:в{}.ЛюбойТранспорт{ падеж:вин } } then -10 }
// ++++
// Люси отправилась в Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:отправиться{}.предлог:в{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Мы посетили Киото
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:посетить{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// путешественники посещали Киото
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:посещать{}.ЛюбойТопонимНеизв{ падеж:вин } } then 2 }
// ++++
// Мы спросили Людмилу Ивановну
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спросить{}.ЛюбойЧеловек{ падеж:вин } } then 2 }
// Дети спросили совет у учителя
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спросить{}.предлог:у{}.ЛюбойЧеловек{ падеж:род } } then 2 }
// ++++
// Дети спрашивают медсестру
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спрашивать{}.ЛюбойЧеловек{ падеж:вин } } then 2 }
// Дети спрашивают совет у учителя
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:спрашивать{}.предлог:у{}.ЛюбойЧеловек{ падеж:род } } then 2 }
// ++++
// мы поинтересовались ответом у учительницы
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:поинтересоваться{}.предлог:у{}.ЛюбойЧеловек{ падеж:род } } then 2 }
// ++++
// Вдалеке мы увидели Токио
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:увидеть{}.*:*{ падеж:вин } } then 1 }
// ++++
// Справа вы видите Киото
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:видеть{}.*:*{ падеж:вин } } then 1 }
// ++++
//
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:построить{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++
//
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:строить{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++
//
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:создать{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++
//
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:создавать{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:обмениваться{}.*:*{ падеж:твор } } then 1 }
// ++++
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:обменяться{}.*:*{ падеж:твор } } then 1 }
// +++++
// Элис разинула от удивления рот.
// ^^^^^^^^ ^^^
tree_scorer ВалентностьГлагола language=Russian
{ if context { rus_verbs:разинуть{}.НеодушОбъект{ падеж:вин } } then 1 }
// ++++++
// Я покажу тебе, как надо мной смеяться!
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смеяться{}.местоимение:*{ падеж:твор } }
then -5
}
// ++++++++++
// плыть ей пришлось долго.
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:пришлось{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:плыть{}.местоимение:*{ падеж:твор } }
then -5
}
// ++++++++++
// все остальное тебе тоже удалось устроить?
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:удалось{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// +++++++++++++++
// Это событие является одним из элементов широко задуманной акции.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:являться{}.'одним'{ падеж:твор }.'из' }
then 2
}
// +++++++++++++++
// вот кого мне нужно было искать!
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:нужно{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// +++++++++++++++++
// им надо видеть движение.
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:надо{}.{
<SUBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 2
}
// +++++++++++++++++
// но прежде нам необходимо найти тело
tree_scorer ВалентностьПредиката language=Russian
{
if context { безлич_глагол:необходимо{2}.{
<SUBJECT>*:*{ падеж:дат 1 }
инфинитив:*{3}
}
}
then 4
}
// +++++++++++++++++
// мимо тебя пройти невозможно
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:пройти{}.{
наречие:мимо{}
<OBJECT>*:*{ падеж:вин }
}
}
then -10
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:пройти{}.{
наречие:мимо{}
<OBJECT>*:*{ падеж:род }
}
}
then -10
}
// +++++++++++++++++
// Сегодня я буду читать дома
// ^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:читать{}.{
<OBJECT>существительное:*{ <в_класс> СУЩЕСТВИТЕЛЬНОЕ:СТРОЕНИЕ{} }
}
}
then -10
}
// +++++++++++++++++
// Она ослепила его своей красотой.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:ослепить{}.{
<OBJECT>*:*{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
// +++++++++++++++++++
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:слышать{}.<OBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then 2
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:слышать{}.<SUBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:услышать{}.<OBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then 2
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:услышать{}.<SUBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:расслышать{}.<OBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then 2
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:расслышать{}.<SUBJECT>существительное:*{ <в_класс>существительное:звук{} } }
then -5
}
// +++++++++++++++++++++++++
/*
// пища помогла мне окончательно прогнать сон
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:помочь{}.{
<SUBJECT>*:*{}
<OBJECT>*:*{ падеж:дат }
инфинитив:*{}
}
}
then 5
}
*/
// +++++++++++++++++
// Немного повысим достоверность императива в случае,
// когда предложение оканчивается восклицательным знаком:
// держите ее за ноги!
tree_scorer language=Russian
{
if context { глагол:*{ наклонение:побуд }.'!' }
then 1
}
// - А яичницу любите?
tree_scorer language=Russian
{
if context { глагол:*{ наклонение:побуд }.'?' }
then -4
}
// +++++++++++++++++
// Страх охватил Грегори
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:охватить{}.{
<SUBJECT>существительное:*{ одуш:неодуш <в_класс>существительное:эмоция{} }
<OBJECT>*:*{ падеж:вин }
}
}
then 5
}
// ++++++++++++++++++
// какие тут могут быть секреты?
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:мочь{}.{
инфинитив:*{}
<OBJECT>*:*{ падеж:вин }
}
}
then -100
}
// +++++++++++++++++
// В Ульяновской области детей обстреляли из пневматики
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обстрелять{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// +++++++++++++++++
// теперь вы все знаете
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.<OBJECT>'все'{ падеж:вин } }
then 2
}
// +++++++++++++++++
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:предложить{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } }
then 6
}
// +++++++++++++++++
// Мы велели ей убраться из комнаты
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:велеть{}.{ <OBJECT>*:*{ падеж:дат } инфинитив:*{} } }
then 6
}
// +++++++++++++++++
// Обычно глагол БЫТЬ не присоединяет прямое дополнение в винительном падеже:
// Это будет аварийный запас.
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.<OBJECT>*:*{ падеж:вин } }
then -5
}
// в этом кафе будут они
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{}.{
<SUBJECT>местоимение:*{ падеж:им }
<RHEMA>*:*{ одуш:неодуш падеж:им }
}
}
then -3
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{}.{
<RHEMA>местоимение:*{ падеж:им }
<SUBJECT>существительное:*{ одуш:неодуш падеж:им }
}
}
then -3
}
// Компаратив наречия для БЫТЬ/БЫВАТЬ подавляем
// она была старше меня
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.<RHEMA>наречие:*{ степень:сравн } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:бывать{}.<RHEMA>наречие:*{ степень:сравн } }
then -5
}
// +++++++++++++++++
// Глаголы, синонимичные ЗАПЕРЕТЬ - подавляем вариант, когда подлежащим становится
// существительное из класса ЗДАНИЕ:
// запер сарай
// ^^^^^^^^^^^^
#define ЗаперетьЗдание(v) \
#begin
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:v{}.<SUBJECT>существительное:*{ <в_класс>существительное:здание{} } }
then -100
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:v{}.<SUBJECT>существительное:*{ <в_класс>существительное:здание{} } }
then -100
}
#end
ЗаперетьЗдание(запереть)
ЗаперетьЗдание(запирать)
ЗаперетьЗдание(закрыть)
ЗаперетьЗдание(закрывать)
ЗаперетьЗдание(открыть)
ЗаперетьЗдание(открывать)
// +++++++++++++++++
// она несла на плечах своего мужа.
// ^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:нести{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then 1
}
// +++++++++++++++++++++
// И была опасность, что когда-нибудь откажет дыхательный аппарат.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отказать{}.<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then -2
}
// ++++++++++++++++++++++
// Ты знаешь, что на следующий день должен был приехать мой муж.
// ^^^ ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:должный{}.{
<OBJECT>*:*{ ПАДЕЖ:ВИН }
инфинитив:*{}
}
}
then -100
}
// Двое гонцов из Мурманска должны были прибыть ночным поездом.
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:должный{}.{
<OBJECT>*:*{ ПАДЕЖ:РОД }
инфинитив:*{}
}
}
then -100
}
// ++++++++++++++++++++++
// чувашскими законотворцами был взят проект Федерального закона
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { прилагательное:*{ КРАТКИЙ СТРАД ПРИЧАСТИЕ }.<OBJECT>*:*{ падеж:род } }
then -5
}
// ++++++++++++++++++++++
// ружье его было тут
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.'его'{ class:прилагательное } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.'ее'{ class:прилагательное } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.'их'{ class:прилагательное } }
then -5
}
// +++++++++++++++++++++++++++
// его отучают пить из-под крана
tree_scorer language=Russian
{
if context { инфинитив:*{}.
<LEFT_AUX_VERB>глагол:отучать{}.
ОдушОбъект{ ПАДЕж:ВИН } }
then 2
}
// +++++++++++++++++++++++++++++++
// Смелость города берёт
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:брать{}.<OBJECT>существительное:*{ падеж:вин } }
then 1
}
// --------------------------------
// это открытие его удивило
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:удивить{}.<OBJECT>ОдушОбъект{ падеж:вин } }
then 2
}
// ++++++++++++++++++++++++++++++++++++++++++++
// Ветерок был приятным
// ^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:быть{}.{
thema=<SUBJECT>*:*{}
rhema=<RHEMA>прилагательное:*{}
}
}
then adj_noun_score(rhema,thema)
}
// Выбор фруктов слаб
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { a=прилагательное:*{ КРАТКИЙ}.n=<SUBJECT>СУЩЕСТВИТЕЛЬНОЕ:*{}
}
then adj_noun_score(a,n)
}
// Воздух становился всё холоднее
// ^^^^^^ ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:становиться{}.{
thema=<SUBJECT>*:*{}
rhema=прилагательное:*{}
}
}
then adj_noun_score(rhema,thema)
}
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:стать{}.{
thema=<SUBJECT>*:*{}
rhema=прилагательное:*{}
}
}
then adj_noun_score(rhema,thema)
}
// -----------------------------------
#define VerbInstr(v,w) \
#begin
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:v{}.<OBJECT>существительное:*{ падеж:твор } }
then w
}
#end
VerbInstr(ограничиться,2)
VerbInstr(интересоваться,2)
VerbInstr(заинтересоваться,2)
VerbInstr(поинтересоваться,2)
VerbInstr(пренебрегать,2)
VerbInstr(пренебречь,2)
VerbInstr(увенчаться,2)
// ----------------------------------
// Все звали ее Верочкой...
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:звать{}.{
<OBJECT>ОдушОбъект{ ПАДЕЖ:ВИН }
<OBJECT>существительное:*{ ПАДЕЖ:ТВОР }
}
}
then 2
}
// ----------------------------------
/*
wordentry_set ПредлогНаправления = предлог:{ на, в, под, через }
// дракону на спину сел
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ ~ПАДЕЖ:ДАТ }.{
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
<PREPOS_ADJUNCT>ПредлогНаправления.*:*{ ПАДЕЖ:ВИН }
}
}
then 8
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{ ~ПАДЕЖ:ДАТ }.{
<OBJECT>*:*{ ПАДЕЖ:ДАТ }
<PREPOS_ADJUNCT>ПредлогНаправления.*:*{ ПАДЕЖ:ВИН }
}
}
then 8
}
*/
// -----------------------------------
// Официант денег не взял.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:взять{}.{
частица:не{}
<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД }
}
}
then 2
}
// ----------------------------------
// эти последние энергично пошли им навстречу.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пойти{}.послелог:навстречу{}.*:*{ падеж:дат } }
then 5
}
// Он сделал шаг ей навстречу.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сделать{}.{ <OBJECT>НеодушОбъект{ ПАДЕЖ:ВИН } послелог:навстречу{}.*:*{ падеж:дат } } }
then 5
}
// ---------------------------------
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:объявить{}.{
<OBJECT>*:*{ падеж:вин }
предлог:о{}
}
}
then -100
}
// ----------------------------------
// именно поэтому она собиралась предложить им очень простой выбор.
// ^^^^^^^^^^ ^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:предложить{}.{
<OBJECT>*:*{ падеж:дат }
<OBJECT>*:*{ падеж:вин }
}
}
then 5
}
// -----------------------------------------------
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:править{}.<OBJECT>существительное:*{ <в_класс>существительное:страна{} ПАДЕЖ:ТВОР } }
then 5
}
// ----------------------------------
// мы уже начали за вас волноваться.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:волноваться{}.предлог:за{}.*:*{ падеж:вин } }
then 5
}
// ----------------------------------
// ей следовало бы проверить зрение.
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:следует{}.{ *:*{ падеж:дат } инфинитив:*{} } }
then 2
}
// ----------------------------------
// как легко превратить в кляксу живого человека
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:превратить{}.{ <OBJECT>*:*{ падеж:вин } предлог:в{}.*:*{ падеж:вин } } }
then 2
}
// ----------------------------------
// мне надо было встать
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.{
БезличСвязка0
безлич_глагол:*{ ~ТИП_ПРЕДИКАТИВ:БЫЛО_СВЯЗКА }
}
}
then -5
}
// ----------------------------------
// Уточняем согласование подлежащего и
// атрибута для связочных глаголов:
//
wordentry_set СвязочныеГлаголы=
{
rus_verbs:стать{},
rus_verbs:становиться{},
rus_verbs:быть{},
rus_verbs:бывать{},
rus_verbs:оказаться{},
rus_verbs:оказываться{},
rus_verbs:получиться{},
rus_verbs:получаться{}
}
// Он может стать главным
// ^^ ^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { СвязочныеГлаголы.{
sbj=<SUBJECT>*:*{ ЧИСЛО:ЕД }
прилагательное:*{ ПАДЕЖ:ТВОР ЧИСЛО:ЕД ~КРАТКИЙ !=sbj:РОД }
} }
then -2
}
// Ты можешь стать главным
// ^^ ^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { СвязочныеГлаголы.{
sbj=<SUBJECT>местоимение:я{ ЧИСЛО:ЕД ~лицо:3 }
прилагательное:*{ ПАДЕЖ:ТВОР ЧИСЛО:ЕД ~КРАТКИЙ РОД:СР }
} }
then -2
}
// ----------------------------------
#define НеГлагРодЕд(v,n,w) \
#begin
tree_scorer ВалентностьГлагола language=Russian
{
if context {
rus_verbs:v{}.{
частица:не{}
<OBJECT>существительное:n{ падеж:род число:ед }
}
} then w
}
#end
// Америка не имеет права вмешиваться во внутренние дела России
// ^^^^^^^^^^^^^^
НеГлагРодЕд(иметь,право,2)
// Ни один прокурор такого разрешения не даст.
НеГлагРодЕд(дать,разрешение,8)
// ----------------------------------
// Надежде приходилось, чтобы успеть вставить свои ответы между его репликами, произносить слова со скоростью пулеметной очереди.
tree_scorer ВалентностьГлагола language=Russian
{
if context { безлич_глагол:приходится{}.инфинитив:*{ вид:несоверш } }
then 2
}
// ----------------------------------
// Мы внедрили в его организацию соглядатая
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:внедрить{}.существительное:*{ падеж:вин } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:внедрять{}.существительное:*{ падеж:вин } }
then 1
}
// ----------------------------------
// Основание качнулось, зажатое манипуляторами.
// ^^^^^^^^^ ^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:*{}.{
n3=<SUBJECT>*:*{}
<SEPARATE_ATTR>*:*{ ПАДЕЖ:ИМ =n3:РОД =n3:ЧИСЛО }
} }
then 2
}
// День выдался ненастный.
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { *:*{}.{ sbj=<SUBJECT>существительное:*{} attr=<SEPARATE_ATTR>прилагательное:*{ ПАДЕЖ:ИМ =sbj:РОД =sbj:ЧИСЛО } } }
then adj_noun_score(attr,sbj)
}
// Такое было удовольствие!
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:быть{}.{
n3=<SUBJECT>*:*{}
attr=<SEPARATE_ATTR>*:*{ ПАДЕЖ:ИМ =n3:РОД =n3:ЧИСЛО }
} }
then adj_noun_score(attr,n3)
}
// Ответы я давал самые несуразные.
// ^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { глагол:*{}.{
n3=<OBJECT>*:*{}
<SEPARATE_ATTR>*:*{ =n3:ПАДЕЖ =n3:РОД =n3:ЧИСЛО }
} }
then 2
}
// ------------------------------------------------------------------
// Некоторые модальные редко употребляются без инфинитива:
// Разве можно в такую погоду как следует настроиться на мысль о преступлении?
// ^^^^^
wordentry_set МодальныеТребуютИнф=
{
безлич_глагол:можно{},
безлич_глагол:хочется{},
безлич_глагол:захотелось{},
глагол:мочь{},
глагол:смочь{}
}
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.<LEFT_AUX_VERB>МодальныеТребуютИнф }
then 7
}
// -------------------------------------------
// а им уже приходилось умирать вместе
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.{ <SUBJECT>местоимение:*{ падеж:дат } безлич_глагол:*{ МОДАЛЬНЫЙ } } }
then 1
}
// Ей вдруг захотелось закричать от разочарования.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.{ <OBJECT>"ей"{ падеж:твор } безлич_глагол:*{ МОДАЛЬНЫЙ } } }
then -2
}
// Ей было приятно думать об этом.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{}.{ <OBJECT>"ей"{ падеж:твор } } }
then -1
}
// ------------------------------------------------------
// им давно пора уходить.
wordentry_set БезличнМодальн=безлич_глагол:{ пора, надо, нужно }
tree_scorer ВалентностьПредиката language=Russian generic
{
if context { инфинитив:*{}.{ *:*{ падеж:дат } БезличнМодальн } }
then 1
}
// -------------------------------------------------------
// у нас мало времени!
tree_scorer ВалентностьПредиката language=Russian
{
if context { СчетнСвязка.{ предлог:у{} существительное:время{ падеж:род } } }
then 10
}
// ----------------------------------------------
// ЕСЛИ не сочетается с императивом:
// - Не объясняйте, если не хотите.
// ^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ наклонение:побуд }.'если' }
then -10
}
// --------------------------------------------
// Частица НЕТ не всегда выполняет роль предикатива, иногда
// она выступает в роли вводной частицы, аналогично ДА:
// - Нет, вы не понимаете.
// ^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { частица:нет{}.[not]<OBJECT>*:*{} }
then -2
}
// ---------------------------------------------
// Позади никого не было.
// ^^^^^^^^^^^^^^
// Пыли не было
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{ наклонение:изъяв число:ед род:ср время:прошедшее }.{ частица:не{} <OBJECT>*:*{ ПАДЕЖ:РОД } } }
then 4
}
// Радости не было предела
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{ наклонение:изъяв число:ед род:ср время:прошедшее }.
{
частица:не{}
<OBJECT>НеодушОбъект{ ПАДЕЖ:ДАТ }
<OBJECT>'предела'{ ПАДЕЖ:РОД }
}
}
then 6
}
// ---------------------------------------------
wordentry_set ОтрицМестоим = местоим_сущ:{ никто, ничто }
// Местоимение НИЧТО и НИКТО в косвенных падежах обычно прикрепляются
// только к глаголу с частией НЕ:
//
// Стояла ничем не нарушаемая тишина.
// ~~~~~~ ^^^^^ ^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.{ [not]частица:не{} <OBJECT>ОтрицМестоим{} } }
then -5
}
// -------------------------------------------------------
// Я имею на это право.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:иметь{}.{ <OBJECT>существительное:право{ ПАДЕЖ:ВИН } <PREPOS_ADJUNCT>предлог:на{}.*:*{ ПАДЕЖ:ВИН } } }
then 1
}
// Они, должно быть, спустились с горы.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:спуститься{}.предлог:с{}.*:*{ падеж:вин } }
then -5
}
// ------------------------------------------------------------
// наконец усталость дала о себе знать.
// ^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:знать{}.rus_verbs:дать{} }
then 2
}
// ------------------------------------------------------------
// Но никто не обращал на них внимания.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:обращать{}.предлог:на{}.*:*{ ПАДЕЖ:ПРЕДЛ } }
then -1
}
// распространяться по территории штата
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:распространяться{}.предлог:по{}.*:*{ ПАДЕЖ:ВИН } }
then -1
}
// я собираюсь с тобой в прятки поиграть
// ^^^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:поиграть{}.предлог:в{}.'прятки'{ ПАДЕЖ:ВИН } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:играть{}.предлог:в{}.'прятки'{ ПАДЕЖ:ВИН } }
then 1
}
// бежать, повалявшись в снегу, обратно в тепло
// ^^^^^^ ^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бежать{}.предлог:в{}.*:*{ ПАДЕЖ:ВИН ОДУШ:НЕОДУШ } }
then 1
}
// Ты сама ко мне лезла!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:лезть{}.предлог:к{}.*:*{ ПАДЕЖ:ДАТ } }
then 1
}
// В действительности же дело обстояло не так.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:обстоять{}.<SUBJECT>существительное:дело{} }
then 1
}
// Тем дело пока и кончилось.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:кончиться{}.{ <SUBJECT>существительное:дело{} <OBJECT>*:*{ ПАДЕЖ:ТВОР } } }
then 1
}
// На этом дело и кончилось.
// ^^^^ ^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:кончиться{}.<SUBJECT>существительное:дело{} }
then 1
}
// В действительности же дело обстояло не так.
// ^^^^ ^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:обстоять{}.<SUBJECT>существительное:дело{} }
then 1
}
// Озеленение на этом не закончится.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:закончиться{}.предлог:на{}.*:*{ ПАДЕЖ:ПРЕДЛ } }
then 1
}
// Ты что-то от меня скрываешь?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:скрывать{}.предлог:от{}.ОдушОбъект{ ПАДЕЖ:РОД } }
then 1
}
// мы будем атаковать
// ^^^^^^^^^^^^^^^
tree_scorer ГлагИнф language=Russian generic
{
if context { инфинитив:*{ ВИД:СОВЕРШ }.МодальныеТолькоНесоверш }
then -100
}
// Ужин был подан, и все сели за стол.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сесть{}.предлог:за{}.существительное:стол{} }
then 1
}
// Ты совсем отстал от жизни.
// ^^^^^^ ^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отстать{}.предлог:от{} }
then 2
}
// Тут есть над чем задуматься
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:задуматься{}.предлог:над{} }
then 2
}
// Пора было положить этому конец.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:положить{}.{ <OBJECT>существительное:конец{ ПАДЕЖ:ВИН } <OBJECT>*:*{ ПАДЕЖ:ДАТ } } }
then 2
}
// Задержать преступников по горячим следам милиционерам не удалось.
// ^^^^^^^^^ ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:задержать{}."по"."горячим"."следам" }
then 4
}
// ----------------------------
// Особо обрабатываем ситуацию с появлением РОДИТЕЛЬНОЙ валентности в случае,
// когда модальный глагол стоит в отрицательной форме:
//
// Ломать вы ничего не хотите.
// ^^^^^^ ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { инфинитив:*{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПАДЕЖ:ВИН }
.{
<LEFT_AUX_VERB>глагол:*{}.<NEGATION_PARTICLE>частица:не{}
<OBJECT>*:*{ ПАДЕЖ:РОД }
}
}
then 3
}
// ----------------------------------------
// Они не хотят ее знать.
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:знать{}.{ <LEFT_AUX_VERB>глагол:хотеть{} } }
then 5
}
// Никому до тебя нет дела
tree_scorer ВалентностьПредиката language=Russian
{
if context { частица:нет{}.{ <OBJECT>'дела'{ падеж:род } <PREPOS_ADJUNCT>предлог:до{} } }
then 5
}
// Я не удостоил Ее ответом.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:удостоить{}.{ <OBJECT>*:*{ ПАДЕЖ:ДАТ } <OBJECT>'ответом' } }
then 2
}
// -----------------------------------------------
// Горю родителей нет предела.
tree_scorer ВалентностьПредиката language=Russian
{
if context { частица:нет{}.{ <OBJECT>'предела'{ падеж:род } *:*{ ПАДЕЖ:ДАТ } } }
then 5
}
// -----------------------------------------
// Он весь день провел со мной!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:провести{}.{ <OBJECT>'день'.'весь' <PREPOS_ADJUNCT>предлог:с{}.*:*{ падеж:твор } } }
then 4
}
// Рабочие день и ночь трудятся.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:трудиться{}.<ATTRIBUTE>'день'.'и'.'ночь' }
then 2
}
wordentry_set СчетныеНаречия=наречие:{ мало, немало, много, немного, маловато, многовато }
// Но и этого будет мало.
// ^^^^^^^^^^^^^^^^
// Контрпример:
// Несколько мгновений все было тихо.
// ~~~~~~~~~ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.{ <OBJECT>*:*{ падеж:род } <ATTRIBUTE>СчетныеНаречия } }
then 5
}
// Шуму было много, однако гора родила мышь.
// ^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:быть{}.{ <OBJECT>*:*{ падеж:парт } <ATTRIBUTE>СчетныеНаречия } }
then 5
}
// Я не удостоил Ее ответом.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:удостоить{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>'ответом' } }
then 2
}
word_set ЕеЕгоИхОбъект = { 'ее', 'его', 'их' }
// Аня неумело стиснула ее зубами.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ ПАДЕЖ:ВИН ~ПАДЕЖ:ТВОР }.
{
<OBJECT>ЕеЕгоИхОбъект{ падеж:вин }
<OBJECT>*:*{ падеж:твор }
}
}
then 2
}
// Орлиц в поле зрения не оказалось.
// ^^^^^^^^^^^^^ ^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { rus_verbs:оказаться{}.<PREPOS_ADJUNCT>предлог:в{}.'поле'{ РОД:СР ПАДЕЖ:ПРЕДЛ }.'зрения' }
then 2
}
// Я пересекла двор и села рядом с ней.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сесть{}.<PREPOS_ADJUNCT>предлог:с{}.<ATTRIBUTE>наречие:рядом{} }
then 2
}
// Я всегда стою, обучая кого-то.
// ^^ ^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:стоить{}.<SUBJECT>местоимение:я{ лицо:1 } }
then -2
}
// Окончив первый, принялся за второй.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приняться{}.<PREPOS_ADJUNCT>предлог:за{}.*:*{ ПАДЕЖ:ТВОР } }
then -2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приниматься{}.<PREPOS_ADJUNCT>предлог:за{}.*:*{ ПАДЕЖ:ТВОР } }
then -2
}
// Оставшихся в живых они же заперли в резервациях.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:остаться{}.<PREPOS_ADJUNCT>предлог:в{}.'живых' }
then 2
}
// Ворованные автомобили злоумышленники разбирали на запчасти и продавали.
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разбирать{}.<PREPOS_ADJUNCT>предлог:на{}.существительное:*{ падеж:вин одуш:неодуш } }
then 2
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разобрать{}.<PREPOS_ADJUNCT>предлог:на{}.существительное:*{ падеж:вин одуш:неодуш } }
then 2
}
// Белолобый неприязненно смерил его взглядом.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смерить{}.{ <OBJECT>*:*{ падеж:вин } <OBJECT>'взглядом' } }
then 2
}
// Безмерно нибелунги о Зигфриде грустили.
// ^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:грустить{}.<PREPOS_ADJUNCT>предлог:о{}.<OBJECT>*:*{ падеж:предл } }
then 1
}
// Блондин потащил девчонку к двери;
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:потащить{}.<PREPOS_ADJUNCT>предлог:к{} }
then 1
}
// Сняв шляпу, Рэнналф прибавил шагу.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прибавить{}.<OBJECT>'шагу'{ падеж:парт } }
then 3
}
// Хвалю я ее за это?
// ^^^^^ ^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:хвалить{}.<PREPOS_ADJUNCT>предлог:за{}.<OBJECT>*:*{ падеж:вин } }
then 2
}
// Александр улыбнулся, пожирая её глазами.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пожирать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } 'глазами' } }
then 2
}
// мне будет сорок один год
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{ число:ед лицо:3 время:будущее }.
{
<SUBJECT>существительное:год{}.числительное:*{}
<OBJECT>*:*{ падеж:дат }
}
}
then 2
}
// Мне было двадцать три года.
tree_scorer ВалентностьПредиката language=Russian
{
if context { глагол:быть{ число:ед род:ср время:прошедшее }.
{
<SUBJECT>существительное:год{}.числительное:*{}
<OBJECT>*:*{ падеж:дат }
}
}
then 2
}
// Устойчивый оборот: принять участие в чем-то:
//
// В экспедиции приняли участие много иностранцев.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:принять{}.{ <OBJECT>существительное:участие{ ПАДЕЖ:ВИН } <PREPOS_ADJUNCT>предлог:в{}.*:*{ падеж:предл } } }
then 1
}
// Женщина и ребенок с ног валились.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:валиться{}.'с'.'ног' }
then 2
}
// Ведет оседлый и полуоседлый образ жизни.
// ^^^^^ ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:вести{}.<OBJECT>'образ'.'жизни' }
then 2
}
// Я обещался в точности исполнить поручение.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:исполнить{}.'в'.'точности'{ падеж:предл } }
then 2
}
// Впрочем, может быть и меньше.
// ~~~~~~
tree_scorer ВалентностьПредиката language=Russian
{
if context { СчетнСвязка.[not]<OBJECT>*:*{} }
then -3
}
// Проехали километра два.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:проехать{}.<OBJECT>существительное:километр{} }
then 4
}
// Прошли пять километров
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<OBJECT>существительное:километр{} }
then 4
}
// Пройдет много лет.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:пройти{}.<SUBJECT>'лет'.'много' }
then 4
}
// Ничего не видит.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:видеть{}.<SUBJECT>'ничего' }
then -4
}
// Ничего не знает.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:знать{}.<SUBJECT>'ничего' }
then -4
}
// Ничего не боится.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:бояться{}.<SUBJECT>'ничего' }
then -4
}
// Взяли в клещи.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:взять{}.'в'.'клещи'{ ПАДЕЖ:ВИН} }
then 2
}
// К вам пришли!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придти{}.'к'.*:*{ ПАДЕЖ:ДАТ } }
then 1
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прийти{}.'к'.*:*{ ПАДЕЖ:ДАТ } }
then 1
}
// Сергиенко воспользовался моментом.
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:воспользоваться{}.[not]<OBJECT>*:*{ ПАДЕЖ:ТВОР } }
then -1
}
// Готовиться времени нет.
tree_scorer ВалентностьПредиката language=Russian
{
if context { частица:нет{}.'времени'.<INFINITIVE>инфинитив:*{} }
then 4
}
// Дал время подумать.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:дать{}.<OBJECT>существительное:время{ падеж:вин }.<INFINITIVE>инфинитив:*{} }
then 4
}
// -------------------------------------------------------------------------------
// Ночь выдается беспокойная.
// ^^^^^^^^^^^^^
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:выдаваться{}.<SUBJECT>СущСоЗначВремКакОбст1{ ПАДЕЖ:ИМ } }
then 4
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:выдаться{}.<SUBJECT>СущСоЗначВремКакОбст1{ ПАДЕЖ:ИМ } }
then 4
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выдаваться{}.<ATTRIBUTE>СущСоЗначВремКакОбст1{} }
then -10
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:выдаться{}.<ATTRIBUTE>СущСоЗначВремКакОбст1{} }
then -10
}
// -------------------------------------------------------------------------------
// Что говорит свинец?
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:говорить{}.<SUBJECT>местоим_сущ:что{} }
then -3
}
// В детях эта программа усиливается во много раз.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:усиливаться{}."во"."раз"."много" }
then 5
}
// Я посмотрел на часы.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:посмотреть{}."на".*{ ПАДЕЖ:ВИН } }
then 3
}
// К вам пришли!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:придти{}."к".ОдушОбъект }
then 3
}
// Он бросил взгляд на часы. (БРОСИТЬ ВЗГЛЯД НА что-то)
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:бросить{}.{ <OBJECT>"взгляд"{ ПАДЕЖ:ВИН } <PREPOS_ADJUNCT>"на".*:*{ ПАДЕЖ:ВИН } } }
then 3
}
// Женщина и ребенок с ног валились. (ВАЛИТЬСЯ С НОГ)
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:валиться{}."с"."ног" }
then 3
}
// стыдно ребятам в глаза смотреть. (СМОТРЕТЬ В ГЛАЗА)
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}."в"."глаза"{ ПАДЕЖ:ВИН } }
then 3
}
// Надежнее иметь дело со взрослыми. (ИМЕТЬ ДЕЛО С кем-то/чем-то)
// ^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:иметь{}.{ <OBJECT>существительное:дело{ падеж:вин } <PREPOS_ADJUNCT>предлог:с{}.*:*{ ПАДЕЖ:ТВОР } } }
then 3
}
// Вдохновлял он ее и на поэмы. (ВДОХНОВЛЯТЬ/ВДОХНОВИТЬ НА что-то)
// ^^^^^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:вдохновлять{}.<PREPOS_ADJUNCT>предлог:на{}.*:*{ ПАДЕЖ:ВИН } }
then 3
}
// Оставшихся в живых они же заперли в резервациях. (ОСТАТЬСЯ В ЖИВЫХ)
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:остаться{}.<PREPOS_ADJUNCT>предлог:в{}.'живых' }
then 3
}
// Я стояла, провожая его взглядом. (ПРОВОЖАТЬ кого-то/что-то ВЗГЛЯДОМ)
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:провожать{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } 'взглядом' } }
then 3
}
// Эпидемии гриппа не ожидается
tree_scorer ВалентностьГлагола language=Russian
{
if context { "ожидается".{ <OBJECT>*:*{ ПАДЕЖ:РОД } 'не' } }
then 3
}
// --------------------------------------------------------------------------
// Прикажи дать коньяку.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}.<OBJECT>*:*{ ПАДЕЖ:ПАРТ <в_класс>СУЩЕСТВИТЕЛЬНОЕ:НАПИТОК{} } }
then 6
}
// Там дела важнее.
// ^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { 'дела'.<ATTRIBUTE>НАРЕЧИЕ:*{ СТЕПЕНЬ:СРАВН } }
then -10
}
// --------------------------------------------------------------------
// Что делает Танасчишин?
// ~~~~~~~~~~
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:делать{}.<SUBJECT>местоим_сущ:что{} }
then -3
}
// -------------------------------------------------------
// Нельзя допустить атрофии.
tree_scorer ВалентностьПредиката language=Russian
{
if context { инфинитив:допустить{}.{ <LEFT_AUX_VERB>безлич_глагол:Нельзя{} <OBJECT>*:*{ падеж:род } } }
then 3
}
// --------------------------------------------------------
// Надо Дорошенко сказать.
// ^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сказать{}.<OBJECT>существительное:*{ ОДУШ:ОДУШ ПАДЕЖ:ТВОР } }
then -5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сказать{}.<OBJECT>существительное:*{ ОДУШ:ОДУШ ПАДЕЖ:ВИН } }
then -5
}
// --------------------------------------------------------------
// Тем не менее досталось всем.
// ^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:достаться{}.<ATTRIBUTE>'всем'{ ПАДЕЖ:ТВОР } }
then -20
}
// Наконец достигли вершины.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:достичь{}.<OBJECT>НеодушОбъект{ ПАДЕЖ:РОД } }
then 3
}
// --------------------------------------------------------------
// Возглавляет его мэр.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:возглавлять{}.[not]<OBJECT>*:*{ ПАДЕЖ:ВИН } }
then -3
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:возглавлять{}.<OBJECT>существительное:*{ ПАДЕЖ:ВИН } }
then -3
}
/*
// Засыпаю его вопросами.
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:засыпать{ ПЕРЕХОДНОСТЬ:ПЕРЕХОДНЫЙ }.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <OBJECT>'вопросами' } }
then 2
}
*/
// Разбудила его Надя.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:разбудить{}.{ <OBJECT>*:*{ ПАДЕЖ:ВИН } <SUBJECT>*:*{} } }
then 2
}
// Прошло две недели.
tree_scorer ВалентностьПредиката language=Russian
{
if context { 'прошло'.<SUBJECT>СущСоЗначВрем{ ПАДЕЖ:РОД }.числительное:*{} }
then 2
}
// Я просидел дома весь день
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:просидеть{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// Сегодня я весь день читал.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:читать{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// я буду работать весь день
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:работать{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// вместе они шли весь день.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:идти{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// бой продолжался весь день.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:продолжаться{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// битва длилась весь день.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:длиться{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'весь'{ ПАДЕЖ:ВИН } }
then 2
}
// мы играли во дворе целый день
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:играть{}.<ATTRIBUTE>'день'{ ПАДЕЖ:ВИН }.<ATTRIBUTE>'целый'{ ПАДЕЖ:ВИН } }
then 2
}
// У меня к тебе дело
// ~~~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:деть{ род:ср }.предлог:к{}.*:*{ падеж:дат } }
then -10
}
// дайте им три часа.
// ^^^^^ ^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:дать{}.<OBJECT>существительное:час{}.числительное:*{} }
then 5
}
// Важное значение имеет и нестационарность Метагалактики.
// ^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:иметь{}.<OBJECT>существительное:значение{}.'важное' }
then 10
}
// Я не теряю надежды.
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:терять{}.{ <NEGATION_PARTICLE>частица:не{} <OBJECT>существительное:надежда{ падеж:род число:ед } } }
then 1
}
// Вы не знаете Дезире?
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:знать{}.<OBJECT>существительное:*{ одуш:одуш падеж:твор } }
then -5
}
// Я целую Викторию...
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:целовать{}.<OBJECT>существительное:*{ одуш:одуш падеж:дат } }
then -5
}
// Благоустройство кладбища продолжалось и летом.
// ^^^^^^^^^^^^ ^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:продолжаться{}.<ATTRIBUTE>существительное:лето{ падеж:твор } }
then 5
}
// ----------------------------------------------------------------
// Ей нужен был отдых.
tree_scorer ВалентностьПредиката language=Russian
{
if context { прилагательное:нужный{ краткий }.'ей'{ падеж:твор } }
then -5
}
tree_scorer ВалентностьПредиката language=Russian
{
if context { прилагательное:нужный{ краткий }.'им'{ падеж:твор } }
then -5
}
// - Я тебе дам знать .
tree_scorer ВалентностьГлагола language=Russian
{
if context { инфинитив:знать{}.rus_verbs:дать{} }
then 5
}
// Для отправителя они не представляли опасности.
// ^^^^^^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:представлять{}.'опасности'{ ПАДЕЖ:РОД } }
then 5
}
// К вам это не имело отношения.
// ^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { глагол:иметь{}.'отношения'{ ЧИСЛО:МН } }
then -1
}
// ты встала на его пути
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:встать{}.'на'.'пути'{ ПАДЕЖ:ВИН } }
then -2
}
// Она хотела стать моей
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:хотеть{}.<OBJECT>существительное:стать{} }
then -10
}
// откуда нам это знать?
tree_scorer ВалентностьПредиката language=Russian
{
if context { инфинитив:знать{}.{ <ATTRIBUTE>наречие:откуда{} <OBJECT>*:*{ падеж:дат } } }
then 2
}
// друид встал на их пути
// ^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:встать{}.<PREPOS_ADJUNCT>предлог:на{}.<OBJECT>существительное:путь{ падеж:вин } }
then -2
}
// «Мы вытолкнули Украину из Русского мира»
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:вытолкнуть{}.<PREPOS_ADJUNCT>предлог:из{} }
then 2
}
// Владимир Путин объявил финансовые пирамиды вне закона
// ^^^^^^^ ^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:объявить{}.<PREPOS_ADJUNCT>предлог:вне{} }
then 2
}
// Содержание их было однообразно.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rhema=прилагательное:*{ КРАТКИЙ ЧИСЛО:ЕД РОД:СР }.{ thema=<SUBJECT>существительное:*{ ЧИСЛО:ЕД РОД:СР } } }
then adj_noun_score(rhema,thema)
}
// Отдам краснохвостого сома в хорошие руки
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отдать{}.предлог:в{}.'руки'.'хорошие' }
then 5
}
// ----------------------------------------------------------------
// Приобретает массовый характер Стахановское движение.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приобретать{}.<OBJECT>существительное:характер{}.<ATTRIBUTE>прилагательное:массовый{} }
then 5
}
// Фашистские стрелки открывают ответный огонь.
tree_scorer ВалентностьПредиката language=Russian
{
if context { rus_verbs:открывать{}.{ <SUBJECT>существительное:стрелок{} <OBJECT>существительное:огонь{} } }
then 5
}
// Документы эти разрабатывались соответствующими начальниками.
// Старый хрыч обернулся добродушным дедулей.
tree_scorer ВалентностьГлагола language=Russian generic
{
if context { глагол:*{}.<ATTRIBUTE>существительное:*{ падеж:твор одуш:одуш } }
then -2
}
// Он смотрел на танцующих вытаращенными глазами.
// ^^^^^^^^^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.предлог:на{}.прилагательное:*{ падеж:предл } }
then -5
}
// Ей в глаза смотрела дама червей.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:смотреть{}.{ предлог:в{} "ей"{падеж:твор} } }
then -5
}
// Ей даже передалось его нервное напряжение.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:передаться{}."ей"{падеж:твор} }
then -5
}
// Ей ничего не приходило на ум.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:приходить{}."ей"{падеж:твор} }
then -5
}
// Ей и так все было ясно.
tree_scorer ВалентностьГлагола language=Russian
{
if context { "было"."ей"{падеж:твор} }
then -5
}
// Ей отвели пять часов на раздумья.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отвести{}."ей"{падеж:твор} }
then -5
}
// Ей смертельно надоели эти смертельные игры.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:надоесть{}."ей"{падеж:твор} }
then -5
}
// Ей пришлось нелегко в прошлом году.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прийтись{}."ей"{падеж:твор} }
then -5
}
// Ей отвечали только изумленные печальные взгляды.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отвечать{}."ей"{падеж:твор} }
then -5
}
// Ей просто дали пипка под зад.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}."ей"{падеж:твор} }
then -5
}
// Ей все виделось в черном цвете.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:видеться{}."ей"{падеж:твор} }
then -5
}
// Ей в голову пришла одна мысль.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:прийти{}."ей"{падеж:твор} }
then -5
}
// Ей становилось трудно даже держаться прямо;
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:становиться{}."ей"{падеж:твор} }
then -5
}
// Ей бы и не дали вернуться.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:дать{}."ей"{падеж:твор} }
then -5
}
// Ей всегда доставляло удовольствие плести интриги.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:доставлять{}."ей"{падеж:твор} }
then -5
}
// Ей доставило немало удовольствия унизить меня.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:доставить{}."ей"{падеж:твор} }
then -5
}
// Ей отдается вся энергия творящего артиста.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:отдаваться{}."ей"{падеж:твор} }
then -5
}
// Ей заранее был известен результат взрыва.
tree_scorer ВалентностьГлагола language=Russian
{
if context { прилагательное:*{краткий}."ей"{падеж:твор} }
then -2
}
// Ей ставят капельницы и делают уколы.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:ставить{}."ей"{падеж:твор} }
then -5
}
// Ей вызвали «скорую помощь».
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:вызвать{}."ей"{падеж:твор} }
then -5
}
// Ей подражали все девушки Советского Союза.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подражать{}."ей"{падеж:твор} }
then -5
}
// Ей разрешили оформить опеку над Сашей!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:разрешить{}."ей"{падеж:твор} }
then -5
}
// Ей Самсонова подавай, шофера автобазы!
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:подавать{}."ей"{падеж:твор} }
then -5
}
// Ему это с рук не сойдет.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:сойти{}."с"."рук" }
then 5
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { "это"."с"."рук" }
then -10
}
// Ему хотелось душу из нее вытрясти.
// ~~~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { существительное:душа{}."из".местоимение:*{} }
then -10
}
// Ему просто не приходилось этого делать.
// ^^^^^^^^^^^^
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:делать{}."этого"{падеж:вин} }
then -10
}
// Ему хотелось драки, хотелось убить.
tree_scorer ВалентностьГлагола language=Russian
{
if context { "хотелось".<OBJECT>существительное:*{число:мн падеж:вин} }
then -5
}
// А что со мной могло случиться?
// ~~~~~~~~~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { "что".предлог:с{} }
then -10
}
// А раньше-то что молчал?
// ~~~
tree_scorer ВалентностьГлагола language=Russian
{
if context { "молчал".<OBJECT>"что" }
then -100
}
tree_scorer ВалентностьГлагола language=Russian
{
if context { "молчал".<SUBJECT>"что" }
then -100
}
// А ты с ними по-русски говори.
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:говорить{}.ПРЕДЛОГ:С{}.МЕСТОИМЕНИЕ:*{ПАДЕЖ:ТВОР} }
then 1
}
// ----------------------------------------------------------------
#define vap(v,adv,p,w) \
#begin
tree_scorer ВалентностьГлагола language=Russian
{
if context { rus_verbs:v{}.<PREPOS_ADJUNCT>ПРЕДЛОГ:p{}.<ATTRIBUTE>НАРЕЧИЕ:adv{} }
then w
}
#end
vap(стоять,впритык,к,1) // Шкаф стоит впритык к столу.
vap(стоять,вплотную,к,1) // Шкаф стоит вплотную к столу.
vap(бежать,следом,за,2) // она как раз начала бежать следом за ним
vap(быть,рядом,с,2) // он был рядом с дверью
vap(пойти,следом,за,2) // Катя пошла следом за ними.
// Я приехал в Москву одновременно с братом.
// ^^^^^^^ ^^^^^^^^^^^^^^
vap(приехать,одновременно,с,1)
vap(прийти,одновременно,с,1)
vap(прибыть,одновременно,с,1)
vap(появиться,одновременно,с,1)
// Петя положил яблоки вместе с картошкой.
// ^^^^^^^ ^^^^^^^^
vap(положить,вместе,с,1)
vap(ложить,вместе,с,1)
vap(положить,слева,от,2) // Положи книгу слева от тетради
vap(глядеть,прямо,в,5) // глядя прямо в ее круглые карие глаза, произнес
vap(посмотреть,прямо,в,5)
vap(смотреть,прямо,в,5)
vap(заглянуть,прямо,в,5)
vap(швырнуть,прямо,в,5) // Он подлетает к башне и... сейчас кибер швырнет нашего гладиатора прямо в ее пустую утробу.
vap(швырять,прямо,в,5)
vap(кинуть,прямо,в,5)
vap(кидать,прямо,в,5)
| сегодня все было как обычно ^^^^^^^^^^ | tree_scorer ВалентностьГлагола language=Russian generic { if context { инфинитив:*{}.<ATTRIBUTE>наречие:как обычно{} } then 7 }
| 12,629,414 | [
1,
146,
228,
145,
118,
145,
116,
145,
127,
145,
117,
145,
126,
146,
242,
225,
145,
115,
146,
228,
145,
118,
225,
145,
114,
146,
238,
145,
124,
145,
127,
225,
145,
123,
145,
113,
145,
123,
225,
145,
127,
145,
114,
146,
238,
146,
234,
145,
126,
145,
127,
5375,
3602,
20254,
20254,
66,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3413,
67,
1017,
8922,
225,
145,
245,
145,
113,
145,
124,
145,
118,
145,
126,
146,
229,
145,
126,
145,
127,
146,
228,
146,
229,
146,
239,
145,
246,
145,
124,
145,
113,
145,
116,
145,
127,
145,
124,
145,
113,
2653,
33,
54,
5567,
2779,
5210,
288,
309,
819,
288,
225,
145,
121,
145,
126,
146,
231,
145,
121,
145,
126,
145,
121,
146,
229,
145,
121,
145,
115,
30,
14,
2916,
22782,
11616,
34,
145,
126,
145,
113,
146,
227,
145,
118,
146,
234,
145,
121,
145,
118,
30,
145,
123,
145,
113,
145,
123,
225,
145,
127,
145,
114,
146,
238,
146,
234,
145,
126,
145,
127,
2916,
289,
1508,
2371,
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
] |
pragma solidity ^0.5.11;
// Public-Sale for #3277-12000 stage of Voken2.0
//
// More info:
// https://vision.network
// https://voken.io
//
// Contact us:
// [email protected]
// [email protected]
/**
* @dev Uint256 wrappers over Solidity's arithmetic operations with added overflow checks.
*/
library SafeMath256 {
/**
* @dev Returns the addition of two unsigned integers, reverting on 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).
*/
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).
*/
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.
*/
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. Reverts on
* division by zero. The result is rounded towards 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.
*/
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);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by 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.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Uint16 wrappers over Solidity's arithmetic operations with added overflow checks.
*/
library SafeMath16 {
/**
* @dev Returns the addition of two unsigned integers, reverting on overflow.
*/
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 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).
*/
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
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).
*/
function sub(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) {
require(b <= a, errorMessage);
uint16 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*/
function mul(uint16 a, uint16 b) internal pure returns (uint16) {
if (a == 0) {
return 0;
}
uint16 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.
*/
function div(uint16 a, uint16 b) internal pure returns (uint16) {
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.
*/
function div(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*/
function mod(uint16 a, uint16 b) internal pure returns (uint16) {
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.
*/
function mod(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
/**
* @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.
*/
contract Ownable {
address internal _owner;
address internal _newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event OwnershipAccepted(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 addresses of the current and new owner.
*/
function owner() public view returns (address currentOwner, address newOwner) {
currentOwner = _owner;
newOwner = _newOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(msg.sender), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner(address account) public view returns (bool) {
return account == _owner;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*
* IMPORTANT: Need to run {acceptOwnership} by the new owner.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_newOwner = newOwner;
}
/**
* @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 Accept ownership of the contract.
*
* Can only be called by the new owner.
*/
function acceptOwnership() public {
require(msg.sender == _newOwner, "Ownable: caller is not the new owner address");
require(msg.sender != address(0), "Ownable: caller is the zero address");
emit OwnershipAccepted(_owner, msg.sender);
_owner = msg.sender;
_newOwner = address(0);
}
/**
* @dev Rescue compatible ERC20 Token
*
* Can only be called by the current owner.
*/
function rescueTokens(address tokenAddr, address recipient, uint256 amount) external onlyOwner {
IERC20 _token = IERC20(tokenAddr);
require(recipient != address(0), "Rescue: recipient is the zero address");
uint256 balance = _token.balanceOf(address(this));
require(balance >= amount, "Rescue: amount exceeds balance");
_token.transfer(recipient, amount);
}
/**
* @dev Withdraw Ether
*
* Can only be called by the current owner.
*/
function withdrawEther(address payable recipient, uint256 amount) external onlyOwner {
require(recipient != address(0), "Withdraw: recipient is the zero address");
uint256 balance = address(this).balance;
require(balance >= amount, "Withdraw: amount exceeds balance");
recipient.transfer(amount);
}
}
/**
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
bool private _paused;
event Paused(address account);
event Unpaused(address account);
/**
* @dev Constructor
*/
constructor () internal {
_paused = false;
}
/**
* @return Returns true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Paused");
_;
}
/**
* @dev Sets paused state.
*
* Can only be called by the current owner.
*/
function setPaused(bool value) external onlyOwner {
_paused = value;
if (_paused) {
emit Paused(msg.sender);
} else {
emit Unpaused(msg.sender);
}
}
}
/**
* @dev Part of ERC20 interface.
*/
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
}
/**
* @title Voken2.0 interface.
*/
interface IVoken2 {
function balanceOf(address owner) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function mint(address account, uint256 amount) external returns (bool);
function mintWithAllocation(address account, uint256 amount, address allocationContract) external returns (bool);
function whitelisted(address account) external view returns (bool);
function whitelistReferee(address account) external view returns (address payable);
function whitelistReferralsCount(address account) external view returns (uint256);
}
/**
* @dev Interface of an allocation contract
*/
interface IAllocation {
function reservedOf(address account) external view returns (uint256);
}
/**
* @dev Allocation for VOKEN
*/
library Allocations {
struct Allocation {
uint256 amount;
uint256 timestamp;
}
}
/**
* @title VokenShareholders interface.
*/
interface VokenShareholders {
//
}
/**
* @title Voken Public Sale v2.0
*/
contract VokenPublicSale2 is Ownable, Pausable, IAllocation {
using SafeMath16 for uint16;
using SafeMath256 for uint256;
using Roles for Roles.Role;
using Allocations for Allocations.Allocation;
// Proxy
Roles.Role private _proxies;
// Addresses
IVoken2 private _VOKEN = IVoken2(0xFfFAb974088Bd5bF3d7E6F522e93Dd7861264cDB);
VokenShareholders private _SHAREHOLDERS = VokenShareholders(0x7712F76D2A52141D44461CDbC8b660506DCAB752);
address payable private _TEAM;
// Referral rewards, 35% for 15 levels
uint16[15] private REWARDS_PCT = [6, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1];
// Limit
uint16[] private LIMIT_COUNTER = [1, 3, 10, 50, 100, 200, 300];
uint256[] private LIMIT_WEIS = [100 ether, 50 ether, 40 ether, 30 ether, 20 ether, 10 ether, 5 ether];
uint256 private LIMIT_WEI_MIN = 3 ether;
// 6,000 000 gas mininum
uint24 private GAS_MIN = 6000000;
// Price
uint256 private VOKEN_USD_PRICE_START = 1000; // $ 0.00100 USD
uint256 private VOKEN_USD_PRICE_STEP = 10; // $ + 0.00001 USD
uint256 private STAGE_USD_CAP_START = 100000000; // $ 100 USD
uint256 private STAGE_USD_CAP_STEP = 1000000; // $ +1 USD
uint256 private STAGE_USD_CAP_MAX = 15100000000; // $ 15,100 USD
// 1 Ether|Voken = xx.xxxxxx USD, with 6 decimals
uint256 private _etherUsdPrice;
uint256 private _vokenUsdPrice;
// Progress
uint16 private SEASON_MAX = 100; // 100 seasons max
uint16 private SEASON_LIMIT = 20; // 20 season total
uint16 private SEASON_STAGES = 600; // each 600 stages is a season
uint16 private STAGE_MAX = SEASON_STAGES.mul(SEASON_MAX);
uint16 private STAGE_LIMIT = SEASON_STAGES.mul(SEASON_LIMIT);
uint16 private _stage;
uint16 private _season;
// Sum
uint256 private _txs;
uint256 private _vokenIssued;
uint256 private _vokenIssuedTxs;
uint256 private _vokenBonus;
uint256 private _vokenBonusTxs;
uint256 private _weiSold;
uint256 private _weiRewarded;
uint256 private _weiShareholders;
uint256 private _weiTeam;
uint256 private _weiPended;
uint256 private _usdSold;
uint256 private _usdRewarded;
// Shareholders ratio
uint256 private SHAREHOLDERS_RATIO_START = 15000000; // 15%, with 8 decimals
uint256 private SHAREHOLDERS_RATIO_DISTANCE = 50000000; // 50%, with 8 decimals
uint256 private _shareholdersRatio;
// Cache
bool private _cacheWhitelisted;
uint256 private _cacheWeiShareholders;
uint256 private _cachePended;
uint16[] private _cacheRewards;
address payable[] private _cacheReferees;
// Allocations
mapping (address => Allocations.Allocation[]) private _allocations;
// Account
mapping (address => uint256) private _accountVokenIssued;
mapping (address => uint256) private _accountVokenBonus;
mapping (address => uint256) private _accountVokenReferral;
mapping (address => uint256) private _accountVokenReferrals;
mapping (address => uint256) private _accountUsdPurchased;
mapping (address => uint256) private _accountWeiPurchased;
mapping (address => uint256) private _accountUsdRewarded;
mapping (address => uint256) private _accountWeiRewarded;
// Stage
mapping (uint16 => uint256) private _stageUsdSold;
mapping (uint16 => uint256) private _stageVokenIssued;
mapping (uint16 => uint256) private _stageVokenBonus;
// Season
mapping (uint16 => uint256) private _seasonWeiSold;
mapping (uint16 => uint256) private _seasonWeiRewarded;
mapping (uint16 => uint256) private _seasonWeiShareholders;
mapping (uint16 => uint256) private _seasonWeiPended;
mapping (uint16 => uint256) private _seasonUsdSold;
mapping (uint16 => uint256) private _seasonUsdRewarded;
mapping (uint16 => uint256) private _seasonUsdShareholders;
mapping (uint16 => uint256) private _seasonVokenIssued;
mapping (uint16 => uint256) private _seasonVokenBonus;
// Account in season
mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountIssued;
mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountBonus;
mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountReferral;
mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountReferrals;
mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountPurchased;
mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountReferrals;
mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountRewarded;
mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountPurchased;
mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountReferrals;
mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountRewarded;
// Season wei limit accounts
mapping (uint16 => mapping (uint256 => address[])) private _seasonLimitAccounts;
mapping (uint16 => address[]) private _seasonLimitWeiMinAccounts;
// Referrals
mapping (uint16 => address[]) private _seasonAccounts;
mapping (uint16 => address[]) private _seasonReferrals;
mapping (uint16 => mapping (address => bool)) private _seasonHasAccount;
mapping (uint16 => mapping (address => bool)) private _seasonHasReferral;
mapping (uint16 => mapping (address => address[])) private _seasonAccountReferrals;
mapping (uint16 => mapping (address => mapping (address => bool))) private _seasonAccountHasReferral;
// Events
event ProxyAdded(address indexed account);
event ProxyRemoved(address indexed account);
event StageClosed(uint256 _stageNumber);
event SeasonClosed(uint16 _seasonNumber);
event AuditEtherPriceUpdated(uint256 value, address indexed account);
event Log(uint256 value);
/**
* @dev Throws if called by account which is not a proxy.
*/
modifier onlyProxy() {
require(isProxy(msg.sender), "ProxyRole: caller does not have the Proxy role");
_;
}
/**
* @dev Returns true if the `account` has the Proxy role.
*/
function isProxy(address account) public view returns (bool) {
return _proxies.has(account);
}
/**
* @dev Give an `account` access to the Proxy role.
*
* Can only be called by the current owner.
*/
function addProxy(address account) public onlyOwner {
_proxies.add(account);
emit ProxyAdded(account);
}
/**
* @dev Remove an `account` access from the Proxy role.
*
* Can only be called by the current owner.
*/
function removeProxy(address account) public onlyOwner {
_proxies.remove(account);
emit ProxyRemoved(account);
}
/**
* @dev Returns the VOKEN address.
*/
function VOKEN() public view returns (IVoken2) {
return _VOKEN;
}
/**
* @dev Returns the shareholders contract address.
*/
function SHAREHOLDERS() public view returns (VokenShareholders) {
return _SHAREHOLDERS;
}
/**
* @dev Returns the team wallet address.
*/
function TEAM() public view returns (address) {
return _TEAM;
}
/**
* @dev Returns the main status.
*/
function status() public view returns (uint16 stage,
uint16 season,
uint256 etherUsdPrice,
uint256 vokenUsdPrice,
uint256 shareholdersRatio) {
if (_stage > STAGE_MAX) {
stage = STAGE_MAX;
season = SEASON_MAX;
}
else {
stage = _stage;
season = _season;
}
etherUsdPrice = _etherUsdPrice;
vokenUsdPrice = _vokenUsdPrice;
shareholdersRatio = _shareholdersRatio;
}
/**
* @dev Returns the sum.
*/
function sum() public view returns(uint256 vokenIssued,
uint256 vokenBonus,
uint256 weiSold,
uint256 weiRewarded,
uint256 weiShareholders,
uint256 weiTeam,
uint256 weiPended,
uint256 usdSold,
uint256 usdRewarded) {
vokenIssued = _vokenIssued;
vokenBonus = _vokenBonus;
weiSold = _weiSold;
weiRewarded = _weiRewarded;
weiShareholders = _weiShareholders;
weiTeam = _weiTeam;
weiPended = _weiPended;
usdSold = _usdSold;
usdRewarded = _usdRewarded;
}
/**
* @dev Returns the transactions' counter.
*/
function transactions() public view returns(uint256 txs,
uint256 vokenIssuedTxs,
uint256 vokenBonusTxs) {
txs = _txs;
vokenIssuedTxs = _vokenIssuedTxs;
vokenBonusTxs = _vokenBonusTxs;
}
/**
* @dev Returns the `account` data.
*/
function queryAccount(address account) public view returns (uint256 vokenIssued,
uint256 vokenBonus,
uint256 vokenReferral,
uint256 vokenReferrals,
uint256 weiPurchased,
uint256 weiRewarded,
uint256 usdPurchased,
uint256 usdRewarded) {
vokenIssued = _accountVokenIssued[account];
vokenBonus = _accountVokenBonus[account];
vokenReferral = _accountVokenReferral[account];
vokenReferrals = _accountVokenReferrals[account];
weiPurchased = _accountWeiPurchased[account];
weiRewarded = _accountWeiRewarded[account];
usdPurchased = _accountUsdPurchased[account];
usdRewarded = _accountUsdRewarded[account];
}
/**
* @dev Returns the stage data by `stageIndex`.
*/
function stage(uint16 stageIndex) public view returns (uint256 vokenUsdPrice,
uint256 shareholdersRatio,
uint256 vokenIssued,
uint256 vokenBonus,
uint256 vokenCap,
uint256 vokenOnSale,
uint256 usdSold,
uint256 usdCap,
uint256 usdOnSale) {
if (stageIndex <= STAGE_LIMIT) {
vokenUsdPrice = _calcVokenUsdPrice(stageIndex);
shareholdersRatio = _calcShareholdersRatio(stageIndex);
vokenIssued = _stageVokenIssued[stageIndex];
vokenBonus = _stageVokenBonus[stageIndex];
vokenCap = _stageVokenCap(stageIndex);
vokenOnSale = vokenCap.sub(vokenIssued);
usdSold = _stageUsdSold[stageIndex];
usdCap = _stageUsdCap(stageIndex);
usdOnSale = usdCap.sub(usdSold);
}
}
/**
* @dev Returns the season data by `seasonNumber`.
*/
function season(uint16 seasonNumber) public view returns (uint256 vokenIssued,
uint256 vokenBonus,
uint256 weiSold,
uint256 weiRewarded,
uint256 weiShareholders,
uint256 weiPended,
uint256 usdSold,
uint256 usdRewarded,
uint256 usdShareholders) {
if (seasonNumber <= SEASON_LIMIT) {
vokenIssued = _seasonVokenIssued[seasonNumber];
vokenBonus = _seasonVokenBonus[seasonNumber];
weiSold = _seasonWeiSold[seasonNumber];
weiRewarded = _seasonWeiRewarded[seasonNumber];
weiShareholders = _seasonWeiShareholders[seasonNumber];
weiPended = _seasonWeiPended[seasonNumber];
usdSold = _seasonUsdSold[seasonNumber];
usdRewarded = _seasonUsdRewarded[seasonNumber];
usdShareholders = _seasonUsdShareholders[seasonNumber];
}
}
/**
* @dev Returns the `account` data of #`seasonNumber` season.
*/
function accountInSeason(address account, uint16 seasonNumber) public view returns (uint256 vokenIssued,
uint256 vokenBonus,
uint256 vokenReferral,
uint256 vokenReferrals,
uint256 weiPurchased,
uint256 weiReferrals,
uint256 weiRewarded,
uint256 usdPurchased,
uint256 usdReferrals,
uint256 usdRewarded) {
if (seasonNumber > 0 && seasonNumber <= SEASON_LIMIT) {
vokenIssued = _vokenSeasonAccountIssued[seasonNumber][account];
vokenBonus = _vokenSeasonAccountBonus[seasonNumber][account];
vokenReferral = _vokenSeasonAccountReferral[seasonNumber][account];
vokenReferrals = _vokenSeasonAccountReferrals[seasonNumber][account];
weiPurchased = _weiSeasonAccountPurchased[seasonNumber][account];
weiReferrals = _weiSeasonAccountReferrals[seasonNumber][account];
weiRewarded = _weiSeasonAccountRewarded[seasonNumber][account];
usdPurchased = _usdSeasonAccountPurchased[seasonNumber][account];
usdReferrals = _usdSeasonAccountReferrals[seasonNumber][account];
usdRewarded = _usdSeasonAccountRewarded[seasonNumber][account];
}
}
/**
* @dev Referral accounts in a season by `seasonNumber`.
*/
function seasonReferrals(uint16 seasonNumber) public view returns (address[] memory) {
return _seasonReferrals[seasonNumber];
}
/**
* @dev Referral accounts in a season by `seasonNumber` of `account`.
*/
function seasonAccountReferrals(uint16 seasonNumber, address account) public view returns (address[] memory) {
return _seasonAccountReferrals[seasonNumber][account];
}
/**
* @dev Voken price in USD, by `stageIndex`.
*/
function _calcVokenUsdPrice(uint16 stageIndex) private view returns (uint256) {
return VOKEN_USD_PRICE_START.add(VOKEN_USD_PRICE_STEP.mul(stageIndex));
}
/**
* @dev Returns the shareholders ratio by `stageIndex`.
*/
function _calcShareholdersRatio(uint16 stageIndex) private view returns (uint256) {
return SHAREHOLDERS_RATIO_START.add(SHAREHOLDERS_RATIO_DISTANCE.mul(stageIndex).div(STAGE_MAX));
}
/**
* @dev Returns the dollor cap of `stageIndex`.
*/
function _stageUsdCap(uint16 stageIndex) private view returns (uint256) {
uint256 __usdCap = STAGE_USD_CAP_START.add(STAGE_USD_CAP_STEP.mul(stageIndex));
if (__usdCap > STAGE_USD_CAP_MAX) {
return STAGE_USD_CAP_MAX;
}
return __usdCap;
}
/**
* @dev Returns the Voken cap of `stageIndex`.
*/
function _stageVokenCap(uint16 stageIndex) private view returns (uint256) {
return _stageUsdCap(stageIndex).mul(1000000).div(_calcVokenUsdPrice(stageIndex));
}
/**
* @dev Returns an {uint256} by `value` * _shareholdersRatio / 100000000
*/
function _2shareholders(uint256 value) private view returns (uint256) {
return value.mul(_shareholdersRatio).div(100000000);
}
/**
* @dev wei => USD, by `weiAmount`.
*/
function _wei2usd(uint256 weiAmount) private view returns (uint256) {
return weiAmount.mul(_etherUsdPrice).div(1 ether);
}
/**
* @dev USD => wei, by `usdAmount`.
*/
function _usd2wei(uint256 usdAmount) private view returns (uint256) {
return usdAmount.mul(1 ether).div(_etherUsdPrice);
}
/**
* @dev USD => voken, by `usdAmount`.
*/
function _usd2voken(uint256 usdAmount) private view returns (uint256) {
return usdAmount.mul(1000000).div(_vokenUsdPrice);
}
/**
* @dev Returns the season number by `stageIndex`.
*/
function _seasonNumber(uint16 stageIndex) private view returns (uint16) {
if (stageIndex > 0) {
uint16 __seasonNumber = stageIndex.div(SEASON_STAGES);
if (stageIndex.mod(SEASON_STAGES) > 0) {
return __seasonNumber.add(1);
}
return __seasonNumber;
}
return 1;
}
/**
* Close the current stage.
*/
function _closeStage() private {
_stage = _stage.add(1);
emit StageClosed(_stage);
// Close current season
uint16 __seasonNumber = _seasonNumber(_stage);
if (_season < __seasonNumber) {
_season = __seasonNumber;
emit SeasonClosed(_season);
}
_vokenUsdPrice = _calcVokenUsdPrice(_stage);
_shareholdersRatio = _calcShareholdersRatio(_stage);
}
/**
* @dev Update audit ether price.
*/
function updateEtherUsdPrice(uint256 value) external onlyProxy {
_etherUsdPrice = value;
emit AuditEtherPriceUpdated(value, msg.sender);
}
/**
* @dev Update team wallet address.
*/
function updateTeamWallet(address payable account) external onlyOwner {
_TEAM = account;
}
/**
* @dev Returns current max wei value.
*/
function weiMax() public view returns (uint256) {
for(uint16 i = 0; i < LIMIT_WEIS.length; i++) {
if (_seasonLimitAccounts[_season][i].length < LIMIT_COUNTER[i]) {
return LIMIT_WEIS[i];
}
}
return LIMIT_WEI_MIN;
}
/**
* @dev Returns the {limitIndex} and {weiMax}.
*/
function _limit(uint256 weiAmount) private view returns (uint256 __wei) {
uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender];
for(uint16 i = 0; i < LIMIT_WEIS.length; i++) {
if (__purchased >= LIMIT_WEIS[i]) {
return 0;
}
if (__purchased < LIMIT_WEIS[i]) {
__wei = LIMIT_WEIS[i].sub(__purchased);
if (weiAmount >= __wei && _seasonLimitAccounts[_season][i].length < LIMIT_COUNTER[i]) {
return __wei;
}
}
}
if (__purchased < LIMIT_WEI_MIN) {
return LIMIT_WEI_MIN.sub(__purchased);
}
}
/**
* @dev Updates the season limit accounts, or wei min accounts.
*/
function _updateSeasonLimits() private {
uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender];
if (__purchased > LIMIT_WEI_MIN) {
for(uint16 i = 0; i < LIMIT_WEIS.length; i++) {
if (__purchased >= LIMIT_WEIS[i]) {
_seasonLimitAccounts[_season][i].push(msg.sender);
return;
}
}
}
else if (__purchased == LIMIT_WEI_MIN) {
_seasonLimitWeiMinAccounts[_season].push(msg.sender);
return;
}
}
/**
* @dev Returns the accounts of wei limit, by `seasonNumber` and `limitIndex`.
*/
function seasonLimitAccounts(uint16 seasonNumber, uint16 limitIndex) public view returns (uint256 weis, address[] memory accounts) {
if (limitIndex < LIMIT_WEIS.length) {
weis = LIMIT_WEIS[limitIndex];
accounts = _seasonLimitAccounts[seasonNumber][limitIndex];
}
else {
weis = LIMIT_WEI_MIN;
accounts = _seasonLimitWeiMinAccounts[seasonNumber];
}
}
/**
* @dev constructor
*/
constructor () public {
_stage = 3277;
_season = _seasonNumber(_stage);
_vokenUsdPrice = _calcVokenUsdPrice(_stage);
_shareholdersRatio = _calcShareholdersRatio(_stage);
_TEAM = msg.sender;
addProxy(msg.sender);
}
/**
* @dev Receive ETH, and excute the exchange.
*/
function () external payable whenNotPaused {
require(_etherUsdPrice > 0, "VokenPublicSale2: Audit ETH price is zero");
require(_stage <= STAGE_MAX, "VokenPublicSale2: Voken Public-Sale Completled");
uint256 __usdAmount;
uint256 __usdRemain;
uint256 __usdUsed;
uint256 __weiUsed;
uint256 __voken;
// Limit
uint256 __weiMax = _limit(msg.value);
if (__weiMax < msg.value) {
__usdAmount = _wei2usd(__weiMax);
}
else {
__usdAmount = _wei2usd(msg.value);
}
__usdRemain = __usdAmount;
if (__usdRemain > 0) {
// cache
_cache();
// USD => Voken
while (gasleft() > GAS_MIN && __usdRemain > 0 && _stage <= STAGE_LIMIT) {
uint256 __txVokenIssued;
(__txVokenIssued, __usdRemain) = _tx(__usdRemain);
__voken = __voken.add(__txVokenIssued);
}
// Used
__usdUsed = __usdAmount.sub(__usdRemain);
__weiUsed = _usd2wei(__usdUsed);
// Whitelist
if (_cacheWhitelisted && __voken > 0) {
_mintVokenBonus(__voken);
for(uint16 i = 0; i < _cacheReferees.length; i++) {
address payable __referee = _cacheReferees[i];
uint256 __usdReward = __usdUsed.mul(_cacheRewards[i]).div(100);
uint256 __weiReward = __weiUsed.mul(_cacheRewards[i]).div(100);
__referee.transfer(__weiReward);
_usdRewarded = _usdRewarded.add(__usdReward);
_weiRewarded = _weiRewarded.add(__weiReward);
_accountUsdRewarded[__referee] = _accountUsdRewarded[__referee].add(__usdReward);
_accountWeiRewarded[__referee] = _accountWeiRewarded[__referee].add(__weiReward);
}
if (_cachePended > 0) {
_weiPended = _weiPended.add(__weiUsed.mul(_cachePended).div(100));
}
}
// Counter
if (__weiUsed > 0) {
_txs = _txs.add(1);
_usdSold = _usdSold.add(__usdUsed);
_weiSold = _weiSold.add(__weiUsed);
_accountUsdPurchased[msg.sender] = _accountUsdPurchased[msg.sender].add(__usdUsed);
_accountWeiPurchased[msg.sender] = _accountWeiPurchased[msg.sender].add(__weiUsed);
// Wei for SHAREHOLDERS
_weiShareholders = _weiShareholders.add(_cacheWeiShareholders);
(bool __bool,) = address(_SHAREHOLDERS).call.value(_cacheWeiShareholders)("");
assert(__bool);
// Wei for TEAM
uint256 __weiTeam = _weiSold.sub(_weiRewarded).sub(_weiShareholders).sub(_weiPended).sub(_weiTeam);
_weiTeam = _weiTeam.add(__weiTeam);
_TEAM.transfer(__weiTeam);
// Update season limits
_updateSeasonLimits();
}
// Reset cache
_resetCache();
}
// If wei remains, refund.
uint256 __weiRemain = msg.value.sub(__weiUsed);
if (__weiRemain > 0) {
msg.sender.transfer(__weiRemain);
}
}
/**
* @dev Cache.
*/
function _cache() private {
if (!_seasonHasAccount[_season][msg.sender]) {
_seasonAccounts[_season].push(msg.sender);
_seasonHasAccount[_season][msg.sender] = true;
}
_cacheWhitelisted = _VOKEN.whitelisted(msg.sender);
if (_cacheWhitelisted) {
address __account = msg.sender;
for(uint16 i = 0; i < REWARDS_PCT.length; i++) {
address __referee = _VOKEN.whitelistReferee(__account);
if (__referee != address(0) && __referee != __account && _VOKEN.whitelistReferralsCount(__referee) > i) {
if (!_seasonHasReferral[_season][__referee]) {
_seasonReferrals[_season].push(__referee);
_seasonHasReferral[_season][__referee] = true;
}
if (!_seasonAccountHasReferral[_season][__referee][__account]) {
_seasonAccountReferrals[_season][__referee].push(__account);
_seasonAccountHasReferral[_season][__referee][__account] = true;
}
_cacheReferees.push(address(uint160(__referee)));
_cacheRewards.push(REWARDS_PCT[i]);
}
else {
_cachePended = _cachePended.add(REWARDS_PCT[i]);
}
__account = __referee;
}
}
}
/**
* @dev Reset cache.
*/
function _resetCache() private {
delete _cacheWeiShareholders;
if (_cacheWhitelisted) {
delete _cacheWhitelisted;
delete _cacheReferees;
delete _cacheRewards;
delete _cachePended;
}
}
/**
* @dev USD => Voken
*/
function _tx(uint256 __usd) private returns (uint256 __voken, uint256 __usdRemain) {
uint256 __stageUsdCap = _stageUsdCap(_stage);
uint256 __usdUsed;
// in stage
if (_stageUsdSold[_stage].add(__usd) <= __stageUsdCap) {
__usdUsed = __usd;
(__voken, ) = _calcExchange(__usdUsed);
_mintVokenIssued(__voken);
// close stage, if stage dollor cap reached
if (__stageUsdCap == _stageUsdSold[_stage]) {
_closeStage();
}
}
// close stage
else {
__usdUsed = __stageUsdCap.sub(_stageUsdSold[_stage]);
(__voken, ) = _calcExchange(__usdUsed);
_mintVokenIssued(__voken);
_closeStage();
__usdRemain = __usd.sub(__usdUsed);
}
}
/**
* @dev USD => voken & wei, and make records.
*/
function _calcExchange(uint256 __usd) private returns (uint256 __voken, uint256 __wei) {
__wei = _usd2wei(__usd);
__voken = _usd2voken(__usd);
uint256 __usdShareholders = _2shareholders(__usd);
uint256 __weiShareholders = _usd2wei(__usdShareholders);
// Stage: usd
_stageUsdSold[_stage] = _stageUsdSold[_stage].add(__usd);
// Season: usd, wei
_seasonUsdSold[_season] = _seasonUsdSold[_season].add(__usd);
_seasonWeiSold[_season] = _seasonWeiSold[_season].add(__wei);
// Season: wei pended
if (_cachePended > 0) {
_seasonWeiPended[_season] = _seasonWeiPended[_season].add(__wei.mul(_cachePended).div(100));
}
// Season shareholders: usd, wei
_seasonUsdShareholders[_season] = _seasonUsdShareholders[_season].add(__usdShareholders);
_seasonWeiShareholders[_season] = _seasonWeiShareholders[_season].add(__weiShareholders);
// Cache
_cacheWeiShareholders = _cacheWeiShareholders.add(__weiShareholders);
// Season => account: usd, wei
_usdSeasonAccountPurchased[_season][msg.sender] = _usdSeasonAccountPurchased[_season][msg.sender].add(__usd);
_weiSeasonAccountPurchased[_season][msg.sender] = _weiSeasonAccountPurchased[_season][msg.sender].add(__wei);
// season referral account
if (_cacheWhitelisted) {
for (uint16 i = 0; i < _cacheRewards.length; i++) {
address __referee = _cacheReferees[i];
uint256 __usdReward = __usd.mul(_cacheRewards[i]).div(100);
uint256 __weiReward = __wei.mul(_cacheRewards[i]).div(100);
// season
_seasonUsdRewarded[_season] = _seasonUsdRewarded[_season].add(__usdReward);
_seasonWeiRewarded[_season] = _seasonWeiRewarded[_season].add(__weiReward);
// season => account
_usdSeasonAccountRewarded[_season][__referee] = _usdSeasonAccountRewarded[_season][__referee].add(__usdReward);
_weiSeasonAccountRewarded[_season][__referee] = _weiSeasonAccountRewarded[_season][__referee].add(__weiReward);
_usdSeasonAccountReferrals[_season][__referee] = _usdSeasonAccountReferrals[_season][__referee].add(__usd);
_weiSeasonAccountReferrals[_season][__referee] = _weiSeasonAccountReferrals[_season][__referee].add(__wei);
_vokenSeasonAccountReferrals[_season][__referee] = _vokenSeasonAccountReferrals[_season][__referee].add(__voken);
_accountVokenReferrals[__referee] = _accountVokenReferrals[__referee].add(__voken);
if (i == 0) {
_vokenSeasonAccountReferral[_season][__referee] = _vokenSeasonAccountReferral[_season][__referee].add(__voken);
_accountVokenReferral[__referee] = _accountVokenReferral[__referee].add(__voken);
}
}
}
}
/**
* @dev Mint Voken issued.
*/
function _mintVokenIssued(uint256 amount) private {
// Global
_vokenIssued = _vokenIssued.add(amount);
_vokenIssuedTxs = _vokenIssuedTxs.add(1);
// Account
_accountVokenIssued[msg.sender] = _accountVokenIssued[msg.sender].add(amount);
// Stage
_stageVokenIssued[_stage] = _stageVokenIssued[_stage].add(amount);
// Season
_seasonVokenIssued[_season] = _seasonVokenIssued[_season].add(amount);
_vokenSeasonAccountIssued[_season][msg.sender] = _vokenSeasonAccountIssued[_season][msg.sender].add(amount);
// Mint
assert(_VOKEN.mint(msg.sender, amount));
}
/**
* @dev Mint Voken bonus.
*/
function _mintVokenBonus(uint256 amount) private {
// Global
_vokenBonus = _vokenBonus.add(amount);
_vokenBonusTxs = _vokenBonusTxs.add(1);
// Account
_accountVokenBonus[msg.sender] = _accountVokenBonus[msg.sender].add(amount);
// Stage
_stageVokenBonus[_stage] = _stageVokenBonus[_stage].add(amount);
// Season
_seasonVokenBonus[_season] = _seasonVokenBonus[_season].add(amount);
_vokenSeasonAccountBonus[_season][msg.sender] = _vokenSeasonAccountBonus[_season][msg.sender].add(amount);
// Mint with allocation
Allocations.Allocation memory __allocation;
__allocation.amount = amount;
__allocation.timestamp = now;
_allocations[msg.sender].push(__allocation);
assert(_VOKEN.mintWithAllocation(msg.sender, amount, address(this)));
}
/**
* @dev Returns the reserved amount of VOKEN by `account`.
*/
function reservedOf(address account) public view returns (uint256) {
Allocations.Allocation[] memory __allocations = _allocations[account];
uint256 __len = __allocations.length;
if (__len > 0) {
uint256 __vokenIssued = _accountVokenIssued[account];
uint256 __vokenBonus = _accountVokenBonus[account];
uint256 __vokenReferral = _accountVokenReferral[account];
uint256 __vokenBalance = _VOKEN.balanceOf(account);
// balance fixed, by Voken issued.
if (__vokenIssued < __vokenBalance) {
__vokenBalance = __vokenBalance.sub(__vokenIssued);
}
else {
__vokenBalance = 0;
}
// balance fixed, by Voken bonus.
if (__vokenBonus < __vokenBalance) {
__vokenBalance = __vokenBalance.sub(__vokenBonus);
}
else {
__vokenBalance = 0;
}
uint256 __reserved;
for (uint256 i = 0; i < __len; i++) {
// Voken reserved.
Allocations.Allocation memory __allocation = __allocations[i];
__reserved = __reserved.add(__allocation.amount);
if (now >= __allocation.timestamp.add(90 days)) {
// default: 180 days.
uint256 __distance = 180 days;
// shorten the distance, by Voken referral, at least 120 days.
if (__vokenReferral > __allocation.amount) {
__distance = __distance.sub(__vokenReferral.div(__allocation.amount).mul(1 days));
if (__distance > 120 days) {
__distance = 120 days;
}
}
// shorten the distance, by Voken holding
if (__vokenBalance > __allocation.amount) {
__distance = __distance.sub(__vokenBalance.div(__allocation.amount).mul(30 days));
}
// at least: 90 days
if (__distance > 90 days) {
__distance = 90 days;
}
// calc reserved
uint256 __timestamp = __allocation.timestamp.add(__distance);
if (now > __timestamp) {
uint256 __passed = now.sub(__timestamp).div(1 days).add(1);
if (__passed > 30) {
__reserved = __reserved.sub(__allocation.amount);
}
else {
__reserved = __reserved.sub(__allocation.amount.mul(__passed).div(30));
}
}
}
}
return __reserved;
}
return 0;
}
} | If wei remains, refund. | uint256 __weiRemain = msg.value.sub(__weiUsed);
| 14,102,036 | [
1,
2047,
732,
77,
22632,
16,
16255,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
1001,
1814,
77,
1933,
530,
273,
1234,
18,
1132,
18,
1717,
12,
972,
1814,
77,
6668,
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
] |
pragma solidity ^0.4.21;
library BWUtility {
// -------- UTILITY FUNCTIONS ----------
// Return next higher even _multiple for _amount parameter (e.g used to round up to even finneys).
function ceil(uint _amount, uint _multiple) pure public returns (uint) {
return ((_amount + _multiple - 1) / _multiple) * _multiple;
}
// Checks if two coordinates are adjacent:
// xxx
// xox
// xxx
// All x (_x2, _xy2) are adjacent to o (_x1, _y1) in this ascii image.
// Adjacency does not wrapp around map edges so if y2 = 255 and y1 = 0 then they are not ajacent
function isAdjacent(uint8 _x1, uint8 _y1, uint8 _x2, uint8 _y2) pure public returns (bool) {
return ((_x1 == _x2 && (_y2 - _y1 == 1 || _y1 - _y2 == 1))) || // Same column
((_y1 == _y2 && (_x2 - _x1 == 1 || _x1 - _x2 == 1))) || // Same row
((_x2 - _x1 == 1 && (_y2 - _y1 == 1 || _y1 - _y2 == 1))) || // Right upper or lower diagonal
((_x1 - _x2 == 1 && (_y2 - _y1 == 1 || _y1 - _y2 == 1))); // Left upper or lower diagonal
}
// Converts (x, y) to tileId xy
function toTileId(uint8 _x, uint8 _y) pure public returns (uint16) {
return uint16(_x) << 8 | uint16(_y);
}
// Converts _tileId to (x, y)
function fromTileId(uint16 _tileId) pure public returns (uint8, uint8) {
uint8 y = uint8(_tileId);
uint8 x = uint8(_tileId >> 8);
return (x, y);
}
function getBoostFromTile(address _claimer, address _attacker, address _defender, uint _blockValue) pure public returns (uint, uint) {
if (_claimer == _attacker) {
return (_blockValue, 0);
} else if (_claimer == _defender) {
return (0, _blockValue);
}
}
}
interface ERC20I {
function transfer(address _recipient, uint256 _amount) external returns (bool);
function balanceOf(address _holder) external view returns (uint256);
}
contract BWService {
address private owner;
address private bw;
address private bwMarket;
BWData private bwData;
uint private seed = 42;
uint private WITHDRAW_FEE = 20; //1/20 = 5%
modifier isOwner {
if (msg.sender != owner) {
revert();
}
_;
}
modifier isValidCaller {
if (msg.sender != bw && msg.sender != bwMarket) {
revert();
}
_;
}
event TileClaimed(uint16 tileId, address newClaimer, uint priceInWei, uint creationTime);
event TileFortified(uint16 tileId, address claimer, uint addedValueInWei, uint priceInWei, uint fortifyTime); // Sent when a user fortifies an existing claim by bumping its value.
event TileAttackedSuccessfully(uint16 tileId, address attacker, uint attackAmount, uint totalAttackAmount, address defender, uint defendAmount, uint totalDefendAmount, uint attackRoll, uint attackTime); // Sent when a user successfully attacks a tile.
event TileDefendedSuccessfully(uint16 tileId, address attacker, uint attackAmount, uint totalAttackAmount, address defender, uint defendAmount, uint totalDefendAmount, uint attackRoll, uint defendTime); // Sent when a user successfully defends a tile when attacked.
event BlockValueMoved(uint16 sourceTileId, uint16 destTileId, address owner, uint movedBlockValue, uint postSourceValue, uint postDestValue, uint moveTime); // Sent when a user buys a tile from another user, by accepting a tile offer
event UserBattleValueUpdated(address userAddress, uint battleValue, bool isWithdraw);
// Constructor.
constructor(address _bwData) public {
bwData = BWData(_bwData);
owner = msg.sender;
}
// Can't send funds straight to this contract. Avoid people sending by mistake.
function () payable public {
revert();
}
// OWNER-ONLY FUNCTIONS
function kill() public isOwner {
selfdestruct(owner);
}
function setValidBwCaller(address _bw) public isOwner {
bw = _bw;
}
function setValidBwMarketCaller(address _bwMarket) public isOwner {
bwMarket = _bwMarket;
}
// TILE-RELATED FUNCTIONS
// This function claims multiple previously unclaimed tiles in a single transaction.
// The value assigned to each tile is the msg.value divided by the number of tiles claimed.
// The msg.value is required to be an even multiple of the number of tiles claimed.
function storeInitialClaim(address _msgSender, uint16[] _claimedTileIds, uint _claimAmount, bool _useBattleValue) public isValidCaller {
uint tileCount = _claimedTileIds.length;
require(tileCount > 0);
require(_claimAmount >= 1 finney * tileCount); // ensure enough funds paid for all tiles
require(_claimAmount % tileCount == 0); // ensure payment is an even multiple of number of tiles claimed
uint valuePerBlockInWei = _claimAmount / tileCount; // Due to requires above this is guaranteed to be an even number
if (_useBattleValue) {
subUserBattleValue(_msgSender, _claimAmount, false);
}
addGlobalBlockValueBalance(_claimAmount);
uint16 tileId;
bool isNewTile;
for (uint16 i = 0; i < tileCount; i++) {
tileId = _claimedTileIds[i];
isNewTile = bwData.isNewTile(tileId); // Is length 0 if first time purchased
require(isNewTile); // Can only claim previously unclaimed tiles.
// Send claim event
emit TileClaimed(tileId, _msgSender, valuePerBlockInWei, block.timestamp);
// Update contract state with new tile ownership.
bwData.storeClaim(tileId, _msgSender, valuePerBlockInWei);
}
}
function fortifyClaims(address _msgSender, uint16[] _claimedTileIds, uint _fortifyAmount, bool _useBattleValue) public isValidCaller {
uint tileCount = _claimedTileIds.length;
require(tileCount > 0);
uint balance = address(this).balance;
require(balance + _fortifyAmount > balance); // prevent overflow
require(_fortifyAmount % tileCount == 0); // ensure payment is an even multiple of number of tiles fortified
uint addedValuePerTileInWei = _fortifyAmount / tileCount; // Due to requires above this is guaranteed to be an even number
require(_fortifyAmount >= 1 finney * tileCount); // ensure enough funds paid for all tiles
address claimer;
uint blockValue;
for (uint16 i = 0; i < tileCount; i++) {
(claimer, blockValue) = bwData.getTileClaimerAndBlockValue(_claimedTileIds[i]);
require(claimer != 0); // Can't do this on never-owned tiles
require(claimer == _msgSender); // Only current claimer can fortify claim
if (_useBattleValue) {
subUserBattleValue(_msgSender, addedValuePerTileInWei, false);
}
fortifyClaim(_msgSender, _claimedTileIds[i], addedValuePerTileInWei);
}
}
function fortifyClaim(address _msgSender, uint16 _claimedTileId, uint _fortifyAmount) private {
uint blockValue;
uint sellPrice;
(blockValue, sellPrice) = bwData.getCurrentBlockValueAndSellPriceForTile(_claimedTileId);
uint updatedBlockValue = blockValue + _fortifyAmount;
// Send fortify event
emit TileFortified(_claimedTileId, _msgSender, _fortifyAmount, updatedBlockValue, block.timestamp);
// Update tile value. The tile has been fortified by bumping up its value.
bwData.updateTileBlockValue(_claimedTileId, updatedBlockValue);
// Track addition to global block value
addGlobalBlockValueBalance(_fortifyAmount);
}
// Return a pseudo random number between lower and upper bounds
// given the number of previous blocks it should hash.
// Random function copied from https://github.com/axiomzen/eth-random/blob/master/contracts/Random.sol.
// Changed sha3 to keccak256.
// Changed random range from uint64 to uint (=uint256).
function random(uint _upper) private returns (uint) {
seed = uint(keccak256(keccak256(blockhash(block.number), seed), now));
return seed % _upper;
}
// A user tries to claim a tile that's already owned by another user. A battle ensues.
// A random roll is done with % based on attacking vs defending amounts.
function attackTile(address _msgSender, uint16 _tileId, uint _attackAmount, bool _useBattleValue, bool _autoFortify) public isValidCaller {
require(_attackAmount >= 1 finney); // Don't allow attacking with less than one base tile price.
require(_attackAmount % 1 finney == 0);
address claimer;
uint blockValue;
(claimer, blockValue) = bwData.getTileClaimerAndBlockValue(_tileId);
require(claimer != 0); // Can't do this on never-owned tiles
require(claimer != _msgSender); // Can't attack one's own tiles
require(claimer != owner); // Can't attack owner's tiles because it is used for raffle.
// Calculate boosted amounts for attacker and defender
// The base attack amount is sent in the by the user.
// The base defend amount is the attacked tile's current blockValue.
uint attackBoost;
uint defendBoost;
(attackBoost, defendBoost) = bwData.calculateBattleBoost(_tileId, _msgSender, claimer);
uint totalAttackAmount = _attackAmount + attackBoost;
uint totalDefendAmount = blockValue + defendBoost;
require(totalAttackAmount >= _attackAmount); // prevent overflow
require(totalDefendAmount >= blockValue); // prevent overflow
require(totalAttackAmount + totalDefendAmount > totalAttackAmount && totalAttackAmount + totalDefendAmount > totalDefendAmount); // Prevent overflow
// Verify that attack odds are within allowed range.
require(totalAttackAmount / 10 <= blockValue); // Disallow attacks with more than 1000% of defendAmount
require(totalAttackAmount >= blockValue / 10); // Disallow attacks with less than 10% of defendAmount
// The battle considers boosts.
uint attackRoll = random(totalAttackAmount + totalDefendAmount); // This is where the excitement happens!
if (attackRoll > totalDefendAmount) {
// Send update event
emit TileAttackedSuccessfully(_tileId, _msgSender, _attackAmount, totalAttackAmount, claimer, blockValue, totalDefendAmount, attackRoll, block.timestamp);
// Change block owner but keep same block value (attacker got battlevalue instead)
bwData.setClaimerForTile(_tileId, _msgSender);
// Tile successfully attacked!
if (_useBattleValue) {
if (_autoFortify) {
// Fortify the won tile using battle value
fortifyClaim(_msgSender, _tileId, _attackAmount);
subUserBattleValue(_msgSender, _attackAmount, false);
} else {
// No reason to withdraw followed by deposit of same amount
}
} else {
if (_autoFortify) {
// Fortify the won tile using attack amount
fortifyClaim(_msgSender, _tileId, _attackAmount);
} else {
addUserBattleValue(_msgSender, _attackAmount); // Don't include boost here!
}
}
} else {
// Tile successfully defended!
if (_useBattleValue) {
subUserBattleValue(_msgSender, _attackAmount, false); // Don't include boost here!
}
addUserBattleValue(claimer, _attackAmount); // Don't include boost here!
// Send update event
emit TileDefendedSuccessfully(_tileId, _msgSender, _attackAmount, totalAttackAmount, claimer, blockValue, totalDefendAmount, attackRoll, block.timestamp);
// Update the timestamp for the defended block.
bwData.updateTileTimeStamp(_tileId);
}
}
function moveBlockValue(address _msgSender, uint8 _xSource, uint8 _ySource, uint8 _xDest, uint8 _yDest, uint _moveAmount) public isValidCaller {
uint16 sourceTileId = BWUtility.toTileId(_xSource, _ySource);
uint16 destTileId = BWUtility.toTileId(_xDest, _yDest);
address sourceTileClaimer;
address destTileClaimer;
uint sourceTileBlockValue;
uint destTileBlockValue;
(sourceTileClaimer, sourceTileBlockValue) = bwData.getTileClaimerAndBlockValue(sourceTileId);
(destTileClaimer, destTileBlockValue) = bwData.getTileClaimerAndBlockValue(destTileId);
require(sourceTileClaimer == _msgSender);
require(destTileClaimer == _msgSender);
require(_moveAmount >= 1 finney); // Can't be less
require(_moveAmount % 1 finney == 0); // Move amount must be in multiples of 1 finney
// require(sourceTile.blockValue - _moveAmount >= BASE_TILE_PRICE_WEI); // Must always leave some at source
require(sourceTileBlockValue - _moveAmount < sourceTileBlockValue); // Prevent overflow
require(destTileBlockValue + _moveAmount > destTileBlockValue); // Prevent overflow
require(BWUtility.isAdjacent(_xSource, _ySource, _xDest, _yDest));
sourceTileBlockValue -= _moveAmount;
destTileBlockValue += _moveAmount;
// If ALL block value was moved away from the source tile, we lose our claim to it. It becomes ownerless.
if (sourceTileBlockValue == 0) {
bwData.deleteTile(sourceTileId);
} else {
bwData.updateTileBlockValue(sourceTileId, sourceTileBlockValue);
bwData.deleteOffer(sourceTileId); // Offer invalid since block value has changed
}
bwData.updateTileBlockValue(destTileId, destTileBlockValue);
bwData.deleteOffer(destTileId); // Offer invalid since block value has changed
emit BlockValueMoved(sourceTileId, destTileId, _msgSender, _moveAmount, sourceTileBlockValue, destTileBlockValue, block.timestamp);
}
// BATTLE VALUE FUNCTIONS
function withdrawBattleValue(address msgSender, uint _battleValueInWei) public isValidCaller returns (uint) {
require(bwData.hasUser(msgSender));
require(_battleValueInWei % 1 finney == 0); // Must be divisible by 1 finney
uint fee = _battleValueInWei / WITHDRAW_FEE; // Since we divide by 20 we can never create infinite fractions, so we'll always count in whole wei amounts.
require(_battleValueInWei - fee < _battleValueInWei); // prevent underflow
uint amountToWithdraw = _battleValueInWei - fee;
uint feeBalance = bwData.getFeeBalance();
require(feeBalance + fee >= feeBalance); // prevent overflow
feeBalance += fee;
bwData.setFeeBalance(feeBalance);
subUserBattleValue(msgSender, _battleValueInWei, true);
return amountToWithdraw;
}
function addUserBattleValue(address _userId, uint _amount) public isValidCaller {
uint userBattleValue = bwData.getUserBattleValue(_userId);
require(userBattleValue + _amount > userBattleValue); // prevent overflow
uint newBattleValue = userBattleValue + _amount;
bwData.setUserBattleValue(_userId, newBattleValue); // Don't include boost here!
emit UserBattleValueUpdated(_userId, newBattleValue, false);
}
function subUserBattleValue(address _userId, uint _amount, bool _isWithdraw) public isValidCaller {
uint userBattleValue = bwData.getUserBattleValue(_userId);
require(_amount <= userBattleValue); // Must be less than user's battle value - also implicitly checks that underflow isn't possible
uint newBattleValue = userBattleValue - _amount;
bwData.setUserBattleValue(_userId, newBattleValue); // Don't include boost here!
emit UserBattleValueUpdated(_userId, newBattleValue, _isWithdraw);
}
function addGlobalBlockValueBalance(uint _amount) public isValidCaller {
// Track addition to global block value.
uint blockValueBalance = bwData.getBlockValueBalance();
require(blockValueBalance + _amount > blockValueBalance); // Prevent overflow
bwData.setBlockValueBalance(blockValueBalance + _amount);
}
// Allow us to transfer out airdropped tokens if we ever receive any
function transferTokens(address _tokenAddress, address _recipient) public isOwner {
ERC20I token = ERC20I(_tokenAddress);
require(token.transfer(_recipient, token.balanceOf(this)));
}
}
contract BWData {
address public owner;
address private bwService;
address private bw;
address private bwMarket;
uint private blockValueBalance = 0;
uint private feeBalance = 0;
uint private BASE_TILE_PRICE_WEI = 1 finney; // 1 milli-ETH.
mapping (address => User) private users; // user address -> user information
mapping (uint16 => Tile) private tiles; // tileId -> list of TileClaims for that particular tile
// Info about the users = those who have purchased tiles.
struct User {
uint creationTime;
bool censored;
uint battleValue;
}
// Info about a tile ownership
struct Tile {
address claimer;
uint blockValue;
uint creationTime;
uint sellPrice; // If 0 -> not on marketplace. If > 0 -> on marketplace.
}
struct Boost {
uint8 numAttackBoosts;
uint8 numDefendBoosts;
uint attackBoost;
uint defendBoost;
}
constructor() public {
owner = msg.sender;
}
// Can't send funds straight to this contract. Avoid people sending by mistake.
function () payable public {
revert();
}
function kill() public isOwner {
selfdestruct(owner);
}
modifier isValidCaller {
if (msg.sender != bwService && msg.sender != bw && msg.sender != bwMarket) {
revert();
}
_;
}
modifier isOwner {
if (msg.sender != owner) {
revert();
}
_;
}
function setBwServiceValidCaller(address _bwService) public isOwner {
bwService = _bwService;
}
function setBwValidCaller(address _bw) public isOwner {
bw = _bw;
}
function setBwMarketValidCaller(address _bwMarket) public isOwner {
bwMarket = _bwMarket;
}
// ----------USER-RELATED GETTER FUNCTIONS------------
//function getUser(address _user) view public returns (bytes32) {
//BWUtility.User memory user = users[_user];
//require(user.creationTime != 0);
//return (user.creationTime, user.imageUrl, user.tag, user.email, user.homeUrl, user.creationTime, user.censored, user.battleValue);
//}
function addUser(address _msgSender) public isValidCaller {
User storage user = users[_msgSender];
require(user.creationTime == 0);
user.creationTime = block.timestamp;
}
function hasUser(address _user) view public isValidCaller returns (bool) {
return users[_user].creationTime != 0;
}
// ----------TILE-RELATED GETTER FUNCTIONS------------
function getTile(uint16 _tileId) view public isValidCaller returns (address, uint, uint, uint) {
Tile storage currentTile = tiles[_tileId];
return (currentTile.claimer, currentTile.blockValue, currentTile.creationTime, currentTile.sellPrice);
}
function getTileClaimerAndBlockValue(uint16 _tileId) view public isValidCaller returns (address, uint) {
Tile storage currentTile = tiles[_tileId];
return (currentTile.claimer, currentTile.blockValue);
}
function isNewTile(uint16 _tileId) view public isValidCaller returns (bool) {
Tile storage currentTile = tiles[_tileId];
return currentTile.creationTime == 0;
}
function storeClaim(uint16 _tileId, address _claimer, uint _blockValue) public isValidCaller {
tiles[_tileId] = Tile(_claimer, _blockValue, block.timestamp, 0);
}
function updateTileBlockValue(uint16 _tileId, uint _blockValue) public isValidCaller {
tiles[_tileId].blockValue = _blockValue;
}
function setClaimerForTile(uint16 _tileId, address _claimer) public isValidCaller {
tiles[_tileId].claimer = _claimer;
}
function updateTileTimeStamp(uint16 _tileId) public isValidCaller {
tiles[_tileId].creationTime = block.timestamp;
}
function getCurrentClaimerForTile(uint16 _tileId) view public isValidCaller returns (address) {
Tile storage currentTile = tiles[_tileId];
if (currentTile.creationTime == 0) {
return 0;
}
return currentTile.claimer;
}
function getCurrentBlockValueAndSellPriceForTile(uint16 _tileId) view public isValidCaller returns (uint, uint) {
Tile storage currentTile = tiles[_tileId];
if (currentTile.creationTime == 0) {
return (0, 0);
}
return (currentTile.blockValue, currentTile.sellPrice);
}
function getBlockValueBalance() view public isValidCaller returns (uint){
return blockValueBalance;
}
function setBlockValueBalance(uint _blockValueBalance) public isValidCaller {
blockValueBalance = _blockValueBalance;
}
function getFeeBalance() view public isValidCaller returns (uint) {
return feeBalance;
}
function setFeeBalance(uint _feeBalance) public isValidCaller {
feeBalance = _feeBalance;
}
function getUserBattleValue(address _userId) view public isValidCaller returns (uint) {
return users[_userId].battleValue;
}
function setUserBattleValue(address _userId, uint _battleValue) public isValidCaller {
users[_userId].battleValue = _battleValue;
}
function verifyAmount(address _msgSender, uint _msgValue, uint _amount, bool _useBattleValue) view public isValidCaller {
User storage user = users[_msgSender];
require(user.creationTime != 0);
if (_useBattleValue) {
require(_msgValue == 0);
require(user.battleValue >= _amount);
} else {
require(_amount == _msgValue);
}
}
function addBoostFromTile(Tile _tile, address _attacker, address _defender, Boost memory _boost) pure private {
if (_tile.claimer == _attacker) {
require(_boost.attackBoost + _tile.blockValue >= _tile.blockValue); // prevent overflow
_boost.attackBoost += _tile.blockValue;
_boost.numAttackBoosts += 1;
} else if (_tile.claimer == _defender) {
require(_boost.defendBoost + _tile.blockValue >= _tile.blockValue); // prevent overflow
_boost.defendBoost += _tile.blockValue;
_boost.numDefendBoosts += 1;
}
}
function calculateBattleBoost(uint16 _tileId, address _attacker, address _defender) view public isValidCaller returns (uint, uint) {
uint8 x;
uint8 y;
(x, y) = BWUtility.fromTileId(_tileId);
Boost memory boost = Boost(0, 0, 0, 0);
// We overflow x, y on purpose here if x or y is 0 or 255 - the map overflows and so should adjacency.
// Go through all adjacent tiles to (x, y).
if (y != 255) {
if (x != 255) {
addBoostFromTile(tiles[BWUtility.toTileId(x+1, y+1)], _attacker, _defender, boost);
}
addBoostFromTile(tiles[BWUtility.toTileId(x, y+1)], _attacker, _defender, boost);
if (x != 0) {
addBoostFromTile(tiles[BWUtility.toTileId(x-1, y+1)], _attacker, _defender, boost);
}
}
if (x != 255) {
addBoostFromTile(tiles[BWUtility.toTileId(x+1, y)], _attacker, _defender, boost);
}
if (x != 0) {
addBoostFromTile(tiles[BWUtility.toTileId(x-1, y)], _attacker, _defender, boost);
}
if (y != 0) {
if(x != 255) {
addBoostFromTile(tiles[BWUtility.toTileId(x+1, y-1)], _attacker, _defender, boost);
}
addBoostFromTile(tiles[BWUtility.toTileId(x, y-1)], _attacker, _defender, boost);
if(x != 0) {
addBoostFromTile(tiles[BWUtility.toTileId(x-1, y-1)], _attacker, _defender, boost);
}
}
// The benefit of boosts is multiplicative (quadratic):
// - More boost tiles gives a higher total blockValue (the sum of the adjacent tiles)
// - More boost tiles give a higher multiple of that total blockValue that can be used (10% per adjacent tie)
// Example:
// A) I boost attack with 1 single tile worth 10 finney
// -> Total boost is 10 * 1 / 10 = 1 finney
// B) I boost attack with 3 tiles worth 1 finney each
// -> Total boost is (1+1+1) * 3 / 10 = 0.9 finney
// C) I boost attack with 8 tiles worth 2 finney each
// -> Total boost is (2+2+2+2+2+2+2+2) * 8 / 10 = 14.4 finney
// D) I boost attack with 3 tiles of 1, 5 and 10 finney respectively
// -> Total boost is (ss1+5+10) * 3 / 10 = 4.8 finney
// This division by 10 can't create fractions since our uint is wei, and we can't have overflow from the multiplication
// We do allow fractions of finney here since the boosted values aren't stored anywhere, only used for attack rolls and sent in events
boost.attackBoost = (boost.attackBoost / 10 * boost.numAttackBoosts);
boost.defendBoost = (boost.defendBoost / 10 * boost.numDefendBoosts);
return (boost.attackBoost, boost.defendBoost);
}
function censorUser(address _userAddress, bool _censored) public isValidCaller {
User storage user = users[_userAddress];
require(user.creationTime != 0);
user.censored = _censored;
}
function deleteTile(uint16 _tileId) public isValidCaller {
delete tiles[_tileId];
}
function setSellPrice(uint16 _tileId, uint _sellPrice) public isValidCaller {
tiles[_tileId].sellPrice = _sellPrice; //testrpc cannot estimate gas when delete is used.
}
function deleteOffer(uint16 _tileId) public isValidCaller {
tiles[_tileId].sellPrice = 0; //testrpc cannot estimate gas when delete is used.
}
}
/**
* Copyright 2018 Block Wars Team
*
*/
contract BW {
address public owner;
BWService private bwService;
BWData private bwData;
bool public paused = false;
modifier isOwner {
if (msg.sender != owner) {
revert();
}
_;
}
// Checks if entire game (except battle value withdraw) is paused or not.
modifier isNotPaused {
if (paused) {
revert();
}
_;
}
// Only allow wallets to call this function, not contracts.
modifier isNotContractCaller {
require(msg.sender == tx.origin);
_;
}
// All contract event types.
event UserCreated(address userAddress, bytes32 name, bytes imageUrl, bytes32 tag, bytes32 homeUrl, uint creationTime, address invitedBy);
event UserCensored(address userAddress, bool isCensored);
event TransferTileFromOwner(uint16 tileId, address seller, address buyer, uint acceptTime); // Sent when a user buys a tile from another user, by accepting a tile offer
event UserUpdated(address userAddress, bytes32 name, bytes imageUrl, bytes32 tag, bytes32 homeUrl, uint updateTime);
// BASIC CONTRACT FUNCTIONS
// Constructor.
constructor(address _bwService, address _bwData) public {
bwService = BWService(_bwService);
bwData = BWData(_bwData);
owner = msg.sender;
}
// Can't send funds straight to this contract. Avoid people sending by mistake.
function () payable public {
revert();
}
// Allow a new user to claim one or more previously unclaimed tiles by paying Ether.
function claimTilesForNewUser(bytes32 _name, bytes _imageUrl, bytes32 _tag, bytes32 _homeUrl, uint16[] _claimedTileIds, address _invitedBy) payable public isNotPaused isNotContractCaller {
bwData.addUser(msg.sender);
emit UserCreated(msg.sender, _name, _imageUrl, _tag, _homeUrl, block.timestamp, _invitedBy);
bwService.storeInitialClaim(msg.sender, _claimedTileIds, msg.value, false);
}
// Allow an existing user to claim one or more previously unclaimed tiles by paying Ether.
function claimTilesForExistingUser(uint16[] _claimedTileIds, uint _claimAmount, bool _useBattleValue) payable public isNotPaused isNotContractCaller {
bwData.verifyAmount(msg.sender, msg.value, _claimAmount, _useBattleValue);
bwService.storeInitialClaim(msg.sender, _claimedTileIds, _claimAmount, _useBattleValue);
}
// Allow users to change name, image URL, tag and home URL. Not censored status or battle value though.
function updateUser(bytes32 _name, bytes _imageUrl, bytes32 _tag, bytes32 _homeUrl) public isNotPaused isNotContractCaller {
require(bwData.hasUser(msg.sender));
// All the updated values are stored in events only so there's no state to update on the contract here.
emit UserUpdated(msg.sender, _name, _imageUrl, _tag, _homeUrl, block.timestamp);
}
// This function fortifies multiple previously claimed tiles in a single transaction.
// The value assigned to each tile is the msg.value divided by the number of tiles fortified.
// The msg.value is required to be an even multiple of the number of tiles fortified.
// Only tiles owned by msg.sender can be fortified.
function fortifyClaims(uint16[] _claimedTileIds, uint _fortifyAmount, bool _useBattleValue) payable public isNotPaused isNotContractCaller {
bwData.verifyAmount(msg.sender, msg.value, _fortifyAmount, _useBattleValue);
bwService.fortifyClaims(msg.sender, _claimedTileIds, _fortifyAmount, _useBattleValue);
}
// A new user attacks a tile claimed by someone else, trying to make it theirs through battle.
function attackTileForNewUser(uint16 _tileId, bytes32 _name, bytes _imageUrl, bytes32 _tag, bytes32 _homeUrl, address _invitedBy) payable public isNotPaused isNotContractCaller {
bwData.addUser(msg.sender);
emit UserCreated(msg.sender, _name, _imageUrl, _tag, _homeUrl, block.timestamp, _invitedBy);
bwService.attackTile(msg.sender, _tileId, msg.value, false, false);
}
// An existing user attacks a tile claimed by someone else, trying to make it theirs through battle.
function attackTileForExistingUser(uint16 _tileId, uint _attackAmount, bool _useBattleValue, bool _autoFortify) payable public isNotPaused isNotContractCaller {
bwData.verifyAmount(msg.sender, msg.value, _attackAmount, _useBattleValue);
bwService.attackTile(msg.sender, _tileId, _attackAmount, _useBattleValue, _autoFortify);
}
// Move "army" = block value from one block to an adjacent block. Moving ALL value equates giving up ownership of the source tile.
function moveBlockValue(uint8 _xSource, uint8 _ySource, uint8 _xDest, uint8 _yDest, uint _moveAmount) public isNotPaused isNotContractCaller {
bwService.moveBlockValue(msg.sender, _xSource, _ySource, _xDest, _yDest, _moveAmount);
}
// Allow users to withdraw battle value in Ether.
function withdrawBattleValue(uint _battleValueInWei) public isNotContractCaller {
uint amountToWithdraw = bwService.withdrawBattleValue(msg.sender, _battleValueInWei);
msg.sender.transfer(amountToWithdraw);
}
// -------- OWNER-ONLY FUNCTIONS ----------
// Only used by owner for raffle. Owner need name, address and picture from user.
// These users can then be given tiles by owner using transferTileFromOwner.
function createNewUser(bytes32 _name, bytes _imageUrl, address _user) public isOwner {
bwData.addUser(_user);
emit UserCreated(msg.sender, _name, _imageUrl, 0x0, 0x0, block.timestamp, 0x0);
}
// Allow updating censored status. Owner only. In case someone uploads offensive content.
// The contract owners reserve the right to apply censorship. This will mean that the
// name, tag or URL images might not be displayed for a censored user.
function censorUser(address _userAddress, bool _censored) public isOwner {
bwData.censorUser(_userAddress, _censored);
emit UserCensored(_userAddress, _censored);
}
// Pause the entire game, but let users keep withdrawing battle value
function setPaused(bool _paused) public isOwner {
paused = _paused;
}
function kill() public isOwner {
selfdestruct(owner);
}
function withdrawValue(bool _isFee) public isOwner {
uint balance = address(this).balance;
uint amountToWithdraw;
if (_isFee) {
amountToWithdraw = bwData.getFeeBalance();
if (balance < amountToWithdraw) { // Should never happen, but paranoia
amountToWithdraw = balance;
}
bwData.setFeeBalance(0);
} else {
amountToWithdraw = bwData.getBlockValueBalance();
if (balance < amountToWithdraw) { // Should never happen, but paranoia
amountToWithdraw = balance;
}
bwData.setBlockValueBalance(0);
}
owner.transfer(amountToWithdraw);
}
function depositBattleValue(address _user) payable public isOwner {
require(bwData.hasUser(_user));
require(msg.value % 1 finney == 0); // Must be divisible by 1 finney
bwService.addUserBattleValue(_user, msg.value);
}
// The owner can transfer ownership of own tiles to other users, as prizes in competitions.
function transferTileFromOwner(uint16 _tileId, address _newOwner) public payable isOwner {
address claimer = bwData.getCurrentClaimerForTile(_tileId);
require(claimer == owner);
require(bwData.hasUser(_newOwner));
require(msg.value % 1 finney == 0); // Must be divisible by 1 finney
uint balance = address(this).balance;
require(balance + msg.value >= balance); // prevent overflow
bwData.setClaimerForTile(_tileId, _newOwner);
bwService.addUserBattleValue(_newOwner, msg.value);
emit TransferTileFromOwner(_tileId, _newOwner, msg.sender, block.timestamp);
}
// Allow us to transfer out airdropped tokens if we ever receive any
function transferTokens(address _tokenAddress, address _recipient) public isOwner {
ERC20I token = ERC20I(_tokenAddress);
require(token.transfer(_recipient, token.balanceOf(this)));
}
} | Info about a tile ownership | struct Tile {
address claimer;
uint blockValue;
uint creationTime;
}
| 6,679 | [
1,
966,
2973,
279,
4769,
23178,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1958,
13791,
288,
203,
3639,
1758,
927,
69,
4417,
31,
203,
3639,
2254,
1203,
620,
31,
203,
3639,
2254,
6710,
950,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.7.0;
contract SimpleStorage {
uint storedData;
uint store_x;
address payable account = 0xd025bb843c766f6d70AA9221f7532AD9Ae1FD0aB;
address public owner;
uint8 private clientCount;
struct Bet {
address payable player;
uint amt;
}
Bet[] bets;
// constructor() public payable {
// require(msg.value == 30 ether, "30 ether initial funding required");
// /* Set the owner to the creator of this contract */
// owner = msg.sender;
// clientCount = 0;
// }
function pay() public payable {}
function () external payable {}
function random(uint nonce) internal view returns (uint) {
uint randomnumber = uint(keccak256(abi.encodePacked(msg.sender, nonce))) % 2;
// randomnumber = randomnumber + 11;
return randomnumber;
}
function seedMoney() public payable{
require(msg.value >= 0.1 ether, "too low you poor son of a bitch");
}
function Match() public payable returns (uint){
require(address(this).balance >= msg.value, "ether nhi h");
bets.push(Bet(msg.sender, msg.value));
uint rand = random(1);
if(rand == 0) {
return(0);
}
else {
uint xx = msg.value * 2;
account.transfer(xx);
return(1);
}
}
function Match_7() public payable returns (uint){
require(address(this).balance >= msg.value, "ether nhi h");
bets.push(Bet(msg.sender, msg.value));
uint rand = random(14);
if(rand <= 7) {
return(0);
}
else if(rand == 7){
return(0);
}
else {
uint xx = msg.value * 2;
account.transfer(xx);
return(1);
}
}
function set(uint x) public payable {
storedData = x;
store_x = random(uint(x));
uint xx = msg.value / 2;
account.transfer(xx);
}
function transfer_to_account() external payable {
account.transfer(50000000000000000);
// _addr.send(0.1 ether);
}
function get_contract_balance() public view returns (uint){
return uint(address(this).balance);
}
function get_contract_address() public view returns (address) {
return address(this);
}
// to transfer to smart contract
//
}
| randomnumber = randomnumber + 11; | function random(uint nonce) internal view returns (uint) {
uint randomnumber = uint(keccak256(abi.encodePacked(msg.sender, nonce))) % 2;
return randomnumber;
}
| 12,837,965 | [
1,
9188,
2696,
273,
2744,
2696,
397,
4648,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
2744,
12,
11890,
7448,
13,
2713,
1476,
1135,
261,
11890,
13,
288,
203,
565,
2254,
2744,
2696,
273,
2254,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
3576,
18,
15330,
16,
7448,
20349,
738,
576,
31,
203,
565,
327,
2744,
2696,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.