comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @dev it will change the ending date of ico and access by owner only * @param _newBlock enter the future blocknumber * @return It will return the blocknumber */
function changeEndBlock(uint256 _newBlock) external onlyOwner returns (uint256 _endblock ) { // we are expecting that owner will input number greater than current block. require(_newBlock > fundingStartBlock); fundingEndBlock = _newBlock; // New block is assigned to extend the Crowd Sal...
0.4.18
// Stake ID uniquely identifies a stake // (note, `stakeNum` uniquely identifies a stake, rest is for UI sake)
function encodeStakeId( address token, // token contract address uint256 stakeNum, // uniq nonce (limited to 48 bits) uint256 unlockTime, // UNIX time (limited to 32 bits) uint256 stakeHours // Stake duration (limited to 16 bits) ) public pure returns (uint256) { requir...
0.6.12
// Returns `true` if the term sheet has NOT been yet added.
function _isMissingTerms(TermSheet memory newSheet) internal view returns (bool) { for (uint256 i = 0; i < termSheets.length; i++) { TermSheet memory sheet = termSheets[i]; if ( sheet.token == newSheet.token && sheet.mi...
0.6.12
// Assuming the given array does contain the given element
function _removeArrayElement(uint256[] storage arr, uint256 el) internal { uint256 lastIndex = arr.length - 1; if (lastIndex != 0) { uint256 replaced = arr[lastIndex]; if (replaced != el) { // Shift elements until the one being removed is replaced ...
0.6.12
/// @dev Creates a new Artwork and mint an edition
function createArtworkAndMintEdition( uint256 _artworkNumber, uint8 _scarcity, string memory _tokenUri, uint16 _totalLeft, bool _active, address _to ) external whenNotPaused onlyMinter returns (uint256) { _createArtwork( _artworkNumber, ...
0.8.7
/// @dev Get artwork details from artworkNumber
function getArtwork(uint256 artworkNumber) external view returns ( uint8 scarcity, uint16 totalMinted, uint16 totalLeft, string memory tokenUri, bool active ) { ArtworkDetails storage a = artworkNumberToArtworkDetail...
0.8.7
/** * @dev Internal factory method to generate an new tokenId based * @dev based on artwork number */
function _getNextTokenId(uint256 _artworkNumber) internal view returns (uint256) { ArtworkDetails storage _artworkDetails = artworkNumberToArtworkDetails[ _artworkNumber ]; // Build next token ID e.g. 100000 + (1 - 1) = ID of 100001 (this first in the edi...
0.8.7
/** * @dev Internal factory method to mint a new edition * @dev for an artwork */
function _mintEdition( address _to, uint256 _artworkNumber, string memory _tokenUri ) internal returns (uint256) { // Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set) uint256 _tokenId = _getNextTokenId(_artworkNumber); // Mint ne...
0.8.7
/// @dev Migrates tokens to a potential new version of this contract /// @param tokenIds - list of tokens to transfer
function migrateTokens(uint256[] calldata tokenIds) external { require( address(newContract) != address(0), "LaCollection: New contract not set" ); for (uint256 index = 0; index < tokenIds.length; index++) { transferFrom(_msgSender(), address(this), tokenIds[...
0.8.7
//Yes this is ugly but it saves gas through binary search & probability theory, a total of 5-10 ETH for our dear hodlers will be saved because of this ugliness
function multiMint(uint amount, address to) private { require(amount > 0, "Invalid amount"); require(_checkOnERC721Received(address(0), to, _mint(to), ''), "ERC721: transfer to non ERC721Receiver implementer"); //Safe mint 1st and regular mint rest to save gas! if (amount < 4) { ...
0.8.11
/* * @dev Get GMI to user */
function getUnLockedGMI() public isActivated() isExhausted() payable { uint256 currentTakeGMI = 0; uint256 unlockedCount = 0; uint256 unlockedGMI = 0; uint256 userLockedGMI = 0; uint256 userTakeTime = 0; (currentTakeGMI, unlockedCount, unlockedGMI, userLockedGMI, userTakeTime) = cal...
0.4.26
/* * @dev calculate user unlocked GMI amount */
function calculateUnLockerGMI(address userAddr) private isActivated() view returns(uint256, uint256, uint256, uint256, uint256) { uint256 unlockedCount = 0; uint256 currentTakeGMI = 0; uint256 userTakenTime = takenTime[userAddr]; uint256 userLockedGMI = lockList[userAddr]; unlockedCount...
0.4.26
/** * @dev Limit burn functions to owner and reduce cap after burning */
function _burn(address _who, uint256 _value) internal onlyOwner { // no need to check _value <= cap since totalSupply <= cap and // _value <= totalSupply was checked in burn functions super._burn(_who, _value); cap = cap.sub(_value); }
0.4.24
/** * Creates new tokens. Can only be called by one of the three owners. Includes * signatures from each of the 3 owners. * The signed messages is a bytes32(equivalent to uint256), which includes the * nonce and the amount intended to be minted. The network ID is not included, * which means owner keys cannot be sh...
function mint(bytes32 signedMessage, uint8 sigV1, bytes32 sigR1, bytes32 sigS1, uint8 sigV2, bytes32 sigR2, bytes32 sigS2, uint8 sigV3, bytes32 sigR3, bytes32 sigS3) external { require(isOwner(), "Must be owner"); require(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", signedMessage)), ...
0.7.6
/** * @dev See {IRoyaltyEngineV1-getRoyalty} */
function getRoyalty(address tokenAddress, uint256 tokenId, uint256 value) public override returns(address payable[] memory recipients, uint256[] memory amounts) { int16 spec; address royaltyAddress; bool addToCache; (recipients, amounts, spec, royaltyAddress, addToCache) = _getRoyaltyAn...
0.8.7
/** * @dev See {IRoyaltyEngineV1-getRoyaltyView}. */
function getRoyaltyView(address tokenAddress, uint256 tokenId, uint256 value) public view override returns(address payable[] memory recipients, uint256[] memory amounts) { (recipients, amounts, , , ) = _getRoyaltyAndSpec(tokenAddress, tokenId, value); return (recipients, amounts); }
0.8.7
/** * Compute royalty amounts */
function _computeAmounts(uint256 value, uint256[] memory bps) private pure returns(uint256[] memory amounts) { amounts = new uint256[](bps.length); uint256 totalAmount; for (uint i = 0; i < bps.length; i++) { amounts[i] = value*bps[i]/10000; totalAmount += amounts[i]; ...
0.8.7
/// @notice Fetches a time-weighted observation for a given Uniswap V3 pool /// @param pool Address of the pool that we want to observe /// @param period Number of seconds in the past to start calculating the time-weighted observation /// @return observation An observation that has been time-weighted from (block.timest...
function consult(address pool, uint32 period) internal view returns (PeriodObservation memory observation) { require(period != 0, 'BP'); uint192 periodX160 = uint192(period) * type(uint160).max; uint32[] memory secondsAgos = new uint32[](2); secondsAgos[0] = period; secondsAgos[1] = 0; (int56...
0.7.6
/// @notice Given some time-weighted observations, calculates the arithmetic mean tick, weighted by liquidity /// @param observations A list of time-weighted observations /// @return arithmeticMeanWeightedTick The arithmetic mean tick, weighted by the observations' time-weighted harmonic average liquidity
function getArithmeticMeanTickWeightedByLiquidity(PeriodObservation[] memory observations) internal pure returns (int24 arithmeticMeanWeightedTick) { // Accumulates the sum of all observations' products between each their own average tick and harmonic average liquidity // Each product can be store...
0.7.6
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _totalSupply total supply of the token. * @param _name token name e.g Dijets. * @param _symbol token symbol e.g DJT. * @param _decimals amount of decimals. */
function DijetsToken(uint256 _totalSupply, string _name, string _symbol, uint8 _decimals) { balances[msg.sender] = _totalSupply; // Give the creator all initial tokens totalSupply = _totalSupply; name = _name; symbol = _symbol; decimals = _decimals; }
0.4.16
/** * @dev Locking {_amounts} with {_unlockAt} date for specific {_account}. */
function lock(address _account, uint256[] memory _unlockAt, uint256[] memory _amounts) external onlyOwner returns (uint256 totalAmount) { require(_account != address(0), "Zero address"); require( _unlockAt.length == _amounts.length && _unlockAt...
0.8.4
/** * @dev Returns next unlock timestamp by all locks, if return zero, * no time points available. */
function getNextUnlock(address _participant) external view returns (uint256 timestamp) { uint256 locksLen = _balances[_participant].locks.length; uint currentUnlock; uint i; for (i; i < locksLen; i++) { currentUnlock = _getNextUnlock(_participant, i); if (cu...
0.8.4
/** * @dev Grants tokens to an account. * * @param beneficiary = Address to which tokens will be granted. * @param vestingAmount = The number of tokens subject to vesting. * @param startDay = Start day of the grant's vesting schedule, in days since the UNIX epoch * (start of day). The startDay may be given as a...
function _addGrant( address beneficiary, uint256 vestingAmount, uint32 startDay, address vestingLocation ) internal { // Make sure no prior grant is in effect. require(!_tokenGrants[beneficiary].isActive, "grant already exists"); // Check for valid vestingAmount require( vesting...
0.6.12
/** * @dev returns all information about the grant's vesting as of the given day * for the given account. Only callable by the account holder or a contract owner. * * @param grantHolder = The address to do this for. * @param onDayOrToday = The day to check for, in days since the UNIX epoch. Can pass * the speci...
function getGrantInfo(address grantHolder, uint32 onDayOrToday) external view override onlyOwnerOrSelf(grantHolder) returns ( uint256 amountVested, uint256 amountNotVested, uint256 amountOfGrant, uint256 amountAvailable, uint256 amountClaimed, uint32 vestStartDay,...
0.6.12
/** * @dev If the account has a revocable grant, this forces the grant to end immediately. * After this function is called, getGrantInfo will return incomplete data * and there will be no possibility to claim non-claimed tokens * * @param grantHolder = Address to which tokens will be granted. */
function revokeGrant(address grantHolder) external override onlyOwner { tokenGrant storage grant = _tokenGrants[grantHolder]; vestingSchedule storage vesting = _vestingSchedules[grant.vestingLocation]; // Make sure a vesting schedule has previously been set. require(grant.isActive, "no active grant"); ...
0.6.12
/** * This function will take a pair and make sure that all Uniswap V3 pools for the pair are properly initialized for future use. * It will also add all available pools to an internal list, to avoid future queries to the factory. * It can be called multiple times for the same pair of tokens, to include and re-confi...
function addSupportForPair(address _tokenA, address _tokenB) external override { uint256 _length = _supportedFeeTiers.length(); (address __tokenA, address __tokenB) = _sortTokens(_tokenA, _tokenB); EnumerableSet.AddressSet storage _pools = _poolsForPair[__tokenA][__tokenB]; uint16 _cardinality = uint16(...
0.7.6
// **** State mutations **** // // Do a `callStatic` on this. // If it returns true then run it for realz. (i.e. eth_signedTx, not eth_call)
function sync() public returns (bool) { uint256 colFactor = getColFactor(); uint256 safeSyncColFactor = getSafeSyncColFactor(); // If we're not safe if (colFactor > safeSyncColFactor) { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSup...
0.6.7
// Leverages until we're supplying <x> amount // 1. Redeem <x> USDC // 2. Repay <x> USDC
function leverageUntil(uint256 _supplyAmount) public onlyKeepers { // 1. Borrow out <X> USDC // 2. Supply <X> USDC uint256 leverage = getMaxLeverage(); uint256 unleveragedSupply = getSuppliedUnleveraged(); require( _supplyAmount >= unleveragedSupply && ...
0.6.7
/// @dev Internal function to actually purchase the tokens.
function deposit() payable public { uint256 _incomingEthereum = msg.value; address _fundingSource = msg.sender; // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_incomingEthereum * magnitude / toke...
0.4.24
/// @dev Debits address by an amount or sets to zero
function debit(address _customerAddress, uint256 amount) onlyWhitelisted external returns (uint256){ //No money movement; usually a lost wager vault[_customerAddress] = Math.max256(0, vault[_customerAddress].sub(amount)); totalCustomerCredit = totalCustomerCredit.sub(amount); /...
0.4.24
/// @dev Withraws balance for address; returns amount sent
function withdraw(address _customerAddress) onlyWhitelisted external returns (uint256){ require(vault[_customerAddress] > 0); uint256 amount = vault[_customerAddress]; vault[_customerAddress] = 0; totalCustomerCredit = totalCustomerCredit.sub(amount); _customerAddress....
0.4.24
/** * @dev The bridge to the launch ecosystem. Community has to participate to dump divs * Should */
function fundP6(uint256 amount) internal { uint256 fee = amount.mul(p6Fee).div(100); p6Outbound = p6Outbound.add(fee); //GO P6 GO!!! if (p6Outbound >= outboundThreshold){ fee = p6Outbound; p6Outbound = 0; p6.buyFor.value(fee)(owner); ...
0.4.24
// // ======= interface methods ======= // //accept payments here
function () payable noReentrancy { State state = currentState(); if (state == State.PRESALE_RUNNING) { receiveFunds(); } else if (state == State.REFUND_RUNNING) { // any entring call in Refund Phase will cause full refund sendRefund(); ...
0.4.8
// // ======= implementation methods ======= //
function sendRefund() private tokenHoldersOnly { // load balance to refund plus amount currently sent var amount_to_refund = balances[msg.sender] + msg.value; // reset balance balances[msg.sender] = 0; // send refund back to sender if (!msg.sender.send(amount_to_ref...
0.4.8
// migrate stakers from previous contract to this one. can only be called before farm starts.
function addStakes(uint _pid, address[] calldata stakers, uint256[] calldata amounts) external onlyOwner { require(block.number < startBlock, "addStakes: farm started."); for(uint i=0; i<stakers.length; i++){ UserInfo storage user = userInfo[_pid][stakers[i]]; PoolInfo storag...
0.6.12
/** * @dev Allows for approvals to be made via secp256k1 signatures. * @param owner The owner of the funds * @param spender The spender * @param value The amount * @param deadline The deadline timestamp, type(uint256).max for max deadline * @param v Signature param * @param s Signature param * @param r ...
function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { require(block.timestamp <= deadline); uint256 ownerNonce = _nonces[owner]; bytes32 permitDataDigest ...
0.6.12
//New Pancakeswap router version? //No problem, just change it!
function setRouterAddress(address newRouter) external onlyOwner() { IUniswapV2Router02 _uniswapV2newRouter = IUniswapV2Router02(newRouter);//v2 router --> 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D // Create a pancakeswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2newRoute...
0.8.4
/** * Update token info for withdraw. The interest will be withdrawn with higher priority. */
function withdraw(TokenInfo storage self, uint256 amount, uint256 accruedRate, uint256 _block) public { newDepositCheckpoint(self, accruedRate, _block); if (self.depositInterest >= amount) { self.depositInterest = self.depositInterest.sub(amount); } else if (self.depositPrincipal...
0.5.14
/** * @dev Sets the given bit in the bitmap value * @param _bitmap Bitmap value to update the bit in * @param _index Index range from 0 to 127 * @return Returns the updated bitmap value */
function setBit(uint128 _bitmap, uint8 _index) internal pure returns (uint128) { // Suppose `_bitmap` is in bit value: // 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set // Bit not set, hence, set the bit if( ! isBitSet(_bitmap, _index)) { /...
0.5.14
/** * @dev Returns true if the corrosponding bit set in the bitmap * @param _bitmap Bitmap value to check * @param _index Index to check. Index range from 0 to 127 * @return Returns true if bit is set, false otherwise */
function isBitSet(uint128 _bitmap, uint8 _index) internal pure returns (bool) { require(_index < 128, "Index out of range for bit operation"); // Suppose `_bitmap` is in bit value: // 0001 0100 = represents third(_index == 2) and fifth(_index == 4) bit is set // Suppose `_index` is...
0.5.14
/** * @dev Add a new token to registry * @param _token ERC20 Token address * @param _decimals Token's decimals * @param _isTransferFeeEnabled Is token changes transfer fee * @param _isSupportedOnCompound Is token supported on Compound * @param _cToken cToken contract address * @param _chainLinkOracle Chai...
function addToken( address _token, uint8 _decimals, bool _isTransferFeeEnabled, bool _isSupportedOnCompound, address _cToken, address _chainLinkOracle ) public onlyOwner { require(_token != address(0), "Token address is zero"); ...
0.5.14
/** * Initialize function to be called by the Deployer for the first time * @param _tokenAddresses list of token addresses * @param _cTokenAddresses list of corresponding cToken addresses * @param _globalConfig global configuration contract */
function initialize( address[] memory _tokenAddresses, address[] memory _cTokenAddresses, GlobalConfig _globalConfig ) public initializer { // Initialize InitializableReentrancyGuard super._initialize(); super._initialize(address(_globalC...
0.5.14
/** * Borrow the amount of token from the saving pool. * @param _token token address * @param _amount amout of tokens to borrow */
function borrow(address _token, uint256 _amount) external onlySupportedToken(_token) onlyEnabledToken(_token) whenNotPaused nonReentrant { require(_amount != 0, "Borrow zero amount of token is not allowed."); globalConfig.bank().borrow(msg.sender, _token, _amount); // Transfer the token...
0.5.14
/** * Withdraw all tokens from the saving pool. * @param _token the address of the withdrawn token */
function withdrawAll(address _token) external onlySupportedToken(_token) whenNotPaused nonReentrant { // Sanity check require(globalConfig.accounts().getDepositPrincipal(msg.sender, _token) > 0, "Token depositPrincipal must be greater than 0"); // Add a new checkpoint on the index curve. ...
0.5.14
/** * @dev Initialize the Collateral flag Bitmap for given account * @notice This function is required for the contract upgrade, as previous users didn't * have this collateral feature. So need to init the collateralBitmap for each user. * @param _account User account address */
function initCollateralFlag(address _account) public { Account storage account = accounts[_account]; // For all users by default `isCollInit` will be `false` if(account.isCollInit == false) { // Two conditions: // 1) An account has some position previous to this up...
0.5.14
/** * @dev Enable/Disable collateral for a given token * @param _tokenIndex Index of the token * @param _enable `true` to enable the collateral, `false` to disable */
function setCollateral(uint8 _tokenIndex, bool _enable) public { address accountAddr = msg.sender; initCollateralFlag(accountAddr); Account storage account = accounts[accountAddr]; if(_enable) { account.collateralBitmap = account.collateralBitmap.setBit(_tokenIndex); ...
0.5.14
/** * Get deposit interest of an account for a specific token * @param _account account address * @param _token token address * @dev The deposit interest may not have been updated in AccountTokenLib, so we need to explicited calcuate it. */
function getDepositInterest(address _account, address _token) public view returns(uint256) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_account].tokenInfos[_token]; // If the account has never deposited the token, return 0. uint256 lastDepositBlock = tokenInfo.getLastDepositBlock...
0.5.14
/** * Update token info for deposit */
function deposit(address _accountAddr, address _token, uint256 _amount) public onlyAuthorized { initCollateralFlag(_accountAddr); AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; if(tokenInfo.getDepositPrincipal() == 0) { uint8 tokenIndex =...
0.5.14
/** * Get current borrow balance of a token * @param _token token address * @dev This is an estimation. Add a new checkpoint first, if you want to derive the exact balance. */
function getBorrowBalanceCurrent( address _token, address _accountAddr ) public view returns (uint256 borrowBalance) { AccountTokenLib.TokenInfo storage tokenInfo = accounts[_accountAddr].tokenInfos[_token]; Bank bank = globalConfig.bank(); uint256 accruedRate; ...
0.5.14
/** * Get borrowed balance of a token in the uint256 of Wei */
function getBorrowETH( address _accountAddr ) public view returns (uint256 borrowETH) { TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry(); Account memory account = accounts[_accountAddr]; uint128 hasBorrows = account.borrowBitmap; for(uint8 i = 0; i < 128; ...
0.5.14
/** * Check if the account is liquidatable * @param _borrower borrower's account * @return true if the account is liquidatable */
function isAccountLiquidatable(address _borrower) public returns (bool) { TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry(); Bank bank = globalConfig.bank(); // Add new rate check points for all the collateral tokens from borrower in order to // have accurate calculati...
0.5.14
/** * An account claim all mined FIN token. * @dev If the FIN mining index point doesn't exist, we have to calculate the FIN amount * accurately. So the user can withdraw all available FIN tokens. */
function claim(address _account) public onlyAuthorized returns(uint256){ TokenRegistry tokenRegistry = globalConfig.tokenInfoRegistry(); Bank bank = globalConfig.bank(); uint256 currentBlock = getBlockNumber(); Account memory account = accounts[_account]; uint128 deposit...
0.5.14
/** * Accumulate the amount FIN mined by depositing between _lastBlock and _currentBlock */
function calculateDepositFIN(uint256 _lastBlock, address _token, address _accountAddr, uint256 _currentBlock) internal { Bank bank = globalConfig.bank(); uint256 indexDifference = bank.depositFINRateIndex(_token, _currentBlock) .sub(bank.depositFINRateIndex(_token, _lastBlock)); ...
0.5.14
/** * The function is called in Bank.deposit(), Bank.withdraw() and Accounts.claim() functions. * The function should be called AFTER the newRateIndexCheckpoint function so that the account balances are * accurate, and BEFORE the account balance acutally updated due to deposit/withdraw activities. */
function updateDepositFINIndex(address _token) public onlyAuthorized{ uint currentBlock = getBlockNumber(); uint deltaBlock; // If it is the first deposit FIN rate checkpoint, set the deltaBlock value be 0 so that the first // point on depositFINRateIndex is zero. deltaBlock...
0.5.14
/** * Calculate a token deposite rate of current block * @param _token token address * @dev This is an looking forward estimation from last checkpoint and not the exactly rate that the user will pay or earn. */
function depositeRateIndexNow(address _token) public view returns(uint) { uint256 lcp = lastCheckpoint[_token]; // If this is the first checkpoint, set the index be 1. if(lcp == 0) return INT_UNIT; uint256 lastDepositeRateIndex = depositeRateIndex[_token][lcp]; ...
0.5.14
/** * Calculate a token borrow rate of current block * @param _token token address */
function borrowRateIndexNow(address _token) public view returns(uint) { uint256 lcp = lastCheckpoint[_token]; // If this is the first checkpoint, set the index be 1. if(lcp == 0) return INT_UNIT; uint256 lastBorrowRateIndex = borrowRateIndex[_token][lcp]; uint25...
0.5.14
/** * Withdraw a token from an address * @param _from address to be withdrawn from * @param _token token address * @param _amount amount to be withdrawn * @return The actually amount withdrawed, which will be the amount requested minus the commission fee. */
function withdraw(address _from, address _token, uint256 _amount) external onlyAuthorized returns(uint) { require(_amount != 0, "Amount is zero"); // Add a new checkpoint on the index curve. newRateIndexCheckpoint(_token); updateDepositFINIndex(_token); // Withdraw fro...
0.5.14
// Checks if funds of a given address are time-locked
function timeLocked(address _spender) public returns (bool) { if (releaseTimes[_spender] == 0) { return false; } // If time-lock is expired, delete it var _time = timeMode == TimeMode.Timestamp ? block.timestamp : block.number; if (releaseTimes[...
0.4.18
// return normalized rate
function normalizeRate(address src, address dest, uint256 rate) public view returns(uint) { RateAdjustment memory adj = rateAdjustment[src][dest]; if (adj.factor == 0) { uint srcDecimals = _getDecimals(src); uint destDecimals = _getDecimals(dest); if (srcDecimals != destDecimals) ...
0.5.15
// Deposit LP tokens to MasterChef for SUSHI/USDCow allocation.
function deposit(uint256 _pid, uint256 _amount) public payable { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSushiPerSha...
0.6.12
// Safe sushi/usdcow transfer/mint function, just in case if rounding error causes pool to not have enough SUSHIs/USDCows/USDCs.
function safeSushiTransfer(address _to, uint256 _amount) internal { if (_amount > 0) { tryRebase(); } uint256 cowBal = sushi.balanceOf(sushi.uniswapV2Pair()); uint256 usdcBal = sushi.usdc().balanceOf(sushi.uniswapV2Pair()); if (cowBal < usdcB...
0.6.12
/** * @notice External function to transfers a token to another address. * @param _to The address of the recipient, can be a user or contract. * @param _tokenId The ID of the token to transfer. */
function transfer(address _to, uint _tokenId) whenNotPaused external { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. require(_to != address(this)); // You can...
0.4.19
/** * @dev The external function that creates a new dungeon and stores it, only contract owners * can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT. * Will generate a Mint event, a NewDungeonFloor event, and a Transfer event. * @param _difficulty The difficulty of the new dungeon. ...
function createDungeon(uint _difficulty, uint _seedGenes, address _owner) eitherOwner external returns (uint) { // Ensure the total supply is within the fixed limit. require(totalSupply() < DUNGEON_CREATION_LIMIT); // UPDATE STORAGE // Create a new dungeon. dungeons.push(D...
0.4.19
/** * @dev The external function to add another dungeon floor by its ID, * only contract owners can alter dungeon state. * Will generate both a NewDungeonFloor event. */
function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) eitherOwner public { require(_id < totalSupply()); Dungeon storage dungeon = dungeons[_id]; dungeon.floorNumber++; dungeon.floorCreationTime = uint32(now); dungeon.rewards = uint128(_newRewards)...
0.4.19
/** * @dev An external function that creates a new hero and stores it, * only contract owners can create new token. * method doesn't do any checking and should only be called when the * input data is known to be valid. * @param _genes The gene of the new hero. * @param _owner The inital owner of this her...
function createHero(uint _genes, address _owner) external returns (uint) { // UPDATE STORAGE // Create a new hero. heroes.push(Hero(uint64(now), _genes)); // Token id is the index in the storage array. uint newTokenId = heroes.length - 1; // Emit the token mint ...
0.4.19
/** * @dev An internal function to calculate the power of player, or difficulty of a dungeon floor, * if the total heroes power is larger than the current dungeon floor difficulty, the heroes win the challenge. */
function _getGenesPower(uint _genes) internal pure returns (uint) { // Calculate total stats power. uint statsPower; for (uint i = 0; i < 4; i++) { statsPower += _genes % 32; _genes /= 32 ** 4; } // Calculate total stats power. uint equ...
0.4.19
/** * @dev The main public function to call when a player challenge a dungeon, * it determines whether if the player successfully challenged the current floor. * Will generate a DungeonChallenged event. */
function challenge(uint _dungeonId) external payable whenNotPaused canChallenge(_dungeonId) { // Get the dungeon details from the token contract. uint difficulty; uint seedGenes; (,,difficulty,,,,seedGenes,) = dungeonTokenContract.dungeons(_dungeonId); // Checks for paymen...
0.4.19
/** * Split the challenge function into multiple parts because of stack too deep error. */
function _getFirstHeroGenesAndInitialize(uint _dungeonId) private returns (uint heroGenes) { uint seedGenes; (,,,,,,seedGenes,) = dungeonTokenContract.dungeons(_dungeonId); // Get the first hero of the player. uint heroId; if (heroTokenContract.balanceOf(msg.sender) == 0...
0.4.19
/** * @dev The external function to get all the relevant information about a specific dungeon by its ID. * @param _id The ID of the dungeon. */
function getDungeonDetails(uint _id) external view returns (uint creationTime, uint status, uint difficulty, uint floorNumber, uint floorCreationTime, uint rewards, uint seedGenes, uint floorGenes) { require(_id < dungeonTokenContract.totalSupply()); (creationTime, status, difficulty, floorNumber, f...
0.4.19
// Check if the player won or refund if randomness proof failed
function checkIfWon(uint _currentQueryId, uint _randomNumber) private { bool win; if (_randomNumber != 101) { if (_randomNumber < 90) { win = true; sendPayout(_currentQueryId, ((queryIdMap[_currentQueryId].betValue*110)/100)); } else { win = false; sendOneWei(...
0.4.20
///@notice Adds the specified address to the list of administrators. ///@param account The address to add to the administrator list. ///@return Returns true if the operation was successful.
function addAdmin(address account) external onlyAdmin returns(bool) { require(account != address(0), "Invalid address."); require(!_admins[account], "This address is already an administrator."); require(account != super.owner(), "The owner cannot be added or removed to or from the administrator list.")...
0.5.9
///@notice Adds multiple addresses to the administrator list. ///@param accounts The account addresses to add to the administrator list. ///@return Returns true if the operation was successful.
function addManyAdmins(address[] calldata accounts) external onlyAdmin returns(bool) { for(uint8 i = 0; i < accounts.length; i++) { address account = accounts[i]; ///Zero address cannot be an admin. ///The owner is already an admin and cannot be assigned. ///The address cannot be an e...
0.5.9
///@notice Removes the specified address from the list of administrators. ///@param account The address to remove from the administrator list. ///@return Returns true if the operation was successful.
function removeAdmin(address account) external onlyAdmin returns(bool) { require(account != address(0), "Invalid address."); require(_admins[account], "This address isn't an administrator."); //The owner cannot be removed as admin. require(account != super.owner(), "The owner cannot be added or re...
0.5.9
///@notice Ensures that the requested ERC20 transfer amount is within the maximum allowed limit. ///@param amount The amount being requested to be transferred out of this contract. ///@return Returns true if the transfer request is valid and acceptable.
function checkIfValidTransfer(uint256 amount) public view returns(bool) { require(amount > 0, "Access is denied."); if(_maximumTransfer > 0) { require(amount <= _maximumTransfer, "Sorry but the amount you're transferring is too much."); } return true; }
0.5.9
///@notice Allows the sender to transfer tokens to the beneficiary. ///@param token The ERC20 token to transfer. ///@param destination The destination wallet address to send funds to. ///@param amount The amount of tokens to send to the specified address. ///@return Returns true if the operation was successful.
function transferTokens(address token, address destination, uint256 amount) external onlyAdmin whenNotPaused returns(bool) { require(checkIfValidTransfer(amount), "Access is denied."); ERC20 erc20 = ERC20(token); require ( erc20.balanceOf(address(this)) >= amount, "You don't ...
0.5.9
///@notice Allows the sender to transfer Ethers to the beneficiary. ///@param destination The destination wallet address to send funds to. ///@param amount The amount of Ether in wei to send to the specified address. ///@return Returns true if the operation was successful.
function transferEthers(address payable destination, uint256 amount) external onlyAdmin whenNotPaused returns(bool) { require(checkIfValidWeiTransfer(amount), "Access is denied."); require ( address(this).balance >= amount, "You don't have sufficient funds to transfer amount that la...
0.5.9
///@notice Allows the requester to perform ERC20 bulk transfer operation. ///@param token The ERC20 token to bulk transfer. ///@param destinations The destination wallet addresses to send funds to. ///@param amounts The respective amount of funds to send to the specified addresses. ///@return Returns true if the operat...
function bulkTransfer(address token, address[] calldata destinations, uint256[] calldata amounts) external onlyAdmin whenNotPaused returns(bool) { require(destinations.length == amounts.length, "Invalid operation."); //Saving gas by first determining if the sender actually has sufficient balance ...
0.5.9
/// #if_succeeds {:msg "The sell amount should be correct - case _amount = 0"} /// _amount == 0 ==> $result == 0; /// #if_succeeds {:msg "The sell amount should be correct - case _reserveWeight = MAX_WEIGHT"} /// _reserveWeight == 1000000 ==> $result == _removeSellTax(_reserveBalance.mul(_amount) / _supply);
function saleTargetAmount( uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount ) public view returns (uint256) { uint256 reserveValue = _curveAddress.saleTargetAmount( _supply, _reserveBalance, _reserveWeight, ...
0.6.12
/// #if_succeeds {:msg "The fundCost amount should be correct - case _amount = 0"} /// _amount == 0 ==> $result == 0; /// #if_succeeds {:msg "The fundCost amount should be correct - case _reserveRatio = MAX_WEIGHT"} /// _reserveRatio == 1000000 ==> $result == _addBuyTax(_curveAddress.fundCost(_supply, _reserveBalance, ...
function fundCost( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { uint256 reserveTokenCost = _curveAddress.fundCost( _supply, _reserveBalance, _reserveRatio, _am...
0.6.12
/// #if_succeeds {:msg "The liquidateReserveAmount should be correct - case _amount = 0"} /// _amount == 0 ==> $result == 0; /// #if_succeeds {:msg "The liquidateReserveAmount should be correct - case _amount = _supply"} /// _amount == _supply ==> $result == _removeSellTax(_reserveBalance); /// #if_succeeds {:msg "The ...
function liquidateReserveAmount( uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount ) public view returns (uint256) { uint256 liquidateValue = _curveAddress.liquidateReserveAmount( _supply, _reserveBalance, _res...
0.6.12
/// #if_succeeds {:msg "The tax should go to the owner"} /// let reserveBalance := old(_reserveAsset.balanceOf(address(this))) in /// let reserveTokenCost := old(fundCost(totalSupply(), reserveBalance, _fixedReserveRatio, amount)) in /// let taxDeducted := old(_removeBuyTax(reserveTokenCost)) in /// (msg.sender != owne...
function mint(address account, uint256 amount) public returns (bool) { uint256 reserveBalance = _reserveAsset.balanceOf(address(this)); uint256 reserveTokenCost = fundCost(totalSupply(), reserveBalance, _fixedReserveRatio, amount); uint256 taxDeducted = _removeBuyTax(reserveTokenCost); ...
0.6.12
/// #if_succeeds {:msg "The caller's BrincToken balance should be increase correct"} /// let reserveBalance := old(_reserveAsset.balanceOf(address(this))) in /// let tokensToMint := old(purchaseTargetAmount(totalSupply(), reserveBalance, _fixedReserveRatio, amount)) in /// msg.sender != owner() ==> this.balanceOf(accou...
function mintForSpecificReserveAmount(address account, uint256 amount) public returns (bool) { uint256 reserveBalance = _reserveAsset.balanceOf(address(this)); uint256 taxDeducted = _removeBuyTaxFromSpecificAmount(amount); uint256 tokensToMint = purchaseTargetAmount( totalSupply(), ...
0.6.12
/// #if_succeeds {:msg "The overridden burn should decrease caller's BrincToken balance"} /// this.balanceOf(_msgSender()) == old(this.balanceOf(_msgSender()) - amount); /// #if_succeeds {:msg "burn should add burn tax to the owner's balance"} /// let reserveBalance := old(_reserveAsset.balanceOf(address(this))) in ///...
function burn(uint256 amount) public override { uint256 reserveBalance = _reserveAsset.balanceOf(address(this)); uint256 reserveTokenNet = liquidateReserveAmount(totalSupply(), reserveBalance, _fixedReserveRatio, amount); _burn(_msgSender(), amount); uint256 taxAdded = _addSellTax(reser...
0.6.12
/** * @notice Returns a list of all existing token IDs converted to strings */
function getAllTokenIDs() public view returns (string[] memory result) { uint256 length = _allTokenIDs.length; result = new string[](length); for (uint256 i = 0; i < length; ++i) { result[i] = bytes32ToString(_allTokenIDs[i]); } }
0.6.12
/** * @notice Returns true if the token has an underlying token -- meaning the token is deposited into the bridge * @param tokenID String to check if it is a withdraw/underlying token */
function hasUnderlyingToken(string calldata tokenID) public view returns (bool) { bytes32 bytesTokenID = stringToBytes32(tokenID); Token[] memory _mcTokens = _allTokens[bytesTokenID]; for (uint256 i = 0; i < _mcTokens.length; ++i) { if (_mcTokens[i].hasUnderlying) { r...
0.6.12
/** * @notice Returns which token is the underlying token to withdraw * @param tokenID string token ID */
function getUnderlyingToken(string calldata tokenID) public view returns (Token memory token) { bytes32 bytesTokenID = stringToBytes32(tokenID); Token[] memory _mcTokens = _allTokens[bytesTokenID]; for (uint256 i = 0; i < _mcTokens.length; ++i) { if (_mcTokens[i].isUnderlying) { ...
0.6.12
/** * @notice Internal function which handles logic of setting token ID and dealing with mappings * @param tokenID bytes32 version of ID * @param chainID which chain to set the token config for * @param tokenToAdd Token object to set the mapping to */
function _setTokenConfig(bytes32 tokenID, uint256 chainID, Token memory tokenToAdd) internal returns(bool) { _tokens[tokenID][chainID] = tokenToAdd; if (!_isTokenIDExist(tokenID)) { _allTokenIDs.push(tokenID); } Token[] storage _mcTokens = _allTokens[tokenID]; for (...
0.6.12
/** * @notice Main write function of this contract - Handles creating the struct and passing it to the internal logic function * @param tokenID string ID to set the token config object form * @param chainID chain ID to use for the token config object * @param tokenAddress token address of the token on the given cha...
function setTokenConfig( string calldata tokenID, uint256 chainID, address tokenAddress, uint8 tokenDecimals, uint256 maxSwap, uint256 minSwap, uint256 swapFee, uint256 maxSwapFee, uint256 minSwapFee, bool hasUnderlying, bool isUnde...
0.6.12
/** * @notice Calculates bridge swap fee based on the destination chain's token transfer. * @dev This means the fee should be calculated based on the chain that the nodes emit a tx on * @param tokenAddress address of the destination token to query token config for * @param chainID destination chain ID to query the ...
function calculateSwapFee( address tokenAddress, uint256 chainID, uint256 amount ) external view returns (uint256) { Token memory token = getToken(tokenAddress, chainID); uint256 calculatedSwapFee = amount.mul(token.swapFee).div(FEE_DENOMINATOR); if (calculatedSwapFee...
0.6.12
/* @notice: mintMany is for minting many once the public sale is active. The parameter _mintAmount indicates the number of tokens the user wishes to mint. The following checks occur, it checks: - that the public mint is active - whether collection sold out - whether _mintAmount is within boundaries: 0 < x <= 1...
function mintMany(uint256 _mintAmount) external payable whenNotPaused { uint256 _totalSupply = totalSupply(); require( _isPublicMintActiveInternal(_totalSupply), "public sale not active" ); // require(!_isSoldOut(_totalSupply), "sold out"); require(_mintA...
0.8.4
/* @notice: mintColorsBatch is for colors holders to mint a batch of their specific tokens. The following checks occur, it checks: - that the public mint not be active - number of tokens in the array does not exceed boundaries: 0 < tokenIds.length <= 10 Then, it begins looping over the array of tokenIds sent...
function mintColorsBatch(uint256[] memory tokenIds) external whenNotPaused { uint256 _totalSupply = totalSupply(); require(!_isPublicMintActiveInternal(_totalSupply),"presale over"); require(tokenIds.length <= maxMintAmount,"exceeds max mint per tx"); require(tokenIds.length > 0,"Mint sh...
0.8.4
/* @notice: this is a helper function for the frontend that allows the user to view how many of their colors are available to be minted. */
function getUnmintedSpoonsByUser(address user) external view returns (uint256[] memory) { uint256[] memory tokenIds = new uint256[](4317); uint index = 0; for (uint i = 0; i < 4317; i++) { address tokenOwner = ERC721(THE_COLORS).ownerOf(i); ...
0.8.4
// Claim Your Vibe!
function claimVibe(uint256 tokenId) external payable { require(addressCanClaim[msg.sender], "You are not on the list"); require(balanceOf(msg.sender) < 1, "too many"); require(msg.value == mintPrice, "Valid price not sent"); _transferEnabled = true; addressCanClaim[msg.sender] = ...
0.8.3
// Creation of Vibes
function vibeFactory(uint256 num) external onlyOwner { uint256 newItemId = _tokenIds.current(); _transferEnabled = true; for (uint256 i; i < num; i++) { _tokenIds.increment(); newItemId = _tokenIds.current(); _safeMint(address(this), newItemId); } ...
0.8.3
/// @dev Converts all incoming ethereum to tokens for the caller
function buy() public payable returns (uint256) { if (contractIsLaunched){ //ETH sent during prelaunch needs to be processed if(stats[msg.sender].invested == 0 && referralBalance_[msg.sender] > 0){ reinvestFor(msg.sender); } return purchaseTo...
0.4.24
/// @dev Internal utility method for reinvesting
function reinvestFor(address _customerAddress) internal { // fetch dividends uint256 _dividends = totalDividends(_customerAddress, false); // retrieve ref. bonus later in the code payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus...
0.4.24
/// @dev Utility function for withdrawing earnings
function withdrawFor(address _customerAddress) internal { // setup data uint256 _dividends = totalDividends(_customerAddress, false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); ...
0.4.24
/// @dev Utility function for transfering tokens
function transferTokens(address _customerAddress, address _toAddress, uint256 _amountOfTokens) internal returns (bool){ // make sure we have the requested tokens require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if (to...
0.4.24
/// @dev Stats of any single address
function statsOf(address _customerAddress) public view returns (uint256[14]){ Stats memory s = stats[_customerAddress]; uint256[14] memory statArray = [s.invested, s.withdrawn, s.rewarded, s.contributed, s.transferredTokens, s.receivedTokens, s.xInvested, s.xRewarded, s.xContributed, s.xWithdrawn, s.x...
0.4.24
/* Can only be run once per day from the caller avoid bots Minimum of 100 P6 Minimum of 5 P4RTY + amount minted based on dividends processed in 24 hour period */
function processRewards() public teamPlayer launched { require(tokenBalanceLedger_[msg.sender] >= stakingRequirement, "Must meet staking requirement"); uint256 count = 0; address _customer; while (available() && count < maxProcessingCap) { //If this queue has alr...
0.4.24