Unnamed: 0 int64 0 7.36k | comments stringlengths 3 35.2k | code_string stringlengths 1 527k | code stringlengths 1 527k | __index_level_0__ int64 0 88.6k |
|---|---|---|---|---|
0 | // Pool Errors. / | interface IPoolErrors {
/**************************/
/*** Common Pool Errors ***/
/**************************/
/**
* @notice `LP` allowance is already set by the owner.
*/
error AllowanceAlreadySet();
/**
* @notice The action cannot be executed on an active auction.
*/
error AuctionActive();
/**
* @notice Attempted auction to clear doesn't meet conditions.
*/
error AuctionNotClearable();
/**
* @notice Head auction should be cleared prior of executing this action.
*/
error AuctionNotCleared();
/**
* @notice The auction price is greater than the arbed bucket price.
*/
error AuctionPriceGtBucketPrice();
/**
* @notice Pool already initialized.
*/
error AlreadyInitialized();
/**
* @notice Borrower is attempting to create or modify a loan such that their loan's quote token would be less than the pool's minimum debt amount.
*/
error AmountLTMinDebt();
/**
* @notice Recipient of borrowed quote tokens doesn't match the caller of the `drawDebt` function.
*/
error BorrowerNotSender();
/**
* @notice Borrower has a healthy over-collateralized position.
*/
error BorrowerOk();
/**
* @notice Borrower is attempting to borrow more quote token than they have collateral for.
*/
error BorrowerUnderCollateralized();
/**
* @notice Operation cannot be executed in the same block when bucket becomes insolvent.
*/
error BucketBankruptcyBlock();
/**
* @notice User attempted to merge collateral from a lower price bucket into a higher price bucket.
*/
error CannotMergeToHigherPrice();
/**
* @notice User attempted an operation which does not exceed the dust amount, or leaves behind less than the dust amount.
*/
error DustAmountNotExceeded();
/**
* @notice Callback invoked by `flashLoan` function did not return the expected hash (see `ERC-3156` spec).
*/
error FlashloanCallbackFailed();
/**
* @notice Balance of pool contract before flashloan is different than the balance after flashloan.
*/
error FlashloanIncorrectBalance();
/**
* @notice Pool cannot facilitate a flashloan for the specified token address.
*/
error FlashloanUnavailableForToken();
/**
* @notice User is attempting to move or pull more collateral than is available.
*/
error InsufficientCollateral();
/**
* @notice Lender is attempting to move or remove more collateral they have claim to in the bucket.
* @notice Lender is attempting to remove more collateral they have claim to in the bucket.
* @notice Lender must have enough `LP` to claim the desired amount of quote from the bucket.
*/
error InsufficientLP();
/**
* @notice Bucket must have more quote available in the bucket than the lender is attempting to claim.
*/
error InsufficientLiquidity();
/**
* @notice When increasing / decreasing `LP` allowances indexes and amounts arrays parameters should have same length.
*/
error InvalidAllowancesInput();
/**
* @notice When transferring `LP` between indices, the new index must be a valid index.
*/
error InvalidIndex();
/**
* @notice The amount used for performed action should be greater than `0`.
*/
error InvalidAmount();
/**
* @notice Borrower is attempting to borrow more quote token than is available before the supplied `limitIndex`.
*/
error LimitIndexExceeded();
/**
* @notice When moving quote token `HTP` must stay below `LUP`.
* @notice When removing quote token `HTP` must stay below `LUP`.
*/
error LUPBelowHTP();
/**
* @notice Liquidation must result in `LUP` below the borrowers threshold price.
*/
error LUPGreaterThanTP();
/**
* @notice From index and to index arguments to move are the same.
*/
error MoveToSameIndex();
/**
* @notice Owner of the `LP` must have approved the new owner prior to transfer.
*/
error NoAllowance();
/**
* @notice Actor is attempting to take or clear an inactive auction.
*/
error NoAuction();
/**
* @notice No pool reserves are claimable.
*/
error NoReserves();
/**
* @notice Actor is attempting to take or clear an inactive reserves auction.
*/
error NoReservesAuction();
/**
* @notice Lender must have non-zero `LP` when attemptign to remove quote token from the pool.
*/
error NoClaim();
/**
* @notice Borrower has no debt to liquidate.
* @notice Borrower is attempting to repay when they have no outstanding debt.
*/
error NoDebt();
/**
* @notice Borrower is attempting to borrow an amount of quote tokens that will push the pool into under-collateralization.
*/
error PoolUnderCollateralized();
/**
* @notice Actor is attempting to add or move quote tokens at a price below the `LUP`.
* @notice Actor is attempting to kick with bucket price below the `LUP`.
*/
error PriceBelowLUP();
/**
* @notice Lender is attempting to remove quote tokens from a bucket that exists above active auction debt from top-of-book downward.
*/
error RemoveDepositLockedByAuctionDebt();
/**
* @notice User attempted to kick off a new auction less than `2` weeks since the last auction completed.
*/
error ReserveAuctionTooSoon();
/**
* @notice Take was called before `1` hour had passed from kick time.
*/
error TakeNotPastCooldown();
/**
* @notice Current block timestamp has reached or exceeded a user-provided expiration.
*/
error TransactionExpired();
/**
* @notice The address that transfer `LP` is not approved by the `LP` receiving address.
*/
error TransferorNotApproved();
/**
* @notice Owner of the `LP` attemps to transfer `LP` to same address.
*/
error TransferToSameOwner();
/**
* @notice The threshold price of the loan to be inserted in loans heap is zero.
*/
error ZeroThresholdPrice();
}
| interface IPoolErrors {
/**************************/
/*** Common Pool Errors ***/
/**************************/
/**
* @notice `LP` allowance is already set by the owner.
*/
error AllowanceAlreadySet();
/**
* @notice The action cannot be executed on an active auction.
*/
error AuctionActive();
/**
* @notice Attempted auction to clear doesn't meet conditions.
*/
error AuctionNotClearable();
/**
* @notice Head auction should be cleared prior of executing this action.
*/
error AuctionNotCleared();
/**
* @notice The auction price is greater than the arbed bucket price.
*/
error AuctionPriceGtBucketPrice();
/**
* @notice Pool already initialized.
*/
error AlreadyInitialized();
/**
* @notice Borrower is attempting to create or modify a loan such that their loan's quote token would be less than the pool's minimum debt amount.
*/
error AmountLTMinDebt();
/**
* @notice Recipient of borrowed quote tokens doesn't match the caller of the `drawDebt` function.
*/
error BorrowerNotSender();
/**
* @notice Borrower has a healthy over-collateralized position.
*/
error BorrowerOk();
/**
* @notice Borrower is attempting to borrow more quote token than they have collateral for.
*/
error BorrowerUnderCollateralized();
/**
* @notice Operation cannot be executed in the same block when bucket becomes insolvent.
*/
error BucketBankruptcyBlock();
/**
* @notice User attempted to merge collateral from a lower price bucket into a higher price bucket.
*/
error CannotMergeToHigherPrice();
/**
* @notice User attempted an operation which does not exceed the dust amount, or leaves behind less than the dust amount.
*/
error DustAmountNotExceeded();
/**
* @notice Callback invoked by `flashLoan` function did not return the expected hash (see `ERC-3156` spec).
*/
error FlashloanCallbackFailed();
/**
* @notice Balance of pool contract before flashloan is different than the balance after flashloan.
*/
error FlashloanIncorrectBalance();
/**
* @notice Pool cannot facilitate a flashloan for the specified token address.
*/
error FlashloanUnavailableForToken();
/**
* @notice User is attempting to move or pull more collateral than is available.
*/
error InsufficientCollateral();
/**
* @notice Lender is attempting to move or remove more collateral they have claim to in the bucket.
* @notice Lender is attempting to remove more collateral they have claim to in the bucket.
* @notice Lender must have enough `LP` to claim the desired amount of quote from the bucket.
*/
error InsufficientLP();
/**
* @notice Bucket must have more quote available in the bucket than the lender is attempting to claim.
*/
error InsufficientLiquidity();
/**
* @notice When increasing / decreasing `LP` allowances indexes and amounts arrays parameters should have same length.
*/
error InvalidAllowancesInput();
/**
* @notice When transferring `LP` between indices, the new index must be a valid index.
*/
error InvalidIndex();
/**
* @notice The amount used for performed action should be greater than `0`.
*/
error InvalidAmount();
/**
* @notice Borrower is attempting to borrow more quote token than is available before the supplied `limitIndex`.
*/
error LimitIndexExceeded();
/**
* @notice When moving quote token `HTP` must stay below `LUP`.
* @notice When removing quote token `HTP` must stay below `LUP`.
*/
error LUPBelowHTP();
/**
* @notice Liquidation must result in `LUP` below the borrowers threshold price.
*/
error LUPGreaterThanTP();
/**
* @notice From index and to index arguments to move are the same.
*/
error MoveToSameIndex();
/**
* @notice Owner of the `LP` must have approved the new owner prior to transfer.
*/
error NoAllowance();
/**
* @notice Actor is attempting to take or clear an inactive auction.
*/
error NoAuction();
/**
* @notice No pool reserves are claimable.
*/
error NoReserves();
/**
* @notice Actor is attempting to take or clear an inactive reserves auction.
*/
error NoReservesAuction();
/**
* @notice Lender must have non-zero `LP` when attemptign to remove quote token from the pool.
*/
error NoClaim();
/**
* @notice Borrower has no debt to liquidate.
* @notice Borrower is attempting to repay when they have no outstanding debt.
*/
error NoDebt();
/**
* @notice Borrower is attempting to borrow an amount of quote tokens that will push the pool into under-collateralization.
*/
error PoolUnderCollateralized();
/**
* @notice Actor is attempting to add or move quote tokens at a price below the `LUP`.
* @notice Actor is attempting to kick with bucket price below the `LUP`.
*/
error PriceBelowLUP();
/**
* @notice Lender is attempting to remove quote tokens from a bucket that exists above active auction debt from top-of-book downward.
*/
error RemoveDepositLockedByAuctionDebt();
/**
* @notice User attempted to kick off a new auction less than `2` weeks since the last auction completed.
*/
error ReserveAuctionTooSoon();
/**
* @notice Take was called before `1` hour had passed from kick time.
*/
error TakeNotPastCooldown();
/**
* @notice Current block timestamp has reached or exceeded a user-provided expiration.
*/
error TransactionExpired();
/**
* @notice The address that transfer `LP` is not approved by the `LP` receiving address.
*/
error TransferorNotApproved();
/**
* @notice Owner of the `LP` attemps to transfer `LP` to same address.
*/
error TransferToSameOwner();
/**
* @notice The threshold price of the loan to be inserted in loans heap is zero.
*/
error ZeroThresholdPrice();
}
| 39,848 |
224 | // Token symbol | string public constant symbol = "KODA";
| string public constant symbol = "KODA";
| 51,028 |
940 | // list of stakers for all contracts | mapping(address => address[]) public contractStakers;
| mapping(address => address[]) public contractStakers;
| 29,442 |
18 | // Reclaim tokens if accidentally sent / | function reclaimToken(IERC20 token) public onlyOwner {
require(address(token) != address(0));
uint256 balance = token.balanceOf(address(this));
token.transfer(msg.sender, balance);
}
| function reclaimToken(IERC20 token) public onlyOwner {
require(address(token) != address(0));
uint256 balance = token.balanceOf(address(this));
token.transfer(msg.sender, balance);
}
| 50,288 |
36 | // Set the array of NFTs to reward. _contractAddresses Addresse of NFT contract _modelIds Model id of the NFT. If the NFT doesn't have a model, the value is uint256.max _pricesInEth Price in ETH. This arrays is expected to be sorted in ascending order, and to contain no repeated elements. / | function setRewardNfts(
address[] memory _contractAddresses,
uint256[] memory _modelIds,
uint256[] memory _pricesInEth
| function setRewardNfts(
address[] memory _contractAddresses,
uint256[] memory _modelIds,
uint256[] memory _pricesInEth
| 61,032 |
65 | // It is a StandardToken ERC20 token and inherits all of that It has the Property structure and holds the Properties It governs the regulators (moderators, admins, root, Property DApps and PixelProperty) It has getters and setts for all data storage It selectively allows access to PXL and Properties based on caller access/ | contract PXLProperty is StandardToken {
/* ERC-20 MetaData */
string public constant name = "PixelPropertyToken";
string public constant symbol = "PXL";
uint256 public constant decimals = 0;
/* Access Level Constants */
uint8 constant LEVEL_1_MODERATOR = 1; // 1: Level 1 Moderator - nsfw-flagging power
uint8 constant LEVEL_2_MODERATOR = 2; // 2: Level 2 Moderator - ban power + [1]
uint8 constant LEVEL_1_ADMIN = 3; // 3: Level 1 Admin - Can manage moderator levels + [1,2]
uint8 constant LEVEL_2_ADMIN = 4; // 4: Level 2 Admin - Can manage admin level 1 levels + [1-3]
uint8 constant LEVEL_1_ROOT = 5; // 5: Level 1 Root - Can set property DApps level [1-4]
uint8 constant LEVEL_2_ROOT = 6; // 6: Level 2 Root - Can set pixelPropertyContract level [1-5]
uint8 constant LEVEL_3_ROOT = 7; // 7: Level 3 Root - Can demote/remove root, transfer root, [1-6]
uint8 constant LEVEL_PROPERTY_DAPPS = 8; // 8: Property DApps - Power over manipulating Property data
uint8 constant LEVEL_PIXEL_PROPERTY = 9; // 9: PixelProperty - Power over PXL generation & Property ownership
/* Flags Constants */
uint8 constant FLAG_NSFW = 1;
uint8 constant FLAG_BAN = 2;
/* Accesser Addresses & Levels */
address pixelPropertyContract; // Only contract that has control over PXL creation and Property ownership
mapping (address => uint8) public regulators; // Mapping of users/contracts to their control levels
// Mapping of PropertyID to Property
mapping (uint16 => Property) public properties;
// Property Owner's website
mapping (address => uint256[2]) public ownerWebsite;
// Property Owner's hover text
mapping (address => uint256[2]) public ownerHoverText;
// Whether migration is occuring or not
bool inMigrationPeriod;
// Old PXLProperty Contract from before update we migrate data from
PXLProperty oldPXLProperty;
/* ### Ownable Property Structure ### */
struct Property {
uint8 flag;
bool isInPrivateMode; //Whether in private mode for owner-only use or free-use mode to be shared
address owner; //Who owns the Property. If its zero (0), then no owner and known as a "system-Property"
address lastUpdater; //Who last changed the color of the Property
uint256[5] colors; //10x10 rgb pixel colors per property. colors[0] is the top row, colors[9] is the bottom row
uint256 salePrice; //PXL price the owner has the Property on sale for. If zero, then its not for sale.
uint256 lastUpdate; //Timestamp of when it had its color last updated
uint256 becomePublic; //Timestamp on when to become public
uint256 earnUntil; //Timestamp on when Property token generation will stop
}
/* ### Regulation Access Modifiers ### */
modifier regulatorAccess(uint8 accessLevel) {
require(accessLevel <= LEVEL_3_ROOT); // Only request moderator, admin or root levels forr regulatorAccess
require(regulators[msg.sender] >= accessLevel); // Users must meet requirement
if (accessLevel >= LEVEL_1_ADMIN) { //
require(regulators[msg.sender] <= LEVEL_3_ROOT); //DApps can't do Admin/Root stuff, but can set nsfw/ban flags
}
_;
}
modifier propertyDAppAccess() {
require(regulators[msg.sender] == LEVEL_PROPERTY_DAPPS || regulators[msg.sender] == LEVEL_PIXEL_PROPERTY );
_;
}
modifier pixelPropertyAccess() {
require(regulators[msg.sender] == LEVEL_PIXEL_PROPERTY);
_;
}
/* ### Constructor ### */
function PXLProperty(address oldAddress) public {
inMigrationPeriod = true;
oldPXLProperty = PXLProperty(oldAddress);
regulators[msg.sender] = LEVEL_3_ROOT; // Creator set to Level 3 Root
}
/* ### Moderator, Admin & Root Functions ### */
// Moderator Flags
function setPropertyFlag(uint16 propertyID, uint8 flag) public regulatorAccess(flag == FLAG_NSFW ? LEVEL_1_MODERATOR : LEVEL_2_MODERATOR) {
properties[propertyID].flag = flag;
if (flag == FLAG_BAN) {
require(properties[propertyID].isInPrivateMode); //Can't ban an owner's property if a public user caused the NSFW content
properties[propertyID].colors = [0, 0, 0, 0, 0];
}
}
// Setting moderator/admin/root access
function setRegulatorAccessLevel(address user, uint8 accessLevel) public regulatorAccess(LEVEL_1_ADMIN) {
if (msg.sender != user) {
require(regulators[msg.sender] > regulators[user]); // You have to be a higher rank than the user you are changing
}
require(regulators[msg.sender] > accessLevel); // You have to be a higher rank than the role you are setting
regulators[user] = accessLevel;
}
function setPixelPropertyContract(address newPixelPropertyContract) public regulatorAccess(LEVEL_2_ROOT) {
require(newPixelPropertyContract != 0);
if (pixelPropertyContract != 0) {
regulators[pixelPropertyContract] = 0; //If we already have a pixelPropertyContract, revoke its ownership
}
pixelPropertyContract = newPixelPropertyContract;
regulators[newPixelPropertyContract] = LEVEL_PIXEL_PROPERTY;
}
function setPropertyDAppContract(address propertyDAppContract, bool giveAccess) public regulatorAccess(LEVEL_1_ROOT) {
require(propertyDAppContract != 0);
regulators[propertyDAppContract] = giveAccess ? LEVEL_PROPERTY_DAPPS : 0;
}
/* ### Migration Functions Post Update ### */
//Migrates the owners of Properties
function migratePropertyOwnership(uint16[10] propertiesToCopy) public regulatorAccess(LEVEL_3_ROOT) {
require(inMigrationPeriod);
for(uint16 i = 0; i < 10; i++) {
if (propertiesToCopy[i] < 10000) {
if (properties[propertiesToCopy[i]].owner == 0) { //Only migrate if there is no current owner
properties[propertiesToCopy[i]].owner = oldPXLProperty.getPropertyOwner(propertiesToCopy[i]);
}
}
}
}
//Migrates the PXL balances of users
function migrateUsers(address[10] usersToMigrate) public regulatorAccess(LEVEL_3_ROOT) {
require(inMigrationPeriod);
for(uint16 i = 0; i < 10; i++) {
if(balances[usersToMigrate[i]] == 0) { //Only migrate if they have no funds to avoid duplicate migrations
uint256 oldBalance = oldPXLProperty.balanceOf(usersToMigrate[i]);
if (oldBalance > 0) {
balances[usersToMigrate[i]] = oldBalance;
totalSupply += oldBalance;
Transfer(0, usersToMigrate[i], oldBalance);
}
}
}
}
//Perminantly ends migration so it cannot be abused after it is deemed complete
function endMigrationPeriod() public regulatorAccess(LEVEL_3_ROOT) {
inMigrationPeriod = false;
}
/* ### PropertyDapp Functions ### */
function setPropertyColors(uint16 propertyID, uint256[5] colors) public propertyDAppAccess() {
for(uint256 i = 0; i < 5; i++) {
if (properties[propertyID].colors[i] != colors[i]) {
properties[propertyID].colors[i] = colors[i];
}
}
}
function setPropertyRowColor(uint16 propertyID, uint8 row, uint256 rowColor) public propertyDAppAccess() {
if (properties[propertyID].colors[row] != rowColor) {
properties[propertyID].colors[row] = rowColor;
}
}
function setOwnerHoverText(address textOwner, uint256[2] hoverText) public propertyDAppAccess() {
require (textOwner != 0);
ownerHoverText[textOwner] = hoverText;
}
function setOwnerLink(address websiteOwner, uint256[2] website) public propertyDAppAccess() {
require (websiteOwner != 0);
ownerWebsite[websiteOwner] = website;
}
/* ### PixelProperty Property Functions ### */
function setPropertyPrivateMode(uint16 propertyID, bool isInPrivateMode) public pixelPropertyAccess() {
if (properties[propertyID].isInPrivateMode != isInPrivateMode) {
properties[propertyID].isInPrivateMode = isInPrivateMode;
}
}
function setPropertyOwner(uint16 propertyID, address propertyOwner) public pixelPropertyAccess() {
if (properties[propertyID].owner != propertyOwner) {
properties[propertyID].owner = propertyOwner;
}
}
function setPropertyLastUpdater(uint16 propertyID, address lastUpdater) public pixelPropertyAccess() {
if (properties[propertyID].lastUpdater != lastUpdater) {
properties[propertyID].lastUpdater = lastUpdater;
}
}
function setPropertySalePrice(uint16 propertyID, uint256 salePrice) public pixelPropertyAccess() {
if (properties[propertyID].salePrice != salePrice) {
properties[propertyID].salePrice = salePrice;
}
}
function setPropertyLastUpdate(uint16 propertyID, uint256 lastUpdate) public pixelPropertyAccess() {
properties[propertyID].lastUpdate = lastUpdate;
}
function setPropertyBecomePublic(uint16 propertyID, uint256 becomePublic) public pixelPropertyAccess() {
properties[propertyID].becomePublic = becomePublic;
}
function setPropertyEarnUntil(uint16 propertyID, uint256 earnUntil) public pixelPropertyAccess() {
properties[propertyID].earnUntil = earnUntil;
}
function setPropertyPrivateModeEarnUntilLastUpdateBecomePublic(uint16 propertyID, bool privateMode, uint256 earnUntil, uint256 lastUpdate, uint256 becomePublic) public pixelPropertyAccess() {
if (properties[propertyID].isInPrivateMode != privateMode) {
properties[propertyID].isInPrivateMode = privateMode;
}
properties[propertyID].earnUntil = earnUntil;
properties[propertyID].lastUpdate = lastUpdate;
properties[propertyID].becomePublic = becomePublic;
}
function setPropertyLastUpdaterLastUpdate(uint16 propertyID, address lastUpdater, uint256 lastUpdate) public pixelPropertyAccess() {
if (properties[propertyID].lastUpdater != lastUpdater) {
properties[propertyID].lastUpdater = lastUpdater;
}
properties[propertyID].lastUpdate = lastUpdate;
}
function setPropertyBecomePublicEarnUntil(uint16 propertyID, uint256 becomePublic, uint256 earnUntil) public pixelPropertyAccess() {
properties[propertyID].becomePublic = becomePublic;
properties[propertyID].earnUntil = earnUntil;
}
function setPropertyOwnerSalePricePrivateModeFlag(uint16 propertyID, address owner, uint256 salePrice, bool privateMode, uint8 flag) public pixelPropertyAccess() {
if (properties[propertyID].owner != owner) {
properties[propertyID].owner = owner;
}
if (properties[propertyID].salePrice != salePrice) {
properties[propertyID].salePrice = salePrice;
}
if (properties[propertyID].isInPrivateMode != privateMode) {
properties[propertyID].isInPrivateMode = privateMode;
}
if (properties[propertyID].flag != flag) {
properties[propertyID].flag = flag;
}
}
function setPropertyOwnerSalePrice(uint16 propertyID, address owner, uint256 salePrice) public pixelPropertyAccess() {
if (properties[propertyID].owner != owner) {
properties[propertyID].owner = owner;
}
if (properties[propertyID].salePrice != salePrice) {
properties[propertyID].salePrice = salePrice;
}
}
/* ### PixelProperty PXL Functions ### */
function rewardPXL(address rewardedUser, uint256 amount) public pixelPropertyAccess() {
require(rewardedUser != 0);
balances[rewardedUser] += amount;
totalSupply += amount;
Transfer(0, rewardedUser, amount);
}
function burnPXL(address burningUser, uint256 amount) public pixelPropertyAccess() {
require(burningUser != 0);
require(balances[burningUser] >= amount);
balances[burningUser] -= amount;
totalSupply -= amount;
Transfer(burningUser, 0, amount);
}
function burnPXLRewardPXL(address burner, uint256 toBurn, address rewarder, uint256 toReward) public pixelPropertyAccess() {
require(balances[burner] >= toBurn);
if (toBurn > 0) {
balances[burner] -= toBurn;
totalSupply -= toBurn;
Transfer(burner, 0, toBurn);
}
if (rewarder != 0) {
balances[rewarder] += toReward;
totalSupply += toReward;
Transfer(0, rewarder, toReward);
}
}
function burnPXLRewardPXLx2(address burner, uint256 toBurn, address rewarder1, uint256 toReward1, address rewarder2, uint256 toReward2) public pixelPropertyAccess() {
require(balances[burner] >= toBurn);
if (toBurn > 0) {
balances[burner] -= toBurn;
totalSupply -= toBurn;
Transfer(burner, 0, toBurn);
}
if (rewarder1 != 0) {
balances[rewarder1] += toReward1;
totalSupply += toReward1;
Transfer(0, rewarder1, toReward1);
}
if (rewarder2 != 0) {
balances[rewarder2] += toReward2;
totalSupply += toReward2;
Transfer(0, rewarder2, toReward2);
}
}
/* ### All Getters/Views ### */
function getOwnerHoverText(address user) public view returns(uint256[2]) {
return ownerHoverText[user];
}
function getOwnerLink(address user) public view returns(uint256[2]) {
return ownerWebsite[user];
}
function getPropertyFlag(uint16 propertyID) public view returns(uint8) {
return properties[propertyID].flag;
}
function getPropertyPrivateMode(uint16 propertyID) public view returns(bool) {
return properties[propertyID].isInPrivateMode;
}
function getPropertyOwner(uint16 propertyID) public view returns(address) {
return properties[propertyID].owner;
}
function getPropertyLastUpdater(uint16 propertyID) public view returns(address) {
return properties[propertyID].lastUpdater;
}
function getPropertyColors(uint16 propertyID) public view returns(uint256[5]) {
if (properties[propertyID].colors[0] != 0 || properties[propertyID].colors[1] != 0 || properties[propertyID].colors[2] != 0 || properties[propertyID].colors[3] != 0 || properties[propertyID].colors[4] != 0) {
return properties[propertyID].colors;
} else {
return oldPXLProperty.getPropertyColors(propertyID);
}
}
function getPropertyColorsOfRow(uint16 propertyID, uint8 rowIndex) public view returns(uint256) {
require(rowIndex <= 9);
return getPropertyColors(propertyID)[rowIndex];
}
function getPropertySalePrice(uint16 propertyID) public view returns(uint256) {
return properties[propertyID].salePrice;
}
function getPropertyLastUpdate(uint16 propertyID) public view returns(uint256) {
return properties[propertyID].lastUpdate;
}
function getPropertyBecomePublic(uint16 propertyID) public view returns(uint256) {
return properties[propertyID].becomePublic;
}
function getPropertyEarnUntil(uint16 propertyID) public view returns(uint256) {
return properties[propertyID].earnUntil;
}
function getRegulatorLevel(address user) public view returns(uint8) {
return regulators[user];
}
// Gets the (owners address, Ethereum sale price, PXL sale price, last update timestamp, whether its in private mode or not, when it becomes public timestamp, flag) for a Property
function getPropertyData(uint16 propertyID, uint256 systemSalePriceETH, uint256 systemSalePricePXL) public view returns(address, uint256, uint256, uint256, bool, uint256, uint8) {
Property memory property = properties[propertyID];
bool isInPrivateMode = property.isInPrivateMode;
//If it's in private, but it has expired and should be public, set our bool to be public
if (isInPrivateMode && property.becomePublic <= now) {
isInPrivateMode = false;
}
if (properties[propertyID].owner == 0) {
return (0, systemSalePriceETH, systemSalePricePXL, property.lastUpdate, isInPrivateMode, property.becomePublic, property.flag);
} else {
return (property.owner, 0, property.salePrice, property.lastUpdate, isInPrivateMode, property.becomePublic, property.flag);
}
}
function getPropertyPrivateModeBecomePublic(uint16 propertyID) public view returns (bool, uint256) {
return (properties[propertyID].isInPrivateMode, properties[propertyID].becomePublic);
}
function getPropertyLastUpdaterBecomePublic(uint16 propertyID) public view returns (address, uint256) {
return (properties[propertyID].lastUpdater, properties[propertyID].becomePublic);
}
function getPropertyOwnerSalePrice(uint16 propertyID) public view returns (address, uint256) {
return (properties[propertyID].owner, properties[propertyID].salePrice);
}
function getPropertyPrivateModeLastUpdateEarnUntil(uint16 propertyID) public view returns (bool, uint256, uint256) {
return (properties[propertyID].isInPrivateMode, properties[propertyID].lastUpdate, properties[propertyID].earnUntil);
}
} | contract PXLProperty is StandardToken {
/* ERC-20 MetaData */
string public constant name = "PixelPropertyToken";
string public constant symbol = "PXL";
uint256 public constant decimals = 0;
/* Access Level Constants */
uint8 constant LEVEL_1_MODERATOR = 1; // 1: Level 1 Moderator - nsfw-flagging power
uint8 constant LEVEL_2_MODERATOR = 2; // 2: Level 2 Moderator - ban power + [1]
uint8 constant LEVEL_1_ADMIN = 3; // 3: Level 1 Admin - Can manage moderator levels + [1,2]
uint8 constant LEVEL_2_ADMIN = 4; // 4: Level 2 Admin - Can manage admin level 1 levels + [1-3]
uint8 constant LEVEL_1_ROOT = 5; // 5: Level 1 Root - Can set property DApps level [1-4]
uint8 constant LEVEL_2_ROOT = 6; // 6: Level 2 Root - Can set pixelPropertyContract level [1-5]
uint8 constant LEVEL_3_ROOT = 7; // 7: Level 3 Root - Can demote/remove root, transfer root, [1-6]
uint8 constant LEVEL_PROPERTY_DAPPS = 8; // 8: Property DApps - Power over manipulating Property data
uint8 constant LEVEL_PIXEL_PROPERTY = 9; // 9: PixelProperty - Power over PXL generation & Property ownership
/* Flags Constants */
uint8 constant FLAG_NSFW = 1;
uint8 constant FLAG_BAN = 2;
/* Accesser Addresses & Levels */
address pixelPropertyContract; // Only contract that has control over PXL creation and Property ownership
mapping (address => uint8) public regulators; // Mapping of users/contracts to their control levels
// Mapping of PropertyID to Property
mapping (uint16 => Property) public properties;
// Property Owner's website
mapping (address => uint256[2]) public ownerWebsite;
// Property Owner's hover text
mapping (address => uint256[2]) public ownerHoverText;
// Whether migration is occuring or not
bool inMigrationPeriod;
// Old PXLProperty Contract from before update we migrate data from
PXLProperty oldPXLProperty;
/* ### Ownable Property Structure ### */
struct Property {
uint8 flag;
bool isInPrivateMode; //Whether in private mode for owner-only use or free-use mode to be shared
address owner; //Who owns the Property. If its zero (0), then no owner and known as a "system-Property"
address lastUpdater; //Who last changed the color of the Property
uint256[5] colors; //10x10 rgb pixel colors per property. colors[0] is the top row, colors[9] is the bottom row
uint256 salePrice; //PXL price the owner has the Property on sale for. If zero, then its not for sale.
uint256 lastUpdate; //Timestamp of when it had its color last updated
uint256 becomePublic; //Timestamp on when to become public
uint256 earnUntil; //Timestamp on when Property token generation will stop
}
/* ### Regulation Access Modifiers ### */
modifier regulatorAccess(uint8 accessLevel) {
require(accessLevel <= LEVEL_3_ROOT); // Only request moderator, admin or root levels forr regulatorAccess
require(regulators[msg.sender] >= accessLevel); // Users must meet requirement
if (accessLevel >= LEVEL_1_ADMIN) { //
require(regulators[msg.sender] <= LEVEL_3_ROOT); //DApps can't do Admin/Root stuff, but can set nsfw/ban flags
}
_;
}
modifier propertyDAppAccess() {
require(regulators[msg.sender] == LEVEL_PROPERTY_DAPPS || regulators[msg.sender] == LEVEL_PIXEL_PROPERTY );
_;
}
modifier pixelPropertyAccess() {
require(regulators[msg.sender] == LEVEL_PIXEL_PROPERTY);
_;
}
/* ### Constructor ### */
function PXLProperty(address oldAddress) public {
inMigrationPeriod = true;
oldPXLProperty = PXLProperty(oldAddress);
regulators[msg.sender] = LEVEL_3_ROOT; // Creator set to Level 3 Root
}
/* ### Moderator, Admin & Root Functions ### */
// Moderator Flags
function setPropertyFlag(uint16 propertyID, uint8 flag) public regulatorAccess(flag == FLAG_NSFW ? LEVEL_1_MODERATOR : LEVEL_2_MODERATOR) {
properties[propertyID].flag = flag;
if (flag == FLAG_BAN) {
require(properties[propertyID].isInPrivateMode); //Can't ban an owner's property if a public user caused the NSFW content
properties[propertyID].colors = [0, 0, 0, 0, 0];
}
}
// Setting moderator/admin/root access
function setRegulatorAccessLevel(address user, uint8 accessLevel) public regulatorAccess(LEVEL_1_ADMIN) {
if (msg.sender != user) {
require(regulators[msg.sender] > regulators[user]); // You have to be a higher rank than the user you are changing
}
require(regulators[msg.sender] > accessLevel); // You have to be a higher rank than the role you are setting
regulators[user] = accessLevel;
}
function setPixelPropertyContract(address newPixelPropertyContract) public regulatorAccess(LEVEL_2_ROOT) {
require(newPixelPropertyContract != 0);
if (pixelPropertyContract != 0) {
regulators[pixelPropertyContract] = 0; //If we already have a pixelPropertyContract, revoke its ownership
}
pixelPropertyContract = newPixelPropertyContract;
regulators[newPixelPropertyContract] = LEVEL_PIXEL_PROPERTY;
}
function setPropertyDAppContract(address propertyDAppContract, bool giveAccess) public regulatorAccess(LEVEL_1_ROOT) {
require(propertyDAppContract != 0);
regulators[propertyDAppContract] = giveAccess ? LEVEL_PROPERTY_DAPPS : 0;
}
/* ### Migration Functions Post Update ### */
//Migrates the owners of Properties
function migratePropertyOwnership(uint16[10] propertiesToCopy) public regulatorAccess(LEVEL_3_ROOT) {
require(inMigrationPeriod);
for(uint16 i = 0; i < 10; i++) {
if (propertiesToCopy[i] < 10000) {
if (properties[propertiesToCopy[i]].owner == 0) { //Only migrate if there is no current owner
properties[propertiesToCopy[i]].owner = oldPXLProperty.getPropertyOwner(propertiesToCopy[i]);
}
}
}
}
//Migrates the PXL balances of users
function migrateUsers(address[10] usersToMigrate) public regulatorAccess(LEVEL_3_ROOT) {
require(inMigrationPeriod);
for(uint16 i = 0; i < 10; i++) {
if(balances[usersToMigrate[i]] == 0) { //Only migrate if they have no funds to avoid duplicate migrations
uint256 oldBalance = oldPXLProperty.balanceOf(usersToMigrate[i]);
if (oldBalance > 0) {
balances[usersToMigrate[i]] = oldBalance;
totalSupply += oldBalance;
Transfer(0, usersToMigrate[i], oldBalance);
}
}
}
}
//Perminantly ends migration so it cannot be abused after it is deemed complete
function endMigrationPeriod() public regulatorAccess(LEVEL_3_ROOT) {
inMigrationPeriod = false;
}
/* ### PropertyDapp Functions ### */
function setPropertyColors(uint16 propertyID, uint256[5] colors) public propertyDAppAccess() {
for(uint256 i = 0; i < 5; i++) {
if (properties[propertyID].colors[i] != colors[i]) {
properties[propertyID].colors[i] = colors[i];
}
}
}
function setPropertyRowColor(uint16 propertyID, uint8 row, uint256 rowColor) public propertyDAppAccess() {
if (properties[propertyID].colors[row] != rowColor) {
properties[propertyID].colors[row] = rowColor;
}
}
function setOwnerHoverText(address textOwner, uint256[2] hoverText) public propertyDAppAccess() {
require (textOwner != 0);
ownerHoverText[textOwner] = hoverText;
}
function setOwnerLink(address websiteOwner, uint256[2] website) public propertyDAppAccess() {
require (websiteOwner != 0);
ownerWebsite[websiteOwner] = website;
}
/* ### PixelProperty Property Functions ### */
function setPropertyPrivateMode(uint16 propertyID, bool isInPrivateMode) public pixelPropertyAccess() {
if (properties[propertyID].isInPrivateMode != isInPrivateMode) {
properties[propertyID].isInPrivateMode = isInPrivateMode;
}
}
function setPropertyOwner(uint16 propertyID, address propertyOwner) public pixelPropertyAccess() {
if (properties[propertyID].owner != propertyOwner) {
properties[propertyID].owner = propertyOwner;
}
}
function setPropertyLastUpdater(uint16 propertyID, address lastUpdater) public pixelPropertyAccess() {
if (properties[propertyID].lastUpdater != lastUpdater) {
properties[propertyID].lastUpdater = lastUpdater;
}
}
function setPropertySalePrice(uint16 propertyID, uint256 salePrice) public pixelPropertyAccess() {
if (properties[propertyID].salePrice != salePrice) {
properties[propertyID].salePrice = salePrice;
}
}
function setPropertyLastUpdate(uint16 propertyID, uint256 lastUpdate) public pixelPropertyAccess() {
properties[propertyID].lastUpdate = lastUpdate;
}
function setPropertyBecomePublic(uint16 propertyID, uint256 becomePublic) public pixelPropertyAccess() {
properties[propertyID].becomePublic = becomePublic;
}
function setPropertyEarnUntil(uint16 propertyID, uint256 earnUntil) public pixelPropertyAccess() {
properties[propertyID].earnUntil = earnUntil;
}
function setPropertyPrivateModeEarnUntilLastUpdateBecomePublic(uint16 propertyID, bool privateMode, uint256 earnUntil, uint256 lastUpdate, uint256 becomePublic) public pixelPropertyAccess() {
if (properties[propertyID].isInPrivateMode != privateMode) {
properties[propertyID].isInPrivateMode = privateMode;
}
properties[propertyID].earnUntil = earnUntil;
properties[propertyID].lastUpdate = lastUpdate;
properties[propertyID].becomePublic = becomePublic;
}
function setPropertyLastUpdaterLastUpdate(uint16 propertyID, address lastUpdater, uint256 lastUpdate) public pixelPropertyAccess() {
if (properties[propertyID].lastUpdater != lastUpdater) {
properties[propertyID].lastUpdater = lastUpdater;
}
properties[propertyID].lastUpdate = lastUpdate;
}
function setPropertyBecomePublicEarnUntil(uint16 propertyID, uint256 becomePublic, uint256 earnUntil) public pixelPropertyAccess() {
properties[propertyID].becomePublic = becomePublic;
properties[propertyID].earnUntil = earnUntil;
}
function setPropertyOwnerSalePricePrivateModeFlag(uint16 propertyID, address owner, uint256 salePrice, bool privateMode, uint8 flag) public pixelPropertyAccess() {
if (properties[propertyID].owner != owner) {
properties[propertyID].owner = owner;
}
if (properties[propertyID].salePrice != salePrice) {
properties[propertyID].salePrice = salePrice;
}
if (properties[propertyID].isInPrivateMode != privateMode) {
properties[propertyID].isInPrivateMode = privateMode;
}
if (properties[propertyID].flag != flag) {
properties[propertyID].flag = flag;
}
}
function setPropertyOwnerSalePrice(uint16 propertyID, address owner, uint256 salePrice) public pixelPropertyAccess() {
if (properties[propertyID].owner != owner) {
properties[propertyID].owner = owner;
}
if (properties[propertyID].salePrice != salePrice) {
properties[propertyID].salePrice = salePrice;
}
}
/* ### PixelProperty PXL Functions ### */
function rewardPXL(address rewardedUser, uint256 amount) public pixelPropertyAccess() {
require(rewardedUser != 0);
balances[rewardedUser] += amount;
totalSupply += amount;
Transfer(0, rewardedUser, amount);
}
function burnPXL(address burningUser, uint256 amount) public pixelPropertyAccess() {
require(burningUser != 0);
require(balances[burningUser] >= amount);
balances[burningUser] -= amount;
totalSupply -= amount;
Transfer(burningUser, 0, amount);
}
function burnPXLRewardPXL(address burner, uint256 toBurn, address rewarder, uint256 toReward) public pixelPropertyAccess() {
require(balances[burner] >= toBurn);
if (toBurn > 0) {
balances[burner] -= toBurn;
totalSupply -= toBurn;
Transfer(burner, 0, toBurn);
}
if (rewarder != 0) {
balances[rewarder] += toReward;
totalSupply += toReward;
Transfer(0, rewarder, toReward);
}
}
function burnPXLRewardPXLx2(address burner, uint256 toBurn, address rewarder1, uint256 toReward1, address rewarder2, uint256 toReward2) public pixelPropertyAccess() {
require(balances[burner] >= toBurn);
if (toBurn > 0) {
balances[burner] -= toBurn;
totalSupply -= toBurn;
Transfer(burner, 0, toBurn);
}
if (rewarder1 != 0) {
balances[rewarder1] += toReward1;
totalSupply += toReward1;
Transfer(0, rewarder1, toReward1);
}
if (rewarder2 != 0) {
balances[rewarder2] += toReward2;
totalSupply += toReward2;
Transfer(0, rewarder2, toReward2);
}
}
/* ### All Getters/Views ### */
function getOwnerHoverText(address user) public view returns(uint256[2]) {
return ownerHoverText[user];
}
function getOwnerLink(address user) public view returns(uint256[2]) {
return ownerWebsite[user];
}
function getPropertyFlag(uint16 propertyID) public view returns(uint8) {
return properties[propertyID].flag;
}
function getPropertyPrivateMode(uint16 propertyID) public view returns(bool) {
return properties[propertyID].isInPrivateMode;
}
function getPropertyOwner(uint16 propertyID) public view returns(address) {
return properties[propertyID].owner;
}
function getPropertyLastUpdater(uint16 propertyID) public view returns(address) {
return properties[propertyID].lastUpdater;
}
function getPropertyColors(uint16 propertyID) public view returns(uint256[5]) {
if (properties[propertyID].colors[0] != 0 || properties[propertyID].colors[1] != 0 || properties[propertyID].colors[2] != 0 || properties[propertyID].colors[3] != 0 || properties[propertyID].colors[4] != 0) {
return properties[propertyID].colors;
} else {
return oldPXLProperty.getPropertyColors(propertyID);
}
}
function getPropertyColorsOfRow(uint16 propertyID, uint8 rowIndex) public view returns(uint256) {
require(rowIndex <= 9);
return getPropertyColors(propertyID)[rowIndex];
}
function getPropertySalePrice(uint16 propertyID) public view returns(uint256) {
return properties[propertyID].salePrice;
}
function getPropertyLastUpdate(uint16 propertyID) public view returns(uint256) {
return properties[propertyID].lastUpdate;
}
function getPropertyBecomePublic(uint16 propertyID) public view returns(uint256) {
return properties[propertyID].becomePublic;
}
function getPropertyEarnUntil(uint16 propertyID) public view returns(uint256) {
return properties[propertyID].earnUntil;
}
function getRegulatorLevel(address user) public view returns(uint8) {
return regulators[user];
}
// Gets the (owners address, Ethereum sale price, PXL sale price, last update timestamp, whether its in private mode or not, when it becomes public timestamp, flag) for a Property
function getPropertyData(uint16 propertyID, uint256 systemSalePriceETH, uint256 systemSalePricePXL) public view returns(address, uint256, uint256, uint256, bool, uint256, uint8) {
Property memory property = properties[propertyID];
bool isInPrivateMode = property.isInPrivateMode;
//If it's in private, but it has expired and should be public, set our bool to be public
if (isInPrivateMode && property.becomePublic <= now) {
isInPrivateMode = false;
}
if (properties[propertyID].owner == 0) {
return (0, systemSalePriceETH, systemSalePricePXL, property.lastUpdate, isInPrivateMode, property.becomePublic, property.flag);
} else {
return (property.owner, 0, property.salePrice, property.lastUpdate, isInPrivateMode, property.becomePublic, property.flag);
}
}
function getPropertyPrivateModeBecomePublic(uint16 propertyID) public view returns (bool, uint256) {
return (properties[propertyID].isInPrivateMode, properties[propertyID].becomePublic);
}
function getPropertyLastUpdaterBecomePublic(uint16 propertyID) public view returns (address, uint256) {
return (properties[propertyID].lastUpdater, properties[propertyID].becomePublic);
}
function getPropertyOwnerSalePrice(uint16 propertyID) public view returns (address, uint256) {
return (properties[propertyID].owner, properties[propertyID].salePrice);
}
function getPropertyPrivateModeLastUpdateEarnUntil(uint16 propertyID) public view returns (bool, uint256, uint256) {
return (properties[propertyID].isInPrivateMode, properties[propertyID].lastUpdate, properties[propertyID].earnUntil);
}
} | 26,708 |
137 | // EIP712 Domain Separator // EIP2612 Permit nonces // EIP3009 Authorization States / | {
SeizableBridgeERC20.initialize(owner, processor);
processor.register(name, symbol, decimals);
_trustedIntermediaries = trustedIntermediaries;
emit TrustedIntermediariesChanged(trustedIntermediaries);
_upgradeToV2();
}
| {
SeizableBridgeERC20.initialize(owner, processor);
processor.register(name, symbol, decimals);
_trustedIntermediaries = trustedIntermediaries;
emit TrustedIntermediariesChanged(trustedIntermediaries);
_upgradeToV2();
}
| 78,851 |
9 | // Pausable Base contract which allows children to implement an emergency stop mechanism. / | contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
| contract 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();
}
}
| 14,361 |
7 | // Copy revert reason from call | assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
| assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
| 12,186 |
53 | // ========== Internal Functions ========== / | function _convert(address token0, address token1) internal {
// Interactions
// S1 - S4: OK
IRipPair pair = IRipPair(factory.getPair(token0, token1));
require(address(pair) != address(0), "RipMakerV2: Invalid pair");
// balanceOf: S1 - S4: OK
// transfer: X1 - X5: OK
IERC20(address(pair)).safeTransfer(address(pair), pair.balanceOf(address(this)));
// X1 - X5: OK
// We don't take amount0 and amount1 from here, as it won't take into account reflect tokens.
pair.burn(address(this));
// We get the amount0 and amount1 by their respective balance of RipMakerV2.
uint256 amount0 = IERC20(token0).balanceOf(address(this));
uint256 amount1 = IERC20(token1).balanceOf(address(this));
// we invert token0 and token1 as well as we'll need them to get their respective balance.
if (token0 != pair.token0()) {
(amount0, amount1) = (amount1, amount0);
(token0, token1) = (token1, token0);
}
emit LogConvert(msg.sender, token0, token1, amount0, amount1, _convertStep(token0, token1, amount0, amount1));
}
| function _convert(address token0, address token1) internal {
// Interactions
// S1 - S4: OK
IRipPair pair = IRipPair(factory.getPair(token0, token1));
require(address(pair) != address(0), "RipMakerV2: Invalid pair");
// balanceOf: S1 - S4: OK
// transfer: X1 - X5: OK
IERC20(address(pair)).safeTransfer(address(pair), pair.balanceOf(address(this)));
// X1 - X5: OK
// We don't take amount0 and amount1 from here, as it won't take into account reflect tokens.
pair.burn(address(this));
// We get the amount0 and amount1 by their respective balance of RipMakerV2.
uint256 amount0 = IERC20(token0).balanceOf(address(this));
uint256 amount1 = IERC20(token1).balanceOf(address(this));
// we invert token0 and token1 as well as we'll need them to get their respective balance.
if (token0 != pair.token0()) {
(amount0, amount1) = (amount1, amount0);
(token0, token1) = (token1, token0);
}
emit LogConvert(msg.sender, token0, token1, amount0, amount1, _convertStep(token0, token1, amount0, amount1));
}
| 26,975 |
3 | // this modifier will stop the function if emergency breaker is switched on | modifier stop_if_emergency() {
if(!stopped) _;
}
| modifier stop_if_emergency() {
if(!stopped) _;
}
| 35,018 |
110 | // PAID Token Control / | function controlPAIDTokens() public view returns (bool) {
address sender = _msgSender();
uint256 tier = whitelist[sender].tier;
return _paidToken.balanceOf(sender) >= tiers[tier].paidAmount;
}
| function controlPAIDTokens() public view returns (bool) {
address sender = _msgSender();
uint256 tier = whitelist[sender].tier;
return _paidToken.balanceOf(sender) >= tiers[tier].paidAmount;
}
| 61,292 |
150 | // lib/openzeppelin-contracts/src/token/ERC721/ERC721Metadata.sol/ pragma solidity ^0.5.0; // import "../../GSN/Context.sol"; // import "./ERC721.sol"; // import "./IERC721Metadata.sol"; // import "../../introspection/ERC165.sol"; / | contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
| contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
| 32,589 |
115 | // Mapping from tokenId to index of the tokens list | mapping (uint256 => uint256) public tokenIdsIndex;
| mapping (uint256 => uint256) public tokenIdsIndex;
| 41,422 |
79 | // Calculates the new borrower and total borrow balances:newAccountBorrows = accountBorrows + borrowAmountnewTotalBorrows = totalBorrows + borrowAmount | BorrowSnapshot storage borrowSnapshot = accountBorrows[_borrower];
borrowSnapshot.principal = _borrowBalanceInternal(_borrower).add(
_borrowAmount
);
borrowSnapshot.interestIndex = borrowIndex;
totalBorrows = totalBorrows.add(_borrowAmount);
| BorrowSnapshot storage borrowSnapshot = accountBorrows[_borrower];
borrowSnapshot.principal = _borrowBalanceInternal(_borrower).add(
_borrowAmount
);
borrowSnapshot.interestIndex = borrowIndex;
totalBorrows = totalBorrows.add(_borrowAmount);
| 34,490 |
65 | // STC: Sense check | monetaryPolicy = IMonetaryPolicy(data);
| monetaryPolicy = IMonetaryPolicy(data);
| 3,461 |
110 | // e.g. 100e695e16 / 1e6 = 100e18 | uint256 minOutCrv = bAssetBal.mul(95e16).div(10 ** bAssetDec);
purchased = curve.exchange_underlying(_curvePosition, 0, bAssetBal, minOutCrv);
| uint256 minOutCrv = bAssetBal.mul(95e16).div(10 ** bAssetDec);
purchased = curve.exchange_underlying(_curvePosition, 0, bAssetBal, minOutCrv);
| 3,245 |
8 | // Tokens bought by user | mapping(address => uint256) public tokensBoughtOf;
mapping(address => bool) public KYCpassed;
event AcceptedUSD(address indexed user, uint256 amount);
event AcceptedWBTC(address indexed user, uint256 amount);
event AcceptedETH(address indexed user, uint256 amount);
string constant ERR_TRANSFER = "Token transfer failed";
string constant ERR_SALE_LIMIT = "Token sale limit reached";
| mapping(address => uint256) public tokensBoughtOf;
mapping(address => bool) public KYCpassed;
event AcceptedUSD(address indexed user, uint256 amount);
event AcceptedWBTC(address indexed user, uint256 amount);
event AcceptedETH(address indexed user, uint256 amount);
string constant ERR_TRANSFER = "Token transfer failed";
string constant ERR_SALE_LIMIT = "Token sale limit reached";
| 58,133 |
5 | // https:rstormsf.github.io/slides-merkleairdrop14 | function verify(bytes32[] memory proof, address who) public pure returns (bool) {
bytes32 computedHash = keccak256(abi.encodePacked(who));
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash < proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash == rootHash;
}
| function verify(bytes32[] memory proof, address who) public pure returns (bool) {
bytes32 computedHash = keccak256(abi.encodePacked(who));
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash < proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash == rootHash;
}
| 21,421 |
163 | // clean up storage to save gas | userLocks[lock.owner].remove(lockId);
delete tokenLocks[lockId];
| userLocks[lock.owner].remove(lockId);
delete tokenLocks[lockId];
| 29,110 |
18 | // Function to access total supply of tokens . | function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
| function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
| 560 |
58 | // build event data | _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
| _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
| 6,899 |
372 | // This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. / | function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
| function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
| 11,016 |
13 | // A participant cannot send less than the minimum amount | if (msg.value < MIN_AMOUNT) throw;
| if (msg.value < MIN_AMOUNT) throw;
| 34,440 |
108 | // Note: we can't use "currentEthInvested" for this calculation, we must use:currentEthInvested + ethTowardsICOPriceTokens This is because a split-buy essentially needs to simulate two separate buys - including the currentEthInvested update that comes BEFORE variable price tokens are bought! |
uint simulatedEthBeforeInvested = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3) + ethTowardsICOPriceTokens;
uint simulatedEthAfterInvested = simulatedEthBeforeInvested + ethTowardsVariablePriceTokens;
|
uint simulatedEthBeforeInvested = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3) + ethTowardsICOPriceTokens;
uint simulatedEthAfterInvested = simulatedEthBeforeInvested + ethTowardsVariablePriceTokens;
| 80,504 |
6 | // slashing parameter settings record the quit request | address[] public quitRequestList;
| address[] public quitRequestList;
| 4,061 |
7 | // Current max bid in ETH | uint256 loanAmount;
| uint256 loanAmount;
| 8,893 |
85 | // SB07Offer / | contract SB07Offer is Ownable, IOffer {
uint256 public constant TOKEN_BASE_RATE = 2500;
uint256 public constant MIN_TOTAL_TOKEN_SOLD = 32000 * 1 ether;
uint256 public constant TOTAL_TOKENS = 32175.09 * 1 ether;
address public constant OWNER = 0xe7463F674837F3035a4fBE15Da5D50F5cAC982f4;
// If the offer has been initialized by the owner
bool private bInitialized;
// If the success condition has been met
bool private bSuccess;
// If the offer has finished the sale of tokens
bool private bFinished;
// A counter of the total amount of tokens sold
uint256 internal nTotalSold;
// The date the offer finishOffer function was called
uint256 internal nFinishDate;
// To save cashout date/amount so we can filter by date
struct SubPayment {
// The amount of tokens the user cashed out
uint256 amount;
// The date the user performed this cash out
uint256 date;
}
// Create a structure to save our payments
struct Payment {
// The total amount the user bought
uint256 totalInputAmount;
// The total amount the user bought in tokens
uint256 totalAmount;
// The total amount the user has received in tokens
uint256 totalPaid;
// Dates the user cashed out from the offer
SubPayment[] cashouts;
// Payments
SubPayment[] payments;
}
// A map of address to payment
mapping(address => Payment) internal mapPayments;
// SafeMath for all math operations
using SafeMath for uint256;
// A reference to the BRLToken contract
LiqiBRLToken private brlToken;
// A reference to the issuer of the offer
address private aIssuer;
// Total amount of BRLT tokens collected during sale
uint256 internal nTotalCollected;
// A reference to the token were selling
BaseOfferToken private baseToken;
// A counter for the total amount users have cashed out
uint256 private nTotalCashedOut;
constructor(
address _issuer,
address _brlTokenContract,
address _tokenAddress
)
public
{
// save the issuer's address
aIssuer = _issuer;
// convert the BRLT's address to our interface
brlToken = LiqiBRLToken(_brlTokenContract);
// convert the token's address to our interface
baseToken = BaseOfferToken(_tokenAddress);
}
/*
* @dev Initializes the sale
*/
function initialize() public override {
require(!bInitialized, "Offer is already initialized");
// for OutputOnDemand, only the token can call initialize
require(_msgSender() == address(baseToken), "Only call from token");
bInitialized = true;
}
/**
* @dev Cashouts BRLTs paid to the offer to the issuer
* @notice Faz o cashout de todos os BRLTs que estão nesta oferta para o issuer, se a oferta já tiver sucesso.
*/
function cashoutIssuerBRLT() public {
// no cashout if offer is not successful
require(bSuccess, "Offer is not successful");
// check the balance of tokens of this contract
uint256 nBalance = brlToken.balanceOf(address(this));
// nothing to execute if the balance is 0
require(nBalance != 0, "Balance to cashout is 0");
// transfer all tokens to the issuer account
brlToken.transfer(aIssuer, nBalance);
}
/**
* @dev Returns the address of the input token
* @notice Retorna o endereço do token de input (BRLT)
*/
function getInputToken() public view returns (address) {
return address(brlToken);
}
/**
* @dev Returns the total amount of tokens invested
* @notice Retorna quanto total do token de input (BRLT) foi coletado
*/
function getTotalCollected() public view returns (uint256) {
return nTotalCollected;
}
/**
* @dev Returns the total amount of tokens the specified
* investor has bought from this contract, up to the specified date
* @notice Retorna quanto o investidor comprou até a data especificada
*/
function getTotalBoughtDate(address _investor, uint256 _date)
public
view
override
returns (uint256)
{
Payment memory payment = mapPayments[_investor];
uint256 nTotal = 0;
for (uint256 i = 0; i < payment.payments.length; i++) {
SubPayment memory subPayment = payment.payments[i];
if (subPayment.date >= _date) {
break;
}
nTotal = nTotal.add(subPayment.amount);
}
return nTotal;
}
/**
* @dev Returns the total amount of tokens the specified investor
* has cashed out from this contract, up to the specified date
* @notice Retorna quanto o investidor sacou até a data especificada
*/
function getTotalCashedOutDate(address _investor, uint256 _date)
external
view
virtual
override
returns (uint256)
{
Payment memory payment = mapPayments[_investor];
uint256 nTotal = 0;
for (uint256 i = 0; i < payment.cashouts.length; i++) {
SubPayment memory cashout = payment.cashouts[i];
if (cashout.date >= _date) {
break;
}
nTotal = nTotal.add(cashout.amount);
}
return nTotal;
}
/**
* @dev Returns the address of the token being sold
* @notice Retorna o endereço do token sendo vendido
*/
function getToken() public view returns (address token) {
return address(baseToken);
}
/**
* @dev Declare an investment for an address
*/
function invest(address _investor, uint256 _amount) public onlyOwner {
// make sure the investor is not an empty address
require(_investor != address(0), "Investor is empty");
// make sure the amount is not zero
require(_amount != 0, "Amount is zero");
// do not sell if offer is finished
require(!bFinished, "Offer is already finished");
// do not sell if not initialized
require(bInitialized, "Offer is not initialized");
// read the payment data from our map
Payment storage payment = mapPayments[_investor];
// increase the amount of tokens this investor has invested
payment.totalInputAmount = payment.totalInputAmount.add(_amount);
// process input data
// call with same arguments
brlToken.invest(_investor, _amount);
// add the amount to the total
nTotalCollected = nTotalCollected.add(_amount);
// convert input currency to output
// - get rate from module
uint256 nRate = getRate();
// - total amount from the rate obtained
uint256 nOutputAmount = _amount.div(nRate);
// increase the amount of tokens this investor has purchased
payment.totalAmount = payment.totalAmount.add(nOutputAmount);
// pass to module to handling outputs
// get the current contract's balance
uint256 nBalance = baseToken.balanceOf(address(this));
// dont sell tokens that are already cashed out
uint256 nRemainingToCashOut = nTotalSold.sub(nTotalCashedOut);
// calculate how many tokens we can sell
uint256 nRemainingBalance = nBalance.sub(nRemainingToCashOut);
// make sure we're not selling more than we have
require(
nOutputAmount <= nRemainingBalance,
"Offer does not have enough tokens to sell"
);
// log the payment
SubPayment memory subPayment;
subPayment.amount = nOutputAmount;
subPayment.date = block.timestamp;
payment.payments.push(subPayment);
// after everything, add the bought tokens to the total
nTotalSold = nTotalSold.add(nOutputAmount);
// and check if the offer is sucessful after this sale
if (!bSuccess) {
if (nTotalSold >= MIN_TOTAL_TOKEN_SOLD) {
// we have sold more than minimum, success
bSuccess = true;
}
}
}
/*
* @dev Marks the offer as finished
*/
function finishOffer() public onlyOwner {
require(!bFinished, "Offer is already finished");
bFinished = true;
// save the date the offer finished
nFinishDate = block.timestamp;
if (!getSuccess()) {
// notify the BRLT token that we failed, so tokens are burned
brlToken.failedSale();
}
// get the current contract's balance
uint256 nBalance = baseToken.balanceOf(address(this));
if (getSuccess()) {
uint256 nRemainingToCashOut = nTotalSold.sub(nTotalCashedOut);
// calculate how many tokens we have not sold
uint256 nRemainingBalance = nBalance.sub(nRemainingToCashOut);
if (nRemainingBalance != 0) {
// return remaining tokens to issuer
baseToken.transfer(aIssuer, nRemainingBalance);
}
} else {
// return all tokens to issuer
baseToken.transfer(aIssuer, nBalance);
}
}
/*
* @dev Cashouts tokens for a specified user
*/
function cashoutTokens(address _investor) external virtual override returns (bool) {
// cashout is automatic, and done ONLY by the token
require(_msgSender() == address(baseToken), "Call only from token");
// wait till the offer is successful to allow transfer
if (!bSuccess) {
return false;
}
// read the token sale data for that address
Payment storage payment = mapPayments[_investor];
// nothing to be paid
if (payment.totalAmount == 0) {
return false;
}
// calculate the remaining tokens
uint256 nRemaining = payment.totalAmount.sub(payment.totalPaid);
// make sure there's something to be paid
if (nRemaining == 0) {
return false;
}
// transfer to requested user
baseToken.transfer(_investor, nRemaining);
// mark that we paid the user in fully
payment.totalPaid = payment.totalAmount;
// increase the total cashed out
nTotalCashedOut = nTotalCashedOut.add(nRemaining);
// log the cashout
SubPayment memory cashout;
cashout.amount = nRemaining;
cashout.date = block.timestamp;
payment.cashouts.push(cashout);
return true;
}
/*
* @dev Returns the current rate for the token
*/
function getRate() public view virtual returns (uint256 rate) {
return TOKEN_BASE_RATE;
}
/*
* @dev Gets how much the specified user has bought from this offer
*/
function getTotalBought(address _investor) public view override returns (uint256 nTotalBought) {
return mapPayments[_investor].totalAmount;
}
/*
* @dev Get total amount the user has cashed out from this offer
*/
function getTotalCashedOut(address _investor) public view override returns (uint256 nTotalCashedOut) {
return mapPayments[_investor].totalPaid;
}
/*
* @dev Returns true if the offer is initialized
*/
function getInitialized() public view override returns (bool) {
return bInitialized;
}
/*
* @dev Returns true if the offer is finished
*/
function getFinished() public view override returns (bool) {
return bFinished;
}
/*
* @dev Returns true if the offer is successful
*/
function getSuccess() public view override returns (bool) {
return bSuccess;
}
/*
* @dev Gets the total amount of tokens sold
*/
function getTotalSold() public view virtual returns (uint256 totalSold) {
return nTotalSold;
}
/*
* @dev Gets the date the offer finished at
*/
function getFinishDate() external view override returns (uint256) {
return nFinishDate;
}
} | contract SB07Offer is Ownable, IOffer {
uint256 public constant TOKEN_BASE_RATE = 2500;
uint256 public constant MIN_TOTAL_TOKEN_SOLD = 32000 * 1 ether;
uint256 public constant TOTAL_TOKENS = 32175.09 * 1 ether;
address public constant OWNER = 0xe7463F674837F3035a4fBE15Da5D50F5cAC982f4;
// If the offer has been initialized by the owner
bool private bInitialized;
// If the success condition has been met
bool private bSuccess;
// If the offer has finished the sale of tokens
bool private bFinished;
// A counter of the total amount of tokens sold
uint256 internal nTotalSold;
// The date the offer finishOffer function was called
uint256 internal nFinishDate;
// To save cashout date/amount so we can filter by date
struct SubPayment {
// The amount of tokens the user cashed out
uint256 amount;
// The date the user performed this cash out
uint256 date;
}
// Create a structure to save our payments
struct Payment {
// The total amount the user bought
uint256 totalInputAmount;
// The total amount the user bought in tokens
uint256 totalAmount;
// The total amount the user has received in tokens
uint256 totalPaid;
// Dates the user cashed out from the offer
SubPayment[] cashouts;
// Payments
SubPayment[] payments;
}
// A map of address to payment
mapping(address => Payment) internal mapPayments;
// SafeMath for all math operations
using SafeMath for uint256;
// A reference to the BRLToken contract
LiqiBRLToken private brlToken;
// A reference to the issuer of the offer
address private aIssuer;
// Total amount of BRLT tokens collected during sale
uint256 internal nTotalCollected;
// A reference to the token were selling
BaseOfferToken private baseToken;
// A counter for the total amount users have cashed out
uint256 private nTotalCashedOut;
constructor(
address _issuer,
address _brlTokenContract,
address _tokenAddress
)
public
{
// save the issuer's address
aIssuer = _issuer;
// convert the BRLT's address to our interface
brlToken = LiqiBRLToken(_brlTokenContract);
// convert the token's address to our interface
baseToken = BaseOfferToken(_tokenAddress);
}
/*
* @dev Initializes the sale
*/
function initialize() public override {
require(!bInitialized, "Offer is already initialized");
// for OutputOnDemand, only the token can call initialize
require(_msgSender() == address(baseToken), "Only call from token");
bInitialized = true;
}
/**
* @dev Cashouts BRLTs paid to the offer to the issuer
* @notice Faz o cashout de todos os BRLTs que estão nesta oferta para o issuer, se a oferta já tiver sucesso.
*/
function cashoutIssuerBRLT() public {
// no cashout if offer is not successful
require(bSuccess, "Offer is not successful");
// check the balance of tokens of this contract
uint256 nBalance = brlToken.balanceOf(address(this));
// nothing to execute if the balance is 0
require(nBalance != 0, "Balance to cashout is 0");
// transfer all tokens to the issuer account
brlToken.transfer(aIssuer, nBalance);
}
/**
* @dev Returns the address of the input token
* @notice Retorna o endereço do token de input (BRLT)
*/
function getInputToken() public view returns (address) {
return address(brlToken);
}
/**
* @dev Returns the total amount of tokens invested
* @notice Retorna quanto total do token de input (BRLT) foi coletado
*/
function getTotalCollected() public view returns (uint256) {
return nTotalCollected;
}
/**
* @dev Returns the total amount of tokens the specified
* investor has bought from this contract, up to the specified date
* @notice Retorna quanto o investidor comprou até a data especificada
*/
function getTotalBoughtDate(address _investor, uint256 _date)
public
view
override
returns (uint256)
{
Payment memory payment = mapPayments[_investor];
uint256 nTotal = 0;
for (uint256 i = 0; i < payment.payments.length; i++) {
SubPayment memory subPayment = payment.payments[i];
if (subPayment.date >= _date) {
break;
}
nTotal = nTotal.add(subPayment.amount);
}
return nTotal;
}
/**
* @dev Returns the total amount of tokens the specified investor
* has cashed out from this contract, up to the specified date
* @notice Retorna quanto o investidor sacou até a data especificada
*/
function getTotalCashedOutDate(address _investor, uint256 _date)
external
view
virtual
override
returns (uint256)
{
Payment memory payment = mapPayments[_investor];
uint256 nTotal = 0;
for (uint256 i = 0; i < payment.cashouts.length; i++) {
SubPayment memory cashout = payment.cashouts[i];
if (cashout.date >= _date) {
break;
}
nTotal = nTotal.add(cashout.amount);
}
return nTotal;
}
/**
* @dev Returns the address of the token being sold
* @notice Retorna o endereço do token sendo vendido
*/
function getToken() public view returns (address token) {
return address(baseToken);
}
/**
* @dev Declare an investment for an address
*/
function invest(address _investor, uint256 _amount) public onlyOwner {
// make sure the investor is not an empty address
require(_investor != address(0), "Investor is empty");
// make sure the amount is not zero
require(_amount != 0, "Amount is zero");
// do not sell if offer is finished
require(!bFinished, "Offer is already finished");
// do not sell if not initialized
require(bInitialized, "Offer is not initialized");
// read the payment data from our map
Payment storage payment = mapPayments[_investor];
// increase the amount of tokens this investor has invested
payment.totalInputAmount = payment.totalInputAmount.add(_amount);
// process input data
// call with same arguments
brlToken.invest(_investor, _amount);
// add the amount to the total
nTotalCollected = nTotalCollected.add(_amount);
// convert input currency to output
// - get rate from module
uint256 nRate = getRate();
// - total amount from the rate obtained
uint256 nOutputAmount = _amount.div(nRate);
// increase the amount of tokens this investor has purchased
payment.totalAmount = payment.totalAmount.add(nOutputAmount);
// pass to module to handling outputs
// get the current contract's balance
uint256 nBalance = baseToken.balanceOf(address(this));
// dont sell tokens that are already cashed out
uint256 nRemainingToCashOut = nTotalSold.sub(nTotalCashedOut);
// calculate how many tokens we can sell
uint256 nRemainingBalance = nBalance.sub(nRemainingToCashOut);
// make sure we're not selling more than we have
require(
nOutputAmount <= nRemainingBalance,
"Offer does not have enough tokens to sell"
);
// log the payment
SubPayment memory subPayment;
subPayment.amount = nOutputAmount;
subPayment.date = block.timestamp;
payment.payments.push(subPayment);
// after everything, add the bought tokens to the total
nTotalSold = nTotalSold.add(nOutputAmount);
// and check if the offer is sucessful after this sale
if (!bSuccess) {
if (nTotalSold >= MIN_TOTAL_TOKEN_SOLD) {
// we have sold more than minimum, success
bSuccess = true;
}
}
}
/*
* @dev Marks the offer as finished
*/
function finishOffer() public onlyOwner {
require(!bFinished, "Offer is already finished");
bFinished = true;
// save the date the offer finished
nFinishDate = block.timestamp;
if (!getSuccess()) {
// notify the BRLT token that we failed, so tokens are burned
brlToken.failedSale();
}
// get the current contract's balance
uint256 nBalance = baseToken.balanceOf(address(this));
if (getSuccess()) {
uint256 nRemainingToCashOut = nTotalSold.sub(nTotalCashedOut);
// calculate how many tokens we have not sold
uint256 nRemainingBalance = nBalance.sub(nRemainingToCashOut);
if (nRemainingBalance != 0) {
// return remaining tokens to issuer
baseToken.transfer(aIssuer, nRemainingBalance);
}
} else {
// return all tokens to issuer
baseToken.transfer(aIssuer, nBalance);
}
}
/*
* @dev Cashouts tokens for a specified user
*/
function cashoutTokens(address _investor) external virtual override returns (bool) {
// cashout is automatic, and done ONLY by the token
require(_msgSender() == address(baseToken), "Call only from token");
// wait till the offer is successful to allow transfer
if (!bSuccess) {
return false;
}
// read the token sale data for that address
Payment storage payment = mapPayments[_investor];
// nothing to be paid
if (payment.totalAmount == 0) {
return false;
}
// calculate the remaining tokens
uint256 nRemaining = payment.totalAmount.sub(payment.totalPaid);
// make sure there's something to be paid
if (nRemaining == 0) {
return false;
}
// transfer to requested user
baseToken.transfer(_investor, nRemaining);
// mark that we paid the user in fully
payment.totalPaid = payment.totalAmount;
// increase the total cashed out
nTotalCashedOut = nTotalCashedOut.add(nRemaining);
// log the cashout
SubPayment memory cashout;
cashout.amount = nRemaining;
cashout.date = block.timestamp;
payment.cashouts.push(cashout);
return true;
}
/*
* @dev Returns the current rate for the token
*/
function getRate() public view virtual returns (uint256 rate) {
return TOKEN_BASE_RATE;
}
/*
* @dev Gets how much the specified user has bought from this offer
*/
function getTotalBought(address _investor) public view override returns (uint256 nTotalBought) {
return mapPayments[_investor].totalAmount;
}
/*
* @dev Get total amount the user has cashed out from this offer
*/
function getTotalCashedOut(address _investor) public view override returns (uint256 nTotalCashedOut) {
return mapPayments[_investor].totalPaid;
}
/*
* @dev Returns true if the offer is initialized
*/
function getInitialized() public view override returns (bool) {
return bInitialized;
}
/*
* @dev Returns true if the offer is finished
*/
function getFinished() public view override returns (bool) {
return bFinished;
}
/*
* @dev Returns true if the offer is successful
*/
function getSuccess() public view override returns (bool) {
return bSuccess;
}
/*
* @dev Gets the total amount of tokens sold
*/
function getTotalSold() public view virtual returns (uint256 totalSold) {
return nTotalSold;
}
/*
* @dev Gets the date the offer finished at
*/
function getFinishDate() external view override returns (uint256) {
return nFinishDate;
}
} | 20,606 |
109 | // Also it's a good time to rebase! | rebase();
emit Harvested(VESPER_WBTC, _wbtc, _fee);
| rebase();
emit Harvested(VESPER_WBTC, _wbtc, _fee);
| 61,364 |
58 | // Ensure this token has not been withdrawn | require(!_escrowBalance.executed, "executed");
require(_escrowBalance.tokenAddress != address(0), "!token");
_escrowBalance.executed = true;
| require(!_escrowBalance.executed, "executed");
require(_escrowBalance.tokenAddress != address(0), "!token");
_escrowBalance.executed = true;
| 78,234 |
43 | // set investors to invested | if(resetType == 0) {
usr[usrs[i]].invested = 0;
} else {
| if(resetType == 0) {
usr[usrs[i]].invested = 0;
} else {
| 40,031 |
22 | // Exclude an address from the base minimum price check | function excludeFromPriceCheck(address account) public onlyOwner {
_excludedFromPriceCheck[account] = true;
}
| function excludeFromPriceCheck(address account) public onlyOwner {
_excludedFromPriceCheck[account] = true;
}
| 28,523 |
105 | // function to allow owner to claim other modern ERC20 tokens sent to this contract | function transferAnyERC20Token(address _tokenAddr, address _to, uint _amount) public onlyOwner {
require(_tokenAddr != trustedDepositTokenAddress, "Admin cannot transfer out deposit tokens from this vault!");
require((_tokenAddr != trustedRewardTokenAddress) || (now > adminClaimableTime), "Admin cannot Transfer out Reward Tokens Yet!");
require(Token(_tokenAddr).transfer(_to, _amount), "Could not transfer out tokens!");
}
| function transferAnyERC20Token(address _tokenAddr, address _to, uint _amount) public onlyOwner {
require(_tokenAddr != trustedDepositTokenAddress, "Admin cannot transfer out deposit tokens from this vault!");
require((_tokenAddr != trustedRewardTokenAddress) || (now > adminClaimableTime), "Admin cannot Transfer out Reward Tokens Yet!");
require(Token(_tokenAddr).transfer(_to, _amount), "Could not transfer out tokens!");
}
| 40,350 |
203 | // Numerator: 1. val = 1. val := mulmod(val, 1, PRIME). Denominator: point - trace_generator^(16(trace_length / 16 - 1)). val = denominator_invs[4]. | val := mulmod(val, mload(0x51a0), PRIME)
| val := mulmod(val, mload(0x51a0), PRIME)
| 17,504 |
34 | // Stop copying when the memory counter reaches the length of the first bytes array. | let end := add(mc, length)
for {
| let end := add(mc, length)
for {
| 5,144 |
11 | // create new subdomain, temporarily this smartcontract is the owner | registry.setSubnodeOwner(domainNamehash, subdomainLabelhash, address(this));
| registry.setSubnodeOwner(domainNamehash, subdomainLabelhash, address(this));
| 22,306 |
2 | // string mapping to flight | mapping(bytes32 => Flight) private flights;
bytes32[] private currentFlights;
mapping(address => Airline) private airlines;
| mapping(bytes32 => Flight) private flights;
bytes32[] private currentFlights;
mapping(address => Airline) private airlines;
| 19,900 |
10 | // get the outboundNonce from this source chain which, consequently, is always an EVM_srcAddress - the source chain contract address | function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
| function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64);
| 2,905 |
9 | // Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}. Requirements: - If `data` is empty, `msg.value` must be zero. / | function _dispatchUpgradeToAndCall() private {
(address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
ERC1967Utils.upgradeToAndCall(newImplementation, data);
}
| function _dispatchUpgradeToAndCall() private {
(address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
ERC1967Utils.upgradeToAndCall(newImplementation, data);
}
| 636 |
191 | // Returns the staker reward as interest. / | function _calculateInterestAmount(address _property, address _user)
private
view
returns (
uint256 _amount,
uint256 _interestPrice,
RewardPrices memory _prices
)
| function _calculateInterestAmount(address _property, address _user)
private
view
returns (
uint256 _amount,
uint256 _interestPrice,
RewardPrices memory _prices
)
| 10,387 |
8 | // keccack256("BundledSaleApproval(uint8 protocol,address marketplace,uint256 marketplaceFeeNumerator,address privateBuyer,address seller,address tokenAddress,uint256 expiration,uint256 nonce,uint256 masterNonce,address coin,uint256[] tokenIds,uint256[] amounts,uint256[] maxRoyaltyFeeNumerators,uint256[] itemPrices)") | bytes32 public constant BUNDLED_SALE_APPROVAL_HASH = 0x80244acca7a02d7199149a3038653fc8cb10ca984341ec429a626fab631e1662;
| bytes32 public constant BUNDLED_SALE_APPROVAL_HASH = 0x80244acca7a02d7199149a3038653fc8cb10ca984341ec429a626fab631e1662;
| 39,635 |
20 | // Set immutable state variables | _vault = vault;
_poolId = poolId;
percentFee = _percentFee;
| _vault = vault;
_poolId = poolId;
percentFee = _percentFee;
| 34,303 |
97 | // wallet.transfer(msg.value); | vault.deposit.value(msg.value)(msg.sender);
| vault.deposit.value(msg.value)(msg.sender);
| 23,102 |
149 | // Returns whether `msgSender` is equal to `approvedAddress` or `owner`. / | function _isSenderApprovedOrOwner(
address approvedAddress,
address owner,
address msgSender
| function _isSenderApprovedOrOwner(
address approvedAddress,
address owner,
address msgSender
| 5,055 |
34 | // See {cancelDefaultAdminTransfer}. Internal function without access restriction. / | function _cancelDefaultAdminTransfer() internal virtual {
_setPendingDefaultAdmin(address(0), 0);
}
| function _cancelDefaultAdminTransfer() internal virtual {
_setPendingDefaultAdmin(address(0), 0);
}
| 23,577 |
14 | // ERC20 interface / | 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 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);
}
| 596 |
35 | // Throws if called by any account other than contract itself or owner./ | modifier onlyRelevantSender() {
// proxy owner if used through proxy, address(0) otherwise
require(
!address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy
msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls
msg.sender == address(this) // covers calls through upgradeAndCall proxy method
);
/* solcov ignore next */
_;
}
| modifier onlyRelevantSender() {
// proxy owner if used through proxy, address(0) otherwise
require(
!address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy
msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls
msg.sender == address(this) // covers calls through upgradeAndCall proxy method
);
/* solcov ignore next */
_;
}
| 50,366 |
7 | // address of the active staking contracts | address[] public activeContracts;
event GasCostSet(uint256 newGasCost);
event CollectInterestTimeThresholdSet(
uint256 newCollectInterestTimeThreshold
);
event InterestMultiplierSet(uint8 newInterestMultiplier);
event GasCostExceptInterestCollectSet(
uint256 newGasCostExceptInterestCollect
);
| address[] public activeContracts;
event GasCostSet(uint256 newGasCost);
event CollectInterestTimeThresholdSet(
uint256 newCollectInterestTimeThreshold
);
event InterestMultiplierSet(uint8 newInterestMultiplier);
event GasCostExceptInterestCollectSet(
uint256 newGasCostExceptInterestCollect
);
| 18,525 |
667 | // public inputs | PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0);
| PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0);
| 78,555 |
48 | // Gets the approved address to take ownership of a given token ID _tokenId uint256 ID of the token to query the approval ofreturn address currently approved to take ownership of the given token ID / | function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
| function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
| 25,110 |
6 | // Function to deposit currency to the contract _duration is in blocks from current | function deposit(address _tokenAddress, uint256 _amount, uint _duration) public returns (bool success) {
// Require that user doesn't have any pending balances in this token
require(balances[msg.sender][_tokenAddress] == 0, "You can't have two pending pools with the same currency");
// Check that we have allowance to transfer tokens
require(ERC20Interface(_tokenAddress).allowance(msg.sender,address(this)) >= _amount, "Allowance is too low for this transaction");
// Check that user has requested balance
require(ERC20Interface(_tokenAddress).balanceOf(msg.sender) >= _amount,"Wallet balance is too low for this transaction");
// Good to go, execute transaction
// transfer tokens to this contract
require(ERC20Interface(_tokenAddress).transferFrom(msg.sender,address(this),_amount));
// Experation is current block plus duration
uint experation ; //inject UNINIT LOCAL/STATE VAR
assert(experation > block.number);
balances[msg.sender][_tokenAddress] = _amount;
experations[msg.sender][_tokenAddress] = experation;
return true;
}
| function deposit(address _tokenAddress, uint256 _amount, uint _duration) public returns (bool success) {
// Require that user doesn't have any pending balances in this token
require(balances[msg.sender][_tokenAddress] == 0, "You can't have two pending pools with the same currency");
// Check that we have allowance to transfer tokens
require(ERC20Interface(_tokenAddress).allowance(msg.sender,address(this)) >= _amount, "Allowance is too low for this transaction");
// Check that user has requested balance
require(ERC20Interface(_tokenAddress).balanceOf(msg.sender) >= _amount,"Wallet balance is too low for this transaction");
// Good to go, execute transaction
// transfer tokens to this contract
require(ERC20Interface(_tokenAddress).transferFrom(msg.sender,address(this),_amount));
// Experation is current block plus duration
uint experation ; //inject UNINIT LOCAL/STATE VAR
assert(experation > block.number);
balances[msg.sender][_tokenAddress] = _amount;
experations[msg.sender][_tokenAddress] = experation;
return true;
}
| 705 |
23 | // Receive function.Implemented entirely in `_fallback`. / | receive () payable external {
_fallback();
}
| receive () payable external {
_fallback();
}
| 7,457 |
115 | // If the benefactor is found in the set of exchange pools, then it's a buy transactions, otherwise a sell transactions, because the other use cases have already been checked above. | if (_exchangePools.contains(benefactor)) {
basisPoints = _getBuyTaxBasisPoints(amount, poolBalance);
} else {
| if (_exchangePools.contains(benefactor)) {
basisPoints = _getBuyTaxBasisPoints(amount, poolBalance);
} else {
| 42,299 |
6 | // Some ERC20 do not allow zero amounts to be sent: | if (yieldAmount == 0) return;
uint256 incentiveAmount;
uint256 fee = _incentiveRatio;
bool isIncentiveToken = (getIncentiveToken() == _asset);
if (isIncentiveToken && fee != 0) {
incentiveAmount = yieldAmount.percentMul(fee);
_sendIncentive(incentiveAmount);
}
| if (yieldAmount == 0) return;
uint256 incentiveAmount;
uint256 fee = _incentiveRatio;
bool isIncentiveToken = (getIncentiveToken() == _asset);
if (isIncentiveToken && fee != 0) {
incentiveAmount = yieldAmount.percentMul(fee);
_sendIncentive(incentiveAmount);
}
| 9,008 |
310 | // Get Liquidity for Optimizer's balances | uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper);
| uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper);
| 4,219 |
41 | // Checks unprefixed signatures | function _isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s)
internal
pure
returns (bool)
| function _isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s)
internal
pure
returns (bool)
| 34,549 |
393 | // MasterChef is the master of Olymps. He can make Olymps 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 GEMSTONES 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 Referral, ReentrancyGuard {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
using SafeMath16 for uint16;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 rewardLockedUp; // Reward locked up.
uint256 nextHarvestUntil; // When can the user harvest again.
uint256 lastdeposit;
//
// We do some fancy math here. Basically, any point in time, the amount of OLYMPs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accOlympPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accOlympPerShare` (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 {
IBEP20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. OLYMPs to distribute per block.
uint256 lastRewardBlock; // Last block number that OLYMPs distribution occurs.
uint256 accOlympPerShare; // Accumulated OLYMPs per share, times 1e12. See below.
uint16 depositFeeBP; // Deposit fee in basis points
uint256 harvestInterval; // Harvest interval in seconds
uint256 earlyWithdrawalInterval; // Early withdraw time in seconds
uint256 earlyWithdrawalFee; // Early withdraw fee in percentage
uint16 harvestFee; // harvest fee in percentage
}
// Dev address.
address public devAddress = 0x312937277941446de6E34a678844f14Fc7E9a670;
// Deposit Fee address
address public feeAddress = 0x312937277941446de6E34a678844f14Fc7E9a670;
// OLYMP tokens created per block.
uint256 public olympPerBlock;
//Pools and Farms percent from token per block
uint256 public stakingPercent;
//Developers percent from token per block
uint256 public devPercent;
//Pools, Farms, Dev percent decimals
uint256 public percentDec = 1000000;
// Bonus muliplier for early olymp makers.
uint256 public constant BONUS_MULTIPLIER = 1;
// Max harvest interval: 14 days.
uint256 public constant MAXIMUM_HARVEST_INTERVAL = 14 days;
uint256 public constant MAXIMUM_EARLY_WITHDRAWAL_INTERVAL = 7 days;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Mapping of existing coins added
mapping (address => bool) public lpTokensAdded;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when OLYMP mining starts.
uint256 public startBlock;
// Total locked up rewards
uint256 public totalLockedUpRewards;
// Last block then develeper withdraw dev
uint256 public lastBlockDevWithdraw;
// Referral commission rate in basis points.
uint16 public referralCommissionRate = 200;
// Max referral commission rate: 10%.
uint16 public constant MAXIMUM_REFERRAL_COMMISSION_RATE = 1000;
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 EmissionRateUpdated(address indexed caller, uint256 previousAmount, uint256 newAmount);
event RewardLockedUp(address indexed user, uint256 indexed pid, uint256 amountLockedUp);
constructor(
OlympToken _olymp,
uint256 _startBlock,
uint256 _olympPerBlock,
uint256 _stakingPercent,
uint256 _devPercent,
/* Referral */
uint256 _decimals,
uint256 _secondsUntilInactive,
bool _onlyRewardActiveReferrers,
uint256[] memory _levelRate,
uint256[] memory _refereeBonusRateMap,
ReferralStorage _referralStorage
) public Referral(
_olymp,
_decimals,
_secondsUntilInactive,
_onlyRewardActiveReferrers,
_levelRate,
_refereeBonusRateMap,
_referralStorage
){
olymp = _olymp;
startBlock = _startBlock;
olympPerBlock = _olympPerBlock;
devPercent = _devPercent;
stakingPercent = _stakingPercent;
lastBlockDevWithdraw = _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, IBEP20 _lpToken, uint16 _depositFeeBP, uint256 _harvestInterval,uint256 _earlyWithdrawalInterval, uint16 _earlyWithdrawalFee, uint16 _harvestFee, bool _withUpdate) public onlyOwner {
require(!lpTokensAdded[address(_lpToken)], "Add():: Token Already Added!");
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
require(_earlyWithdrawalFee <= 1000, "set: earlyWithdrawalFee MAX 10%");
require(_harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "set: too high harvest interval");
require(_earlyWithdrawalInterval <= MAXIMUM_EARLY_WITHDRAWAL_INTERVAL, "set: too high earlyWithdrawal interval");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accOlympPerShare: 0,
depositFeeBP: _depositFeeBP,
harvestFee: _harvestFee,
harvestInterval: _harvestInterval,
earlyWithdrawalInterval: _earlyWithdrawalInterval,
earlyWithdrawalFee: _earlyWithdrawalFee
}));
lpTokensAdded[address(_lpToken)] = true;
}
// Update the given pool's OLYMP allocation point and deposit fee. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, uint256 _harvestInterval,uint256 _earlyWithdrawalInterval, uint16 _earlyWithdrawalFee, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points");
require(_earlyWithdrawalFee <= 1000, "set: earlyWithdrawalFee MAX 10%");
require(_harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "set: too high harvest interval");
require(_earlyWithdrawalInterval <= MAXIMUM_EARLY_WITHDRAWAL_INTERVAL, "set: too high earlyWithdrawal interval");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].depositFeeBP = _depositFeeBP;
poolInfo[_pid].harvestInterval = _harvestInterval;
poolInfo[_pid].earlyWithdrawalInterval = _earlyWithdrawalInterval;
poolInfo[_pid].earlyWithdrawalFee = _earlyWithdrawalFee;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
function getlastdeposit(uint256 _pid, address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_pid][_user];
return user.lastdeposit;
}
// View function to see pending OLYMPs on frontend.
function pendingOlymp(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accOlympPerShare = pool.accOlympPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 olympReward = multiplier.mul(olympPerBlock).mul(pool.allocPoint).div(totalAllocPoint).mul(stakingPercent).div(percentDec);
accOlympPerShare = accOlympPerShare.add(olympReward.mul(1e12).div(lpSupply));
}
uint256 pending = user.amount.mul(accOlympPerShare).div(1e12).sub(user.rewardDebt);
return pending.add(user.rewardLockedUp);
}
function withdrawDev() public{
require(lastBlockDevWithdraw < block.number, 'wait for new block');
uint256 multiplier = getMultiplier(lastBlockDevWithdraw, block.number);
uint256 olympReward = multiplier.mul(olympPerBlock);
olymp.mint(devAddress, olympReward.mul(devPercent).div(percentDec));
lastBlockDevWithdraw = block.number;
}
// View function to see if user can harvest OLYMPs.
function canHarvest(uint256 _pid, address _user) public view returns (bool) {
UserInfo storage user = userInfo[_pid][_user];
return block.timestamp >= user.nextHarvestUntil;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 olympReward = multiplier.mul(olympPerBlock).mul(pool.allocPoint).div(totalAllocPoint).mul(stakingPercent).div(percentDec);
olymp.mint(devAddress, olympReward.div(10));
olymp.mint(address(this), olympReward);
pool.accOlympPerShare = pool.accOlympPerShare.add(olympReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for OLYMP allocation.
function deposit(uint256 _pid, uint256 _amount, address _referrer) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
payOrLockupPendingOlymp(_pid);
// If the current user doesn't have a referrer yet, add the address
if (_referrer != address(0) && _amount > 0 && isReferralsEnabled() && !hasReferrer(msg.sender)) {
addReferrer(msg.sender, payable(_referrer));
}
if (_amount > 0) {
// Transfer-tax check
uint256 before = pool.lpToken.balanceOf(address(this));
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
uint256 _after = pool.lpToken.balanceOf(address(this));
_amount = _after.sub(before); //Real LP amount recieved
// retrieve the balance of MC here for LP
uint256 beforeTransferBalance = pool.lpToken.balanceOf(address(this));
// transfer lp to masterchef
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if (address(pool.lpToken) == address(olymp)) {
// check how much masterchef received
uint256 afterTransferBalance = pool.lpToken.balanceOf(address(this));
uint256 actualTransferAmount = afterTransferBalance.sub(beforeTransferBalance);
_amount = actualTransferAmount;
uint256 transferTax = _amount.mul(olymp.transferTaxRate()).div(10000);
_amount = _amount.sub(transferTax);
}
user.lastdeposit=now;
referralStorage.setAccountLastActive(msg.sender);
if (pool.depositFeeBP > 0) {
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
} else {
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accOlympPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: user doesnt have enough funds");
updatePool(_pid);
payOrLockupPendingOlymp(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
if(now > user.lastdeposit + pool.earlyWithdrawalInterval ){
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}else{
uint256 fee = _amount.mul(pool.earlyWithdrawalFee).div(10000);
uint256 amountWithoutFee = _amount.sub(fee);
pool.lpToken.safeTransfer(address(msg.sender), amountWithoutFee);
pool.lpToken.safeTransfer(address(feeAddress), fee);
}
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accOlympPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Pay or lockup pending OLYMPs.
function payOrLockupPendingOlymp(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.nextHarvestUntil == 0) {
user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval);
}
uint256 pending = user.amount.mul(pool.accOlympPerShare).div(1e12).sub(user.rewardDebt);
if (canHarvest(_pid, msg.sender)) {
uint256 totalRewards = pending.add(user.rewardLockedUp);
// reset lockup
totalLockedUpRewards = totalLockedUpRewards.sub(user.rewardLockedUp);
user.rewardLockedUp = 0;
user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval);
uint256 fee = 0;
if(pool.harvestFee > 0){
fee = totalRewards.mul(pool.harvestFee).div(10000);
}
// Take referral cut from harvest -- either burn or distribute
uint256 referralCut = totalRewards.mul(referralCutPercentage).div(10000);
uint256 actualReward = totalRewards.sub(referralCut).sub(fee);
require(referralCut + actualReward + fee == totalRewards, "Referral cut was not properly taken");
// Transfer the 'actual' reward to the user
safeOlympTransfer(msg.sender, actualReward);
// Pay referral
uint256 paidToReferrals = 0;
// If referral is enabled, and the user is referred
if(isReferralsEnabled() && hasReferrer(msg.sender)) {
// Pay the referral cut (note: 60% to first level, 30% to second level, 10% to 3rd)
paidToReferrals = payReferral(msg.sender, referralCut);
uint256 rest = referralCut.sub(paidToReferrals);
// transfer the rest (if any) to fee address (if not all 3 levels are present)
safeOlympTransfer(feeAddress, rest.add(fee));
} else if(fee > 0 || referralCut > 0){
// Transfer to fee address
safeOlympTransfer(feeAddress, referralCut.add(fee));
}
}
else if (pending > 0) {
user.rewardLockedUp = user.rewardLockedUp.add(pending);
totalLockedUpRewards = totalLockedUpRewards.add(pending);
emit RewardLockedUp(msg.sender, _pid, pending);
}
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
user.rewardLockedUp = 0;
user.nextHarvestUntil = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe olymp transfer function, just in case if rounding error causes pool to not have enough OLYMPs.
function safeOlympTransfer(address _to, uint256 _amount) internal {
uint256 olympBal = olymp.balanceOf(address(this));
if (_amount > olympBal) {
olymp.transfer(_to, olympBal);
} else {
olymp.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function setDevAddress(address _devAddress) public {
require(msg.sender == devAddress, "setDevAddress: FORBIDDEN");
require(_devAddress != address(0), "setDevAddress: ZERO");
devAddress = _devAddress;
}
function setFeeAddress(address _feeAddress) public {
require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN");
require(_feeAddress != address(0), "setFeeAddress: ZERO");
feeAddress = _feeAddress;
}
// Pancake has to add hidden dummy pools in order to alter the emission, here we make it simple and transparent to all.
function updateEmissionRate(uint256 _olympPerBlock) public onlyOwner {
massUpdatePools();
emit EmissionRateUpdated(msg.sender, olympPerBlock, _olympPerBlock);
olympPerBlock = _olympPerBlock;
}
} | contract MasterChef is Referral, ReentrancyGuard {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
using SafeMath16 for uint16;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 rewardLockedUp; // Reward locked up.
uint256 nextHarvestUntil; // When can the user harvest again.
uint256 lastdeposit;
//
// We do some fancy math here. Basically, any point in time, the amount of OLYMPs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accOlympPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accOlympPerShare` (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 {
IBEP20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. OLYMPs to distribute per block.
uint256 lastRewardBlock; // Last block number that OLYMPs distribution occurs.
uint256 accOlympPerShare; // Accumulated OLYMPs per share, times 1e12. See below.
uint16 depositFeeBP; // Deposit fee in basis points
uint256 harvestInterval; // Harvest interval in seconds
uint256 earlyWithdrawalInterval; // Early withdraw time in seconds
uint256 earlyWithdrawalFee; // Early withdraw fee in percentage
uint16 harvestFee; // harvest fee in percentage
}
// Dev address.
address public devAddress = 0x312937277941446de6E34a678844f14Fc7E9a670;
// Deposit Fee address
address public feeAddress = 0x312937277941446de6E34a678844f14Fc7E9a670;
// OLYMP tokens created per block.
uint256 public olympPerBlock;
//Pools and Farms percent from token per block
uint256 public stakingPercent;
//Developers percent from token per block
uint256 public devPercent;
//Pools, Farms, Dev percent decimals
uint256 public percentDec = 1000000;
// Bonus muliplier for early olymp makers.
uint256 public constant BONUS_MULTIPLIER = 1;
// Max harvest interval: 14 days.
uint256 public constant MAXIMUM_HARVEST_INTERVAL = 14 days;
uint256 public constant MAXIMUM_EARLY_WITHDRAWAL_INTERVAL = 7 days;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Mapping of existing coins added
mapping (address => bool) public lpTokensAdded;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when OLYMP mining starts.
uint256 public startBlock;
// Total locked up rewards
uint256 public totalLockedUpRewards;
// Last block then develeper withdraw dev
uint256 public lastBlockDevWithdraw;
// Referral commission rate in basis points.
uint16 public referralCommissionRate = 200;
// Max referral commission rate: 10%.
uint16 public constant MAXIMUM_REFERRAL_COMMISSION_RATE = 1000;
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 EmissionRateUpdated(address indexed caller, uint256 previousAmount, uint256 newAmount);
event RewardLockedUp(address indexed user, uint256 indexed pid, uint256 amountLockedUp);
constructor(
OlympToken _olymp,
uint256 _startBlock,
uint256 _olympPerBlock,
uint256 _stakingPercent,
uint256 _devPercent,
/* Referral */
uint256 _decimals,
uint256 _secondsUntilInactive,
bool _onlyRewardActiveReferrers,
uint256[] memory _levelRate,
uint256[] memory _refereeBonusRateMap,
ReferralStorage _referralStorage
) public Referral(
_olymp,
_decimals,
_secondsUntilInactive,
_onlyRewardActiveReferrers,
_levelRate,
_refereeBonusRateMap,
_referralStorage
){
olymp = _olymp;
startBlock = _startBlock;
olympPerBlock = _olympPerBlock;
devPercent = _devPercent;
stakingPercent = _stakingPercent;
lastBlockDevWithdraw = _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, IBEP20 _lpToken, uint16 _depositFeeBP, uint256 _harvestInterval,uint256 _earlyWithdrawalInterval, uint16 _earlyWithdrawalFee, uint16 _harvestFee, bool _withUpdate) public onlyOwner {
require(!lpTokensAdded[address(_lpToken)], "Add():: Token Already Added!");
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
require(_earlyWithdrawalFee <= 1000, "set: earlyWithdrawalFee MAX 10%");
require(_harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "set: too high harvest interval");
require(_earlyWithdrawalInterval <= MAXIMUM_EARLY_WITHDRAWAL_INTERVAL, "set: too high earlyWithdrawal interval");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accOlympPerShare: 0,
depositFeeBP: _depositFeeBP,
harvestFee: _harvestFee,
harvestInterval: _harvestInterval,
earlyWithdrawalInterval: _earlyWithdrawalInterval,
earlyWithdrawalFee: _earlyWithdrawalFee
}));
lpTokensAdded[address(_lpToken)] = true;
}
// Update the given pool's OLYMP allocation point and deposit fee. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, uint256 _harvestInterval,uint256 _earlyWithdrawalInterval, uint16 _earlyWithdrawalFee, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points");
require(_earlyWithdrawalFee <= 1000, "set: earlyWithdrawalFee MAX 10%");
require(_harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "set: too high harvest interval");
require(_earlyWithdrawalInterval <= MAXIMUM_EARLY_WITHDRAWAL_INTERVAL, "set: too high earlyWithdrawal interval");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].depositFeeBP = _depositFeeBP;
poolInfo[_pid].harvestInterval = _harvestInterval;
poolInfo[_pid].earlyWithdrawalInterval = _earlyWithdrawalInterval;
poolInfo[_pid].earlyWithdrawalFee = _earlyWithdrawalFee;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
function getlastdeposit(uint256 _pid, address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_pid][_user];
return user.lastdeposit;
}
// View function to see pending OLYMPs on frontend.
function pendingOlymp(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accOlympPerShare = pool.accOlympPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 olympReward = multiplier.mul(olympPerBlock).mul(pool.allocPoint).div(totalAllocPoint).mul(stakingPercent).div(percentDec);
accOlympPerShare = accOlympPerShare.add(olympReward.mul(1e12).div(lpSupply));
}
uint256 pending = user.amount.mul(accOlympPerShare).div(1e12).sub(user.rewardDebt);
return pending.add(user.rewardLockedUp);
}
function withdrawDev() public{
require(lastBlockDevWithdraw < block.number, 'wait for new block');
uint256 multiplier = getMultiplier(lastBlockDevWithdraw, block.number);
uint256 olympReward = multiplier.mul(olympPerBlock);
olymp.mint(devAddress, olympReward.mul(devPercent).div(percentDec));
lastBlockDevWithdraw = block.number;
}
// View function to see if user can harvest OLYMPs.
function canHarvest(uint256 _pid, address _user) public view returns (bool) {
UserInfo storage user = userInfo[_pid][_user];
return block.timestamp >= user.nextHarvestUntil;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 olympReward = multiplier.mul(olympPerBlock).mul(pool.allocPoint).div(totalAllocPoint).mul(stakingPercent).div(percentDec);
olymp.mint(devAddress, olympReward.div(10));
olymp.mint(address(this), olympReward);
pool.accOlympPerShare = pool.accOlympPerShare.add(olympReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for OLYMP allocation.
function deposit(uint256 _pid, uint256 _amount, address _referrer) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
payOrLockupPendingOlymp(_pid);
// If the current user doesn't have a referrer yet, add the address
if (_referrer != address(0) && _amount > 0 && isReferralsEnabled() && !hasReferrer(msg.sender)) {
addReferrer(msg.sender, payable(_referrer));
}
if (_amount > 0) {
// Transfer-tax check
uint256 before = pool.lpToken.balanceOf(address(this));
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
uint256 _after = pool.lpToken.balanceOf(address(this));
_amount = _after.sub(before); //Real LP amount recieved
// retrieve the balance of MC here for LP
uint256 beforeTransferBalance = pool.lpToken.balanceOf(address(this));
// transfer lp to masterchef
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if (address(pool.lpToken) == address(olymp)) {
// check how much masterchef received
uint256 afterTransferBalance = pool.lpToken.balanceOf(address(this));
uint256 actualTransferAmount = afterTransferBalance.sub(beforeTransferBalance);
_amount = actualTransferAmount;
uint256 transferTax = _amount.mul(olymp.transferTaxRate()).div(10000);
_amount = _amount.sub(transferTax);
}
user.lastdeposit=now;
referralStorage.setAccountLastActive(msg.sender);
if (pool.depositFeeBP > 0) {
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
} else {
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accOlympPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: user doesnt have enough funds");
updatePool(_pid);
payOrLockupPendingOlymp(_pid);
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
if(now > user.lastdeposit + pool.earlyWithdrawalInterval ){
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}else{
uint256 fee = _amount.mul(pool.earlyWithdrawalFee).div(10000);
uint256 amountWithoutFee = _amount.sub(fee);
pool.lpToken.safeTransfer(address(msg.sender), amountWithoutFee);
pool.lpToken.safeTransfer(address(feeAddress), fee);
}
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accOlympPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Pay or lockup pending OLYMPs.
function payOrLockupPendingOlymp(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.nextHarvestUntil == 0) {
user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval);
}
uint256 pending = user.amount.mul(pool.accOlympPerShare).div(1e12).sub(user.rewardDebt);
if (canHarvest(_pid, msg.sender)) {
uint256 totalRewards = pending.add(user.rewardLockedUp);
// reset lockup
totalLockedUpRewards = totalLockedUpRewards.sub(user.rewardLockedUp);
user.rewardLockedUp = 0;
user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval);
uint256 fee = 0;
if(pool.harvestFee > 0){
fee = totalRewards.mul(pool.harvestFee).div(10000);
}
// Take referral cut from harvest -- either burn or distribute
uint256 referralCut = totalRewards.mul(referralCutPercentage).div(10000);
uint256 actualReward = totalRewards.sub(referralCut).sub(fee);
require(referralCut + actualReward + fee == totalRewards, "Referral cut was not properly taken");
// Transfer the 'actual' reward to the user
safeOlympTransfer(msg.sender, actualReward);
// Pay referral
uint256 paidToReferrals = 0;
// If referral is enabled, and the user is referred
if(isReferralsEnabled() && hasReferrer(msg.sender)) {
// Pay the referral cut (note: 60% to first level, 30% to second level, 10% to 3rd)
paidToReferrals = payReferral(msg.sender, referralCut);
uint256 rest = referralCut.sub(paidToReferrals);
// transfer the rest (if any) to fee address (if not all 3 levels are present)
safeOlympTransfer(feeAddress, rest.add(fee));
} else if(fee > 0 || referralCut > 0){
// Transfer to fee address
safeOlympTransfer(feeAddress, referralCut.add(fee));
}
}
else if (pending > 0) {
user.rewardLockedUp = user.rewardLockedUp.add(pending);
totalLockedUpRewards = totalLockedUpRewards.add(pending);
emit RewardLockedUp(msg.sender, _pid, pending);
}
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
user.rewardLockedUp = 0;
user.nextHarvestUntil = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe olymp transfer function, just in case if rounding error causes pool to not have enough OLYMPs.
function safeOlympTransfer(address _to, uint256 _amount) internal {
uint256 olympBal = olymp.balanceOf(address(this));
if (_amount > olympBal) {
olymp.transfer(_to, olympBal);
} else {
olymp.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function setDevAddress(address _devAddress) public {
require(msg.sender == devAddress, "setDevAddress: FORBIDDEN");
require(_devAddress != address(0), "setDevAddress: ZERO");
devAddress = _devAddress;
}
function setFeeAddress(address _feeAddress) public {
require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN");
require(_feeAddress != address(0), "setFeeAddress: ZERO");
feeAddress = _feeAddress;
}
// Pancake has to add hidden dummy pools in order to alter the emission, here we make it simple and transparent to all.
function updateEmissionRate(uint256 _olympPerBlock) public onlyOwner {
massUpdatePools();
emit EmissionRateUpdated(msg.sender, olympPerBlock, _olympPerBlock);
olympPerBlock = _olympPerBlock;
}
} | 3,767 |
320 | // Contract module which provides a basic access control mechanism, wherethere is an account (an owner) that can be granted exclusive access tospecific functions. By default, the owner account will be the one that deploys the contract. Thiscan 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 tothe owner. / | abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
| abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
| 3,915 |
8 | // The next line will calculate the reward for each staked token in the pool.So when a specific user will claim his rewards,we will basically multiply this var by the amount the user staked. | accumulatedRewardPerShare = accumulatedRewardPerShare.add(totalNewReward.mul(1e12).div(totalStaked));
lastRewardTimestamp = block.timestamp;
if (block.timestamp > rewardPeriodEndTimestamp) {
rewardPerSecond = 0;
}
| accumulatedRewardPerShare = accumulatedRewardPerShare.add(totalNewReward.mul(1e12).div(totalStaked));
lastRewardTimestamp = block.timestamp;
if (block.timestamp > rewardPeriodEndTimestamp) {
rewardPerSecond = 0;
}
| 31,281 |
30 | // Main mapping storing an Election record for each election id. | Election[] Elections;
| Election[] Elections;
| 55,452 |
6 | // _num_valid_blocks > 0 | function payFlashbotsMiner(bytes32 _parent_hash, uint256 _num_valid_blocks, uint256 _amount_wei) public payable {
for(uint256 i = 0; i < _num_valid_blocks; i++){
if(checkParentHash(_parent_hash, _num_valid_blocks)){
return;
}
}
revert("stale chain");
}
| function payFlashbotsMiner(bytes32 _parent_hash, uint256 _num_valid_blocks, uint256 _amount_wei) public payable {
for(uint256 i = 0; i < _num_valid_blocks; i++){
if(checkParentHash(_parent_hash, _num_valid_blocks)){
return;
}
}
revert("stale chain");
}
| 41,766 |
194 | // cannot be a contract | require(isContract(msg.sender) == false);
address beneficiary = msg.sender;
uint256 weiAmount = msg.value;
| require(isContract(msg.sender) == false);
address beneficiary = msg.sender;
uint256 weiAmount = msg.value;
| 17,759 |
22 | // Allows an owner to confirm a transaction./transactionId Transaction ID. | function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
| function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
| 13,752 |
2 | // Team gets 25 and 75 are minted for promo and giveaways | _tokenIdCounter.increment();
promoAddress = 0x48B8cB893429D97F3fECbFe6301bdA1c6936d8d9;
mint(promoAddress, 100);
whitelistERC721 = [
0xf1eF40f5aEa5D1501C1B8BCD216CF305764fca40,
0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D,
0x711d2aC13b86BE157795B576dE4bbe6827564111,
0x30d5977e4C9B159C2d44461868Bdc7353C2e425b,
0x7F0AB6a57cfD191a202aB3F813eF9B851C77e618,
| _tokenIdCounter.increment();
promoAddress = 0x48B8cB893429D97F3fECbFe6301bdA1c6936d8d9;
mint(promoAddress, 100);
whitelistERC721 = [
0xf1eF40f5aEa5D1501C1B8BCD216CF305764fca40,
0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D,
0x711d2aC13b86BE157795B576dE4bbe6827564111,
0x30d5977e4C9B159C2d44461868Bdc7353C2e425b,
0x7F0AB6a57cfD191a202aB3F813eF9B851C77e618,
| 45,695 |
1 | // stores pushed results | mapping(address => mapping(bytes4 => Result)) private _results;
| mapping(address => mapping(bytes4 => Result)) private _results;
| 18,465 |
100 | // Emits an {Approval} event. Requirements: - `_owner` cannot be the zero address.- `spender` cannot be the zero address. / | function _approve(ShellStorage.Shell storage shell, 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");
shell.allowances[_owner][spender] = amount;
emit Approval(_owner, spender, amount);
}
| function _approve(ShellStorage.Shell storage shell, 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");
shell.allowances[_owner][spender] = amount;
emit Approval(_owner, spender, amount);
}
| 23,029 |
167 | // used for owner and pre sale addresses | require(
canTransferBeforeTradingIsEnabled[account] != allowed,
"JPOPDOGE: Pre trading is already the value of 'excluded'"
);
canTransferBeforeTradingIsEnabled[account] = allowed;
| require(
canTransferBeforeTradingIsEnabled[account] != allowed,
"JPOPDOGE: Pre trading is already the value of 'excluded'"
);
canTransferBeforeTradingIsEnabled[account] = allowed;
| 58,855 |
7 | // Mints new tokens. to The address that will receive the minted tokens amount The amount of tokens to mint / | function mint(address to, uint256 amount) public onlyOwner {
require(
ERC20.totalSupply() + amount <= cap(),
"ERC20FlexibleCappedSupply: cap exceeded"
);
_mint(to, amount);
}
| function mint(address to, uint256 amount) public onlyOwner {
require(
ERC20.totalSupply() + amount <= cap(),
"ERC20FlexibleCappedSupply: cap exceeded"
);
_mint(to, amount);
}
| 80,165 |
5 | // total rewards | uint256 public totalRewards = 0;
| uint256 public totalRewards = 0;
| 27,210 |
3 | // if (keccak256(abi.encodePacked((ApiStore[_name].name))) == keccak256(abi.encodePacked(("")))) { | ApiInfo api = (new ApiInfo)(_name, _param1, _param2, _cost, oar, _owner);
| ApiInfo api = (new ApiInfo)(_name, _param1, _param2, _cost, oar, _owner);
| 51,943 |
62 | // Make the proposal fail if it is requesting more tokens than the available guild bank balance | if (tokenWhitelist[proposal.paymentToken] && proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken]) {
didPass = false;
}
| if (tokenWhitelist[proposal.paymentToken] && proposal.paymentRequested > userTokenBalances[GUILD][proposal.paymentToken]) {
didPass = false;
}
| 40,008 |
202 | // Decrease pendingParsecs by pendingAmountOfParsecs | pendingParsecs = pendingParsecs.sub(pendingAmountOfParsecs);
| pendingParsecs = pendingParsecs.sub(pendingAmountOfParsecs);
| 19,441 |
6 | // Allows transfer adminship of Registry to new adminTransfer associated token and set admin of registry to new admin_registryID uint256 Registry-token ID_newOwner address Address of new admin/ | function updateRegistryOwnership(
uint256 _registryID,
address _newOwner
)
public
whenNotPaused
onlyOwnerOf(_registryID)
| function updateRegistryOwnership(
uint256 _registryID,
address _newOwner
)
public
whenNotPaused
onlyOwnerOf(_registryID)
| 38,922 |
39 | // Custom verification implementation -Mint signature includes a tokenID and address signed by the backend server / | function _verifySignature(
uint256 _tokenId,
address _address,
bytes memory _signature,
address _signer
| function _verifySignature(
uint256 _tokenId,
address _address,
bytes memory _signature,
address _signer
| 24,975 |
116 | // Expose internal function that exchanges components for Set tokens,accepting any owner, to system modules _ownerAddress to use tokens from_recipientAddress to issue Set to_setAddress of the Set to issue_quantity Number of tokens to issue / | function issueModule(
| function issueModule(
| 42,538 |
363 | // Always allowed when the smart wallet hasn't been deployed yet | if (!walletAddress.isContract()) {
return type(uint).max;
}
| if (!walletAddress.isContract()) {
return type(uint).max;
}
| 54,634 |
25 | // must use type "address payable", to send eth, not just "address" | address payable payableOwner = payable(owner());
payableOwner.transfer(amount);
| address payable payableOwner = payable(owner());
payableOwner.transfer(amount);
| 37,742 |
80 | // Increase house stake by msg.value / | function addHouseStake() public payable onlyOwner {
houseStake += msg.value;
}
| function addHouseStake() public payable onlyOwner {
houseStake += msg.value;
}
| 35,204 |
53 | // Make sure input address is clean. (Solidity does not guarantee this) | input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
| input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
| 6,389 |
43 | // Store pendingAdmin with value newPendingAdmin | pendingAdmin = newPendingAdmin;
| pendingAdmin = newPendingAdmin;
| 1,453 |
40 | // Maximum amount of ETH to collect at price 5. / | uint256 internal constant RESERVE_THRESHOLD_5 = 50000 ether;
| uint256 internal constant RESERVE_THRESHOLD_5 = 50000 ether;
| 14,083 |
22 | // Modified allowing execution only if not stopped | modifier stopInEmergency {
require(!halted);
_;
}
| modifier stopInEmergency {
require(!halted);
_;
}
| 30,656 |
9 | // Internal method to remove a subscriber from the list | function _unsubscribe(uint _cdpId) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_cdpId];
require(subInfo.subscribed, "Must first be subscribed");
uint lastCdpId = subscribers[subscribers.length - 1].cdpId;
SubPosition storage subInfo2 = subscribersPos[lastCdpId];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop();
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender, _cdpId);
}
| function _unsubscribe(uint _cdpId) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_cdpId];
require(subInfo.subscribed, "Must first be subscribed");
uint lastCdpId = subscribers[subscribers.length - 1].cdpId;
SubPosition storage subInfo2 = subscribersPos[lastCdpId];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop();
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender, _cdpId);
}
| 43,299 |
12 | // repatriate | function transferToHomeChain(string memory home_address, string memory data, uint amount, uint reward) external {
_burn(msg.sender, amount);
emit NewRepatriation(msg.sender, amount, reward, home_address, data);
}
| function transferToHomeChain(string memory home_address, string memory data, uint amount, uint reward) external {
_burn(msg.sender, amount);
emit NewRepatriation(msg.sender, amount, reward, home_address, data);
}
| 31,251 |
129 | // purchase | error INSUFFICIENT_ERC20_VALUE();
error INSUFFICIENT_VALUE();
| error INSUFFICIENT_ERC20_VALUE();
error INSUFFICIENT_VALUE();
| 37,732 |
45 | // Reentrancy guard/stop infinite tax sells mainly | inSwap = true;
if (
_allowances[address(this)][address(uniswapV2Router)] < tokenAmount
) {
| inSwap = true;
if (
_allowances[address(this)][address(uniswapV2Router)] < tokenAmount
) {
| 458 |
44 | // the wallet who has authority to mint a token | address public mintAuthority = 0x66E69Dc02f0B4F8FE80f31417C56e91e22354B1F;
| address public mintAuthority = 0x66E69Dc02f0B4F8FE80f31417C56e91e22354B1F;
| 34,385 |
30 | // I present a struct which takes only 20k gas | struct playerRoll{
uint200 tokenValue; // Token value in uint
uint48 blockn; // Block number 48 bits
uint8 rollUnder; // Roll under 8 bits
}
| struct playerRoll{
uint200 tokenValue; // Token value in uint
uint48 blockn; // Block number 48 bits
uint8 rollUnder; // Roll under 8 bits
}
| 25,156 |
88 | // Joins an array of slices, using `self` as a delimiter, returning a newly allocated string. self The delimiter to use. parts A list of slices to join.return A newly allocated string containing all the slices in `parts`,joined with `self`. / | function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(uint i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
| function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(uint i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
| 11,956 |
7 | // emergency withdraw ERC20, can only call by the owner/ to withdraw tokens that have been sent to this address | function emergencyERC20Drain(IERC20 token, uint256 amount) external onlyOwner {
token.safeTransfer(owner(), amount);
}
| function emergencyERC20Drain(IERC20 token, uint256 amount) external onlyOwner {
token.safeTransfer(owner(), amount);
}
| 28,635 |
12 | // Balances for each account | mapping(address => uint256) balances;
| mapping(address => uint256) balances;
| 1,266 |
329 | // Sets the ERC-1155 metadata URI. newURI The new ERC-1155 metadata URI. / | function setURI(string memory newURI) external;
| function setURI(string memory newURI) external;
| 15,080 |
133 | // allocate token for Z88 Lotto Jackpot | super.transfer(lotto645JackpotWallet, LOTTO645_JACKPOT_ALLOCATION);
super.transfer(lotto655Jackpot1Wallet, LOTTO655_JACKPOT_1_ALLOCATION);
super.transfer(lotto655Jackpot2Wallet, LOTTO655_JACKPOT_2_ALLOCATION);
| super.transfer(lotto645JackpotWallet, LOTTO645_JACKPOT_ALLOCATION);
super.transfer(lotto655Jackpot1Wallet, LOTTO655_JACKPOT_1_ALLOCATION);
super.transfer(lotto655Jackpot2Wallet, LOTTO655_JACKPOT_2_ALLOCATION);
| 12,982 |
1 | // number of LEAFs that owner receives after deploying contracts | uint256 constant OWNER_LEAFS = 1000000 * (10**18);
| uint256 constant OWNER_LEAFS = 1000000 * (10**18);
| 14,859 |
42 | // https:docs.synthetix.io/contracts/source/interfaces/iflexiblestorage | interface IFlexibleStorage {
// Views
function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint);
function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory);
function getIntValue(bytes32 contractName, bytes32 record) external view returns (int);
function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory);
function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address);
function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory);
function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool);
function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory);
function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32);
function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory);
// Mutative functions
function deleteUIntValue(bytes32 contractName, bytes32 record) external;
function deleteIntValue(bytes32 contractName, bytes32 record) external;
function deleteAddressValue(bytes32 contractName, bytes32 record) external;
function deleteBoolValue(bytes32 contractName, bytes32 record) external;
function deleteBytes32Value(bytes32 contractName, bytes32 record) external;
function setUIntValue(
bytes32 contractName,
bytes32 record,
uint value
) external;
function setUIntValues(
bytes32 contractName,
bytes32[] calldata records,
uint[] calldata values
) external;
function setIntValue(
bytes32 contractName,
bytes32 record,
int value
) external;
function setIntValues(
bytes32 contractName,
bytes32[] calldata records,
int[] calldata values
) external;
function setAddressValue(
bytes32 contractName,
bytes32 record,
address value
) external;
function setAddressValues(
bytes32 contractName,
bytes32[] calldata records,
address[] calldata values
) external;
function setBoolValue(
bytes32 contractName,
bytes32 record,
bool value
) external;
function setBoolValues(
bytes32 contractName,
bytes32[] calldata records,
bool[] calldata values
) external;
function setBytes32Value(
bytes32 contractName,
bytes32 record,
bytes32 value
) external;
function setBytes32Values(
bytes32 contractName,
bytes32[] calldata records,
bytes32[] calldata values
) external;
}
| interface IFlexibleStorage {
// Views
function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint);
function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory);
function getIntValue(bytes32 contractName, bytes32 record) external view returns (int);
function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory);
function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address);
function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory);
function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool);
function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory);
function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32);
function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory);
// Mutative functions
function deleteUIntValue(bytes32 contractName, bytes32 record) external;
function deleteIntValue(bytes32 contractName, bytes32 record) external;
function deleteAddressValue(bytes32 contractName, bytes32 record) external;
function deleteBoolValue(bytes32 contractName, bytes32 record) external;
function deleteBytes32Value(bytes32 contractName, bytes32 record) external;
function setUIntValue(
bytes32 contractName,
bytes32 record,
uint value
) external;
function setUIntValues(
bytes32 contractName,
bytes32[] calldata records,
uint[] calldata values
) external;
function setIntValue(
bytes32 contractName,
bytes32 record,
int value
) external;
function setIntValues(
bytes32 contractName,
bytes32[] calldata records,
int[] calldata values
) external;
function setAddressValue(
bytes32 contractName,
bytes32 record,
address value
) external;
function setAddressValues(
bytes32 contractName,
bytes32[] calldata records,
address[] calldata values
) external;
function setBoolValue(
bytes32 contractName,
bytes32 record,
bool value
) external;
function setBoolValues(
bytes32 contractName,
bytes32[] calldata records,
bool[] calldata values
) external;
function setBytes32Value(
bytes32 contractName,
bytes32 record,
bytes32 value
) external;
function setBytes32Values(
bytes32 contractName,
bytes32[] calldata records,
bytes32[] calldata values
) external;
}
| 25,055 |
31 | // Maintain balances for each funding key | mapping(uint256 => uint256) public dappBalances;
| mapping(uint256 => uint256) public dappBalances;
| 10,139 |
5 | // Gets the next sqrt price given a delta of token1/Always rounds down, because in the exact output case (decreasing price) we need to move the price at least/ far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the/ price less in order to not send too much output./ The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity/sqrtPX96 The starting price, i.e., before accounting for the token1 delta/liquidity The amount of usable liquidity/amount How much of token1 to add, or remove, from | function getNextSqrtPriceFromAmount1RoundingDown(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
| function getNextSqrtPriceFromAmount1RoundingDown(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
| 17,764 |
14 | // 管理员列表(管理员权限见上述) | mapping(bytes32 => bool) public administrators; // 管理者地址列表
| mapping(bytes32 => bool) public administrators; // 管理者地址列表
| 43,290 |
82 | // Get rid of the token in the balance list | for (uint d = 0; d < depositedTokens.length; d++) {
if (depositedTokens[d] == tokenaddress) {
delete depositedTokens[d];
}
| for (uint d = 0; d < depositedTokens.length; d++) {
if (depositedTokens[d] == tokenaddress) {
delete depositedTokens[d];
}
| 39,481 |
15 | // Min duration for each fee-sharing period (in blocks) | uint256 public immutable MIN_REWARD_DURATION_IN_BLOCKS;
| uint256 public immutable MIN_REWARD_DURATION_IN_BLOCKS;
| 69,970 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.