comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/// @dev Internal function to check if a delegate has the permission to call a given contract function /// @param delegate the delegate to be checked /// @param to the target contract /// @param selector the function selector of the contract function to be called /// @return true|false
function _hasPermission( address delegate, address to, bytes4 selector ) internal view returns (bool) { bytes32[] memory roles = getRolesByDelegate(delegate); EnumerableSet.Bytes32Set storage funcRoles = funcToRoles[to][selector]; for (uint256 index = 0; index < roles...
0.7.6
/// @notice Associate a role with given contract funcs /// @dev only owners are allowed to call this function, the given role has /// to be predefined. On success, the role will be associated with the /// given contract function, `AssocContractFuncs` event will be fired. /// @param role the role to be associa...
function assocRoleWithContractFuncs( bytes32 role, address _contract, string[] calldata funcList ) external onlyOwner roleDefined(role) { require(funcList.length > 0, "empty funcList"); for (uint256 index = 0; index < funcList.length; index++) { bytes4 funcSelect...
0.7.6
/// @notice Dissociate a role from given contract funcs /// @dev only owners are allowed to call this function, the given role has /// to be predefined. On success, the role will be disassociated from /// the given contract function, `DissocContractFuncs` event will be /// fired. /// @param role the role...
function dissocRoleFromContractFuncs( bytes32 role, address _contract, string[] calldata funcList ) external onlyOwner roleDefined(role) { require(funcList.length > 0, "empty funcList"); for (uint256 index = 0; index < funcList.length; index++) { bytes4 funcSelec...
0.7.6
/** @dev everyone can buy @param qty - the quantity that a user wants to buy */
function publicBuy(uint256 id, uint256 qty) external payable nonReentrant { require(prices[id] != 0, "not live"); require(prices[id] * qty == msg.value, "exact amount needed"); require(qty <= 5, "max 5 at once"); require(totalSupply(id) + qty <= maxSupplies[id], "out of stock"); require(block.timestamp >= pub...
0.8.13
// Operation for multiplication
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; }
0.5.2
// ERC20 Transfer function
function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != address(0)); require(balanceOf[msg.sender] >= _value); require(balanceOf[_to].add(_value) >= balanceOf[_to]); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_t...
0.5.2
// ERC20 Transfer from wallet
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_from != address(0) && _to != address(0)); require(balanceOf[_from] >= _value); require(balanceOf[_to].add(_value) >= balanceOf[_to]); require(allowance[_from][msg.sender] >= _va...
0.5.2
// Approve to allow tranfer tokens
function approve(address _spender, uint256 _value) public returns (bool success) { require(_spender != address(0)); require(_value <= balanceOf[msg.sender]); require(_value == 0 || allowance[msg.sender][_spender] == 0); allowance[msg.sender][_spender] = _value; emit Approval...
0.5.2
/** * @dev Presale mint */
function presaleMint(bytes32[] calldata _merkleProof, uint16 _mintAmount) external payable onlyAllowValidCountAndActiveSale(_mintAmount) { bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require( MerkleProof.verify(_merkleProof, merkleRoot, leaf), ...
0.8.9
/** * @dev Returns list of token ids owned by address */
function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); uint256 k = 0; for (uint256 i = 1; i <= totalTokens; i++) { ...
0.8.9
/** * @dev Returns the URI to the tokens metadata */
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return ...
0.8.9
/** * @dev Burn tokens in mutiples of 5 */
function burn(uint256[] memory _tokenIds) external { require(burnEnabled, "Burn disabled"); require(_tokenIds.length % 5 == 0, "Multiples of 5"); for (uint256 i = 0; i < _tokenIds.length; i++) { require( _isApprovedOrOwner(_msgSender(), _tokenIds[i]), ...
0.8.9
/** * @dev Get information for a handler * @param handlerID Handler ID * @return (success or failure, handler address, handler name) */
function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory) { bool support; address tokenHandlerAddr; string memory tokenName; if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID);...
0.6.12
/** * @dev Register a handler * @param handlerID Handler ID and address * @param tokenHandlerAddr The handler address * @return result the setter call in contextSetter contract */
function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate, uint256 discountBase) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .handlerRegister.selector, handlerID, tokenHandlerAddr, flashFeeRate, disco...
0.6.12
/** * @dev Update the (SI) rewards for a user * @param userAddr The address of the user * @param callerID The handler ID * @return true (TODO: validate results) */
function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool) { ContractInfo memory handlerInfo; (handlerInfo.support, handlerInfo.addr) = dataStorageInstance.getTokenHandlerInfo(callerID); if (handlerInfo.support) { IProxy TokenHandler; TokenHandler = IProxy(...
0.6.12
/** * @dev Update interest of a user for a handler (internal) * @param userAddr The user address * @param callerID The handler ID * @param allFlag Flag for the full calculation mode (calculting for all handlers) * @return (uint256, uint256, uint256, uint256, uint256, uint256) */
function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .applyInterestHandlers.selector, userAddr, callerID, allFlag ); ...
0.6.12
/** * @dev Claim handler rewards for the user * @param handlerID The ID of claim reward handler * @param userAddr The user address * @return true (TODO: validate results) */
function claimHandlerReward(uint256 handlerID, address payable userAddr) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .claimHandlerReward.selector, handlerID, userAddr ); (bool result, bytes memory returnData) = handlerManagerAddr.delegateca...
0.6.12
/** * @dev Get the borrow and margin call limits of the user for all handlers * @param userAddr The address of the user * @return userTotalBorrowLimitAsset the sum of borrow limit for all handlers * @return userTotalMarginCallLimitAsset the sume of margin call limit for handlers */
function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256) { uint256 userTotalBorrowLimitAsset; uint256 userTotalMarginCallLimitAsset; for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++) { if (dataStorageInstance.getTokenHandlerSupport(handler...
0.6.12
/** * @dev Get the maximum allowed amount to borrow of the user from the given handler * @param userAddr The address of the user * @param callerID The target handler to borrow * @return extraCollateralAmount The maximum allowed amount to borrow from the handler. */
function getUserCollateralizableAmount(address payable userAddr, uint256 callerID) external view returns (uint256) { uint256 userTotalBorrowAsset; uint256 depositAssetBorrowLimitSum; uint256 depositHandlerAsset; uint256 borrowHandlerAsset; for (uint256 handlerID; handlerID < tokenHandlerLength; handler...
0.6.12
/** * @dev Partial liquidation for a user * @param delinquentBorrower The address of the liquidation target * @param liquidateAmount The amount to liquidate * @param liquidator The address of the liquidator (liquidation operator) * @param liquidateHandlerID The hander ID of the liquidating asset * @pa...
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) onlyLiquidationManager external returns (uint256, uint256, uint256) { address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(liqu...
0.6.12
/** * @dev Get the maximum liquidation reward by checking sufficient reward amount for the liquidator. * @param delinquentBorrower The address of the liquidation target * @param liquidateHandlerID The hander ID of the liquidating asset * @param liquidateAmount The amount to liquidate * @param reward...
function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256) { uint256 liquidatePrice = _getTokenHandlerPrice(liquidateHandlerID); uint256 rewardPrice = _getTokenHandlerPric...
0.6.12
/** * @dev Reward the liquidator * @param delinquentBorrower The address of the liquidation target * @param rewardAmount The amount of reward token * @param liquidator The address of the liquidator (liquidation operator) * @param handlerID The handler ID of the reward token for the liquidator * @retur...
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) onlyLiquidationManager external returns (uint256) { address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID); IProxy TokenHandler = IProxy(tokenHand...
0.6.12
/** * @dev Execute flashloan contract with delegatecall * @param handlerID The ID of the token handler to borrow. * @param receiverAddress The address of receive callback contract * @param amount The amount of borrow through flashloan * @param params The encode metadata of user * @return Whether or not succ...
function flashloan( uint256 handlerID, address receiverAddress, uint256 amount, bytes calldata params ) external returns (bool) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .flashloan.selector, handlerID, receiverAddress, amount, params )...
0.6.12
/** * @dev Withdraw accumulated flashloan fee with delegatecall * @param handlerID The ID of handler with accumulated flashloan fee * @return Whether or not succeed */
function withdrawFlashloanFee( uint256 handlerID ) external onlyOwner returns (bool) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .withdrawFlashloanFee.selector, handlerID ); (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData); ...
0.6.12
/** * @dev Get flashloan fee for flashloan amount before make product(BiFi-X) * @param handlerID The ID of handler with accumulated flashloan fee * @param amount The amount of flashloan amount * @param bifiAmount The amount of Bifi amount * @return The amount of fee for flashloan amount */
function getFeeFromArguments( uint256 handlerID, uint256 amount, uint256 bifiAmount ) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .getFeeFromArguments.selector, handlerID, amount, bifiAmount ); (bool result, ...
0.6.12
/** * @dev Get the deposit and borrow amount of the user for the handler (internal) * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount */
function _getHandlerAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256) { IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler ...
0.6.12
/** * @dev Calculates the fee and takes it, transfers the fee to the charity * address and the remains to this contract. * emits feeTaken() * Then, it checks if there is enough approved for the swap, if not it * approves it to the uniswap contract. Emits approvedForTrade if so. * @param user: The payer * @param ...
function takeFeeAndApprove(address user, IERC20 token, uint256 totalAmount) internal returns (uint256){ uint256 _feeTaken = (totalAmount / 10000) * _charityFee; token.transferFrom(user, address(this), totalAmount - _feeTaken); token.transferFrom(user, _charityAddress, _feeTaken); if (tok...
0.8.4
/** * @dev Get the deposit and borrow amount of the user with interest added * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount of the user with interest */
function _getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256) { uint256 price = _getTokenHandlerPrice(handlerID); IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); uint256 depositAmount; uint256 borrowAm...
0.6.12
/** * @dev Get the depositTotalCredit and borrowTotalCredit * @param userAddr The address of the user * @return depositTotalCredit The amount that users can borrow (i.e. deposit * borrowLimit) * @return borrowTotalCredit The sum of borrow amount for all handlers */
function _getUserTotalIntraCreditAsset(address payable userAddr) internal view returns (uint256, uint256) { uint256 depositTotalCredit; uint256 borrowTotalCredit; for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++) { if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { ...
0.6.12
/** * @dev Get the amount of token that the user can borrow more * @param userAddr The address of user * @param handlerID The handler ID * @return The amount of token that user can borrow more */
function _getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256) { uint256 depositCredit; uint256 borrowCredit; (depositCredit, borrowCredit) = _getUserTotalIntraCreditAsset(userAddr); if (depositCredit == 0) { return 0; } if (depositCredit > ...
0.6.12
/** * @dev The functions below are all the same as the Uniswap contract but * they call takeFeeAndApprove() or takeFeeETH() (See the functions above) * and deduct the fee from the amount that will be traded. */
function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external override returns (uint[] memory amounts){ uint256 newAmount = takeFeeAndApprove(_msgSender(), IERC20(path[0]), amountIn); return ...
0.8.4
/** * @dev Same as Uniswap */
function quote(uint amountA, uint reserveA, uint reserveB) external override pure returns (uint amountB){ require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = (amountA * reserveB) / reserveA; ...
0.8.4
/** * @dev To mint OAP Tokens * @param _receiver Reciever address * @param _amount Amount to mint * @param _mrs _mrs[0] - message hash _mrs[1] - r of signature _mrs[2] - s of signature * @param _v v of signature */
function mint(address _receiver, uint256 _amount,bytes32[3] memory _mrs, uint8 _v) public returns (bool) { require(_receiver != address(0), "Invalid address"); require(_amount >= 0, "Invalid amount"); require(hashConfirmation[_mrs[0]] != true, "Hash exists"); require(msg.sender == et...
0.5.16
/** * @dev To mint OAP Tokens * @param _receiver Reciever address * @param _amount Amount to mint */
function ownerMint(address _receiver, uint256 _amount) public onlyOwner returns (bool) { require(_receiver != address(0), "Invalid address"); require(_amount >= 0, "Invalid amount"); totalSupply = totalSupply.add(_amount); balances[_receiver] = balances[_receiver].add(_amount); ...
0.5.16
/** * @notice executes before each token transfer or mint * @param _from address * @param _to address * @param _amount value to transfer * @dev See {ERC20-_beforeTokenTransfer}. * @dev minted tokens must not cause the total supply to go over the cap. * @dev Reverts if the to address is equal to token address */
function _beforeTokenTransfer( address _from, address _to, uint256 _amount ) internal virtual override { super._beforeTokenTransfer(_from, _to, _amount); require( _to != address(this), "TCAP::transfer: can't transfer to TCAP contract" ); if (_from == address(0) && capEnabled)...
0.7.5
/** * @dev recovers any tokens stuck in Contract's balance * NOTE! if ownership is renounced then it will not work */
function recoverTokens(address tokenAddress, uint256 amountToRecover) external onlyOwner { IERC20Upgradeable token = IERC20Upgradeable(tokenAddress); uint256 balance = token.balanceOf(address(this)); require(balance >= amountToRecover, "Not Enough Tokens in contract to recover"); i...
0.8.10
/* @dev (Required) Set the per-second token issuance rate. @param what The tag of the value to change (ex. bytes32("cap")) @param data The value to update (ex. cap of 1000 tokens/yr == 1000*WAD/365 days) */
function file(bytes32 what, uint256 data) external auth lock { if (what == "cap") cap = data; // The maximum amount of tokens that can be streamed per-second per vest else revert("DssVest/file-unrecognized-param"); emit File(what, data); }
0.6.12
/* @dev Govanance adds a vesting contract @param _usr The recipient of the reward @param _tot The total amount of the vest @param _bgn The starting timestamp of the vest @param _tau The duration of the vest (in seconds) @param _eta The cliff duration in seconds (i.e. 1 years) @param _mgr An optional manag...
function create(address _usr, uint256 _tot, uint256 _bgn, uint256 _tau, uint256 _eta, address _mgr) external auth lock returns (uint256 id) { require(_usr != address(0), "DssVest/invalid-user"); require(_tot > 0, "DssVest/no-vest-total-amount"); ...
0.6.12
/* @dev Anyone (or only owner of a vesting contract if restricted) calls this to claim rewards @param _id The id of the vesting contract @param _maxAmt The maximum amount to vest */
function _vest(uint256 _id, uint256 _maxAmt) internal lock { Award memory _award = awards[_id]; require(_award.usr != address(0), "DssVest/invalid-award"); require(_award.res == 0 || _award.usr == msg.sender, "DssVest/only-user-can-claim"); uint256 amt = unpaid(block.timestamp, _awar...
0.6.12
/* @dev amount of tokens accrued, not accounting for tokens paid @param _time the timestamp to perform the calculation @param _bgn the start time of the contract @param _end the end time of the contract @param _amt the total amount of the contract */
function accrued(uint256 _time, uint48 _bgn, uint48 _fin, uint128 _tot) internal pure returns (uint256 amt) { if (_time < _bgn) { amt = 0; } else if (_time >= _fin) { amt = _tot; } else { amt = mul(_tot, sub(_time, _bgn)) / sub(_fin, _bgn); // 0 <= amt <...
0.6.12
/* @dev amount of tokens accrued, not accounting for tokens paid @param _time the timestamp to perform the calculation @param _bgn the start time of the contract @param _clf the timestamp of the cliff @param _end the end time of the contract @param _tot the total amount of the contract @param _rxd th...
function unpaid(uint256 _time, uint48 _bgn, uint48 _clf, uint48 _fin, uint128 _tot, uint128 _rxd) internal pure returns (uint256 amt) { amt = _time < _clf ? 0 : sub(accrued(_time, _bgn, _fin, _tot), _rxd); }
0.6.12
/* @dev Allows governance or the manager to end pre-maturely a vesting contract @param _id The id of the vesting contract @param _end A scheduled time to end the vest */
function _yank(uint256 _id, uint256 _end) internal lock { require(wards[msg.sender] == 1 || awards[_id].mgr == msg.sender, "DssVest/not-authorized"); Award memory _award = awards[_id]; require(_award.usr != address(0), "DssVest/invalid-award"); if (_end < block.timestamp) { ...
0.6.12
/** * @notice Allows the owner to execute custom transactions * @param target address * @param value uint256 * @param signature string * @param data bytes * @dev Only owner can call it */
function executeTransaction( address target, uint256 value, string memory signature, bytes memory data ) external payable onlyOwner returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(k...
0.7.5
/** * @dev Internal setter for the voting period. * * Emits a {VotingPeriodSet} event. */
function _setVotingPeriod(uint256 newVotingPeriod) internal virtual { // voting period must be at least one block long require(newVotingPeriod > 0, "GovernorSettings: voting period too low"); emit VotingPeriodSet(_votingPeriod, newVotingPeriod); _votingPeriod = newVotingPeriod; }
0.8.4
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. * @return bool success */
function transfer(address _to, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances...
0.4.24
/** * @dev Return total stake amount of `account` */
function getStakeAmount( address account ) external view returns (uint256) { uint256[] memory stakeIds = stakerIds[account]; uint256 totalStakeAmount; for (uint256 i = 0; i < stakeIds.length; i++) { totalStakeAmount += stakes[stakeIds...
0.8.4
/** * @dev Return total stake amount that have been in the pool from `fromDate` * Requirements: * * - `fromDate` must be past date */
function getEligibleStakeAmount( uint256 fromDate ) public override view returns (uint256) { require(fromDate <= block.timestamp, "StakeToken#getEligibleStakeAmount: NO_PAST_DATE"); uint256 totalSAmount; for (uint256 i = 1; i <= tokenId...
0.8.4
/** * @dev Returns StakeToken multiplier. * * 0 < `tokenId` <300: 120. * 300 <= `tokenId` <4000: 110. * 4000 <= `tokenId`: 100. */
function _getMultiplier() private view returns (uint256) { if (tokenIds < 300) { return 120; } else if (300 <= tokenIds && tokenIds < 4000) { return 110; } else { return 100; } }
0.8.4
/** * @dev Mint a new StakeToken. * Requirements: * * - `account` must not be zero address, check ERC721 {_mint} * - `amount` must not be zero * @param account address of recipient. * @param amount mint amount. * @param depositedAt timestamp when stake was deposited. */
function _mint( address account, uint256 amount, uint256 depositedAt ) internal virtual returns (uint256) { require(amount > 0, "StakeToken#_mint: INVALID_AMOUNT"); tokenIds++; uint256 multiplier = _getMultiplier(); supe...
0.8.4
/** * @dev Burn stakeToken. * Requirements: * * - `stakeId` must exist in stake pool * @param stakeId id of buring token. */
function _burn( uint256 stakeId ) internal override { require(_exists(stakeId), "StakeToken#_burn: STAKE_NOT_FOUND"); address stakeOwner = ownerOf(stakeId); super._burn(stakeId); delete stakes[stakeId]; uint256[] storage stakeIds = staker...
0.8.4
/** * @dev Decrease stake amount. * If stake amount leads to be zero, the stake is burned. * Requirements: * * - `stakeId` must exist in stake pool * @param stakeId id of buring token. * @param amount to withdraw. */
function _decreaseStakeAmount( uint256 stakeId, uint256 amount ) internal virtual { require(_exists(stakeId), "StakeToken#_decreaseStakeAmount: STAKE_NOT_FOUND"); require(amount <= stakes[stakeId].amount, "StakeToken#_decreaseStakeAmount: INSUFFICIENT_STAK...
0.8.4
/** * @dev Sweep funds * Accessible by operators */
function sweep( address token_, address to, uint256 amount ) public onlyOperator { IERC20 token = IERC20(token_); // balance check is being done in ERC20 token.transfer(to, amount); emit Swept(msg.sender, token_, to, amount); ...
0.8.4
/** * @dev Updates set of the globally enabled features (`features`), * taking into account sender's permissions.= * @dev Requires transaction sender to have `ROLE_FEATURE_MANAGER` permission. * @param mask bitmask representing a set of features to enable/disable */
function updateFeatures(uint256 mask) public { // caller must have a permission to update global features require(isSenderInRole(ROLE_FEATURE_MANAGER)); // evaluate new features set and assign them features = evaluateBy(msg.sender, features, mask); // fire an event emit FeaturesUpdated...
0.4.23
/** * @dev Updates set of permissions (role) for a given operator, * taking into account sender's permissions. * @dev Setting role to zero is equivalent to removing an operator. * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to * copying senders permissions (role) to an operator. * @d...
function updateRole(address operator, uint256 role) public { // caller must have a permission to update user roles require(isSenderInRole(ROLE_ROLE_MANAGER)); // evaluate the role and reassign it userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role); // fire an event ...
0.4.23
/** * @dev Based on the actual role provided (set of permissions), operator address, * and role required (set of permissions), calculate the resulting * set of permissions (role). * @dev If operator is super admin and has full permissions (FULL_PRIVILEGES_MASK), * the function will always retur...
function evaluateBy(address operator, uint256 actual, uint256 required) public constant returns(uint256) { // read operator's permissions uint256 p = userRoles[operator]; // taking into account operator's permissions, // 1) enable permissions requested on the `current` actual |= p & required;...
0.4.23
// Returns TUTs rate per 1 ETH depending on current time
function getRateByTime() public constant returns (uint256) { uint256 timeNow = now; if (timeNow > (startTime + 94 * unitTimeSecs)) { return 1500; } else if (timeNow > (startTime + 87 * unitTimeSecs)) { return 1575; // + 5% } else if (timeNow > (startTime + 8...
0.4.15
/** * @dev Mints (creates) some tokens to address specified * @dev The value passed is treated as number of units (see `ONE_UNIT`) * to achieve natural impression on token quantity * @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission * @param _to an address to mint tokens to * @param _value a...
function mint(address _to, uint256 _value) public { // calculate native value, taking into account `decimals` uint256 value = _value * ONE_UNIT; // arithmetic overflow and non-zero value check require(value > _value); // delegate call to native `mintNative` mintNative(_to, value); }
0.4.23
/** * @dev Mints (creates) some tokens to address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission * @param _to an address to mint tokens to * @param _value an amount of tokens to ...
function mintNative(address _to, uint256 _value) public { // check if caller has sufficient permissions to mint tokens require(isSenderInRole(ROLE_TOKEN_CREATOR)); // non-zero recipient address check require(_to != address(0)); // non-zero _value and arithmetic overflow check on the total s...
0.4.23
/** * @dev Burns (destroys) some tokens from the address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * @dev Requires sender to have `ROLE_TOKEN_DESTROYER` permission * @param _from an address to burn some tokens from * @param _value an am...
function burnNative(address _from, uint256 _value) public { // check if caller has sufficient permissions to burn tokens require(isSenderInRole(ROLE_TOKEN_DESTROYER)); // non-zero burn value check require(_value != 0); // verify `_from` address has enough tokens to destroy // (basicall...
0.4.23
/* User can allow another smart contract to spend some shares in his behalf * (this function should be called by user itself) * @param _spender another contract's address * @param _value number of tokens * @param _extraData Data that can be sent from user to another contract to be processed * bytes - dyn...
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { approve(_spender, _value); // 'spender' is another contract that implements code as prescribed in 'allowanceRecipient' above allowanceRecipient spender = allowanceRecipient(_...
0.5.6
/* https://github.com/ethereum/EIPs/issues/677 * transfer tokens with additional info to another smart contract, and calls its correspondent function * @param address _to - another smart contract address * @param uint256 _value - number of tokens * @param bytes _extraData - data to send to another contract * ...
function transferAndCall(address _to, uint256 _value, bytes memory _extraData) public returns (bool success){ transferFrom(msg.sender, _to, _value); tokenRecipient receiver = tokenRecipient(_to); if (receiver.tokenFallback(msg.sender, _value, _extraData)) { emit DataSentToA...
0.5.6
/* set time for start and time for end pre-ICO * time is integer representing block timestamp * in UNIX Time, * see: https://www.epochconverter.com * @param uint256 startTime - time to start * @param uint256 endTime - time to end * should be taken into account that * "block.timestamp" can be influenced by...
function startSale(uint256 _startUnixTime, uint256 _endUnixTime) public onlyBy(owner) returns (bool success){ require(balanceOf[address(this)] > 0); require(salesCounter < maxSalesAllowed); // time for sale can be set only if: // this is first sale (saleStartUnixTime == 0 && sale...
0.5.6
/* After sale contract owner * (can be another contract or account) * can withdraw all collected Ether */
function withdrawAllToOwner() public onlyBy(owner) returns (bool) { // only after sale is finished: require(saleIsFinished()); uint256 sumInWei = address(this).balance; if ( // makes withdrawal and returns true or false !msg.sender.send(address(this).balance...
0.5.6
/** * @dev Transfers the tokens from a Taraxa owned wallet to the participant. * * Emits a {TokensSent} event. */
function multisendToken( address token, address[] calldata _recipients, uint256[] calldata _amounts ) public { require(_recipients.length <= 200, 'Multisend: max transfers per tx exceeded'); require( _recipients.length == _amounts.length, 'Mult...
0.7.6
//200m coins total //reward begins at 500 and is cut in half every reward era (as tokens are mined)
function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 250 per block //every reward era, the reward amount halves. return (500 * 10**uint(decimals) ).div( 2**rewardEra ) ; }
0.4.18
/** * @dev Getting Deex Token prize of _lastParticipant * @param _lastParticipant Address of _lastParticipant */
function calculateLastDeexPrize(address _lastParticipant) public view returns(uint) { uint payout = 0; uint totalSupply = (lastTotalDeexSupplyOfDragons.add(lastTotalDeexSupplyOfHamsters)).mul(80).div(100); if (depositDragons[currentRound - 1][_lastParticipant] > 0) { payout =...
0.5.6
// To transfer tokens by proxy
function transferFrom(address _from, address _to, uint256 _amount) public canEnter isHolder(_to) returns (bool) { require(_amount <= holders[_from].allowances[msg.sender]); Holder from = holders[_from]; Holder to = holders[_to]; fr...
0.4.10
// Processes token transfers and subsequent change in voting power
function xfer(Holder storage _from, Holder storage _to, uint _amount) internal returns (bool) { // Ensure dividends are up to date at current balances updateDividendsFor(_from); updateDividendsFor(_to); // Remove existing votes revoke(_from); ...
0.4.10
// // Security Functions // // Cause the contract to Panic. This will block most state changing // functions for a set delay.
function PANIC() public isHolder(msg.sender) returns (bool) { // A blocking holder requires at least 10% of tokens require(holders[msg.sender].tokenBalance >= totalSupply / 10); panicked = true; timeToCalm = uint40(now + PANICPERIOD); ...
0.4.10
// Queues a pending transaction
function timeLockSend(address _from, address _to, uint _value, bytes _data) internal returns (uint8) { // Check that queue is not full require(ptxHead + 1 != ptxTail); TX memory tx = TX({ from: _from, to: _to, value: _value, ...
0.4.10
// Execute the first TX in the pendingTxs queue. Values will // revert if the transaction is blocked or fails.
function sendPending() public preventReentry isHolder(msg.sender) returns (bool) { if (ptxTail == ptxHead) return false; // TX queue is empty TX memory tx = pendingTxs[ptxTail]; if(now < tx.timeLock) return false; // Have m...
0.4.10
// To block a pending transaction
function blockPendingTx(uint _txIdx) public returns (bool) { // Only prevent reentry not entry during panic require(!__reMutex); // A blocking holder requires at least 10% of tokens or is trustee or // is from own account require(holders[msg....
0.4.10
// admin methods
function withdrawByAdmin(address _investor, uint256 _investednum, address _target) onlyAdmin public { require(_investednum > 0 && investedAmount[_investor] >= _investednum); require(!investorVault[_investor][_investednum].withdrawn); require(token.balanceOf(address(this)) >= investorVault[_in...
0.4.24
// For the trustee to commit an amount from the fund balance as a dividend
function payDividends(uint _value) public canEnter onlyTrustee returns (bool) { require(_value <= fundBalance()); // Calculates dividend as percent of current `totalSupply` in 10e17 // fixed point math dividendPoints += 10**18 * _value / total...
0.4.10
// Creates holder accounts. Called by addHolder() and issue()
function join(address _addr) internal returns (bool) { if(0 != holders[_addr].id) return true; require(_addr != address(this)); uint8 id; // Search for the first available slot. while (holderIndex[++id] != 0) {} /...
0.4.10
// Enable trading and assign values of arguments to variables
function enableTrading(uint256 blocks) external onlyOwner { require(!tradingEnabled, "Trading already enabled"); require(blocks <= 5, "Must be less than 5 blocks"); tradingEnabled = true; swapEnabled = true; tradingEnabledBlock = block.number; justicePeriod = blocks...
0.8.11
// Lock wallet from transferring out for given time
function lockTokens(address[] memory wallets, uint256[] memory numDays) external onlyOwner { require(wallets.length == numDays.length, "Arrays must be the same length"); require(wallets.length < 200, "Can only lock 200 wallets per txn due to gas limits"); for (uint i = 0; i < wallets.length; ...
0.8.11
// Update token threshold for when the contract sells for liquidity, marketing and development
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner { require(newAmount >= (totalSupply() * 1 / 100000) / 10**18, "Threshold lower than 0.001% total supply"); require(newAmount <= (totalSupply() * 1 / 1000) / 10**18, "Threshold higher than 0.1% total supply"); swapTokensAtAm...
0.8.11
// Transfer given number of tokens to given address
function airdropToWallets(address[] memory wallets, uint256[] memory amountsInTokens) external onlyOwner { require(wallets.length == amountsInTokens.length, "Arrays must be the same length"); require(wallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); for (uint25...
0.8.11
// Update fees on buys
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevelopmentFee = _developmentFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevelopmentF...
0.8.11
// Update fees on sells
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevelopmentFee = _developmentFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDeve...
0.8.11
// Contract sells
function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contract...
0.8.11
// Withdraw unnecessary tokens
function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); ...
0.8.11
// For the trustee to issue an offer of new tokens to a holder
function issue(address _addr, uint _amount) public canEnter onlyTrustee returns (bool) { // prevent overflows in total supply assert(totalSupply + _amount < MAXTOKENS); join(_addr); Holder holder = holders[_addr]; holder.off...
0.4.10
// To close a holder account
function vacate(address _addr) public canEnter isHolder(msg.sender) isHolder(_addr) returns (bool) { Holder holder = holders[_addr]; // Ensure holder account is empty, is not the trustee and there are no // pending transactions or dividends ...
0.4.10
// performs presale burn
function burn (uint256 _burnAmount, bool _presaleBurn) public onlyOwner returns (bool success) { if (_presaleBurn) { require(_presaleBurnTotal.add(_burnAmount) <= _maximumPresaleBurnAmount); _presaleBurnTotal = _presaleBurnTotal.add(_burnAmount); _transfer(_owner, address(0), _burnAmount); ...
0.6.0
/** * @notice Allows an user to create an unique Vault * @dev Only one vault per address can be created */
function createVault() external virtual whenNotPaused { require( userToVault[msg.sender] == 0, "VaultHandler::createVault: vault already created" ); uint256 id = counter.current(); userToVault[msg.sender] = id; Vault memory vault = Vault(id, 0, 0, msg.sender); vaults[id] = vault; ...
0.7.5
/** * @notice Allows users to add collateral to their vaults * @param _amount of collateral to be added * @dev _amount should be higher than 0 * @dev ERC20 token must be approved first */
function addCollateral(uint256 _amount) external virtual nonReentrant vaultExists whenNotPaused notZero(_amount) { require( collateralContract.transferFrom(msg.sender, address(this), _amount), "VaultHandler::addCollateral: ERC20 transfer did not succeed" ); Vault stora...
0.7.5
/** * @notice Allows users to remove collateral currently not being used to generate TCAP tokens from their vaults * @param _amount of collateral to remove * @dev reverts if the resulting ratio is less than the minimun ratio * @dev _amount should be higher than 0 * @dev transfers the collateral back to the user *...
function removeCollateral(uint256 _amount) external virtual nonReentrant vaultExists whenNotPaused notZero(_amount) { Vault storage vault = vaults[userToVault[msg.sender]]; uint256 currentRatio = getVaultRatio(vault.Id); require( vault.Collateral >= _amount, "VaultHand...
0.7.5
/** * @notice Uses collateral to generate debt on TCAP Tokens which are minted and assigend to caller * @param _amount of tokens to mint * @dev _amount should be higher than 0 * @dev requires to have a vault ratio above the minimum ratio * @dev if reward handler is set stake to earn rewards */
function mint(uint256 _amount) external virtual nonReentrant vaultExists whenNotPaused notZero(_amount) { Vault storage vault = vaults[userToVault[msg.sender]]; uint256 collateral = requiredCollateral(_amount); require( vault.Collateral >= collateral, "VaultHandler::mi...
0.7.5
/** * @notice Pays the debt of TCAP tokens resulting them on burn, this releases collateral up to minimun vault ratio * @param _amount of tokens to burn * @dev _amount should be higher than 0 * @dev A fee of exactly burnFee must be sent as value on ETH * @dev The fee goes to the treasury contract * @dev if reward...
function burn(uint256 _amount) external payable virtual nonReentrant vaultExists whenNotPaused notZero(_amount) { uint256 fee = getFee(_amount); require( msg.value >= fee, "VaultHandler::burn: burn fee less than required" ); Vault memory vault = vaults[userToVa...
0.7.5
/** * @notice Allow users to burn TCAP tokens to liquidate vaults with vault collateral ratio under the minium ratio, the liquidator receives the staked collateral of the liquidated vault at a premium * @param _vaultId to liquidate * @param _maxTCAP max amount of TCAP the liquidator is willing to pay to liquidate va...
function liquidateVault(uint256 _vaultId, uint256 _maxTCAP) external payable nonReentrant whenNotPaused { Vault storage vault = vaults[_vaultId]; require(vault.Id != 0, "VaultHandler::liquidateVault: no vault created"); uint256 vaultRatio = getVaultRatio(vault.Id); require( vaul...
0.7.5
/** * @notice Returns the minimal required TCAP to liquidate a Vault * @param _vaultId of the vault to liquidate * @return amount required of the TCAP Token * @dev LT = ((((D * r) / 100) - cTcap) * 100) / (r - (p + 100)) * cTcap = ((C * cp) / P) * LT = Required TCAP * D = Vault Debt * C = Required Collateral *...
function requiredLiquidationTCAP(uint256 _vaultId) public view virtual returns (uint256 amount) { Vault memory vault = vaults[_vaultId]; uint256 tcapPrice = TCAPPrice(); uint256 collateralPrice = getOraclePrice(collateralPriceOracle); uint256 collateralTcap = (vault.Collateral.mu...
0.7.5
/** * @notice Returns the Collateral Ratio of the Vault * @param _vaultId id of vault * @return currentRatio * @dev vr = (cp * (C * 100)) / D * P * vr = Vault Ratio * C = Vault Collateral * cp = Collateral Price * D = Vault Debt * P = TCAP Token Price */
function getVaultRatio(uint256 _vaultId) public view virtual returns (uint256 currentRatio) { Vault memory vault = vaults[_vaultId]; if (vault.Id == 0 || vault.Debt == 0) { currentRatio = 0; } else { uint256 collateralPrice = getOraclePrice(collateralPriceOracle); current...
0.7.5
/** * @dev Get the raw trait indices for a given tokenId * @param tokenId of a MEV Army NFT * @return An array of integers that are indices for the trait arrays stored in this contract * example: [ binary index, legion index, light index, mouth index, helmet index, eyes index, faces index ] **/
function getTraitsIndices(uint256 tokenId) public view returns (EditionIndices memory){ require(tokenId > 0 && tokenId < 10000, "nonexistent tokenId"); // calculate the slot for a given token id uint256 slotForTokenId = (tokenId - 1) >> 2; // calculate the index within a slot for a giv...
0.8.2
/** * @dev Unpack an edition. Each edition contains 7 traits packed into an unsigned integer. * Each packed trait is an 8-bit unsigned integer. **/
function _unPackEdition(uint256 edition) internal pure returns (EditionIndices memory){ return EditionIndices( uint8((edition) & uint256(type(uint8).max)), uint8((edition >> 8) & uint256(type(uint8).max)), uint8((edition >> 16) & uint256(type(uint8).max)), uint8((...
0.8.2
/// @notice Add the hypervisor position /// @param pos Address of the hypervisor /// @param version Type of hypervisor
function addPosition(address pos, uint8 version) external onlyOwner { Position storage p = positions[pos]; require(p.version == 0, 'already added'); require(version > 0, 'version < 1'); p.version = version; IHypervisor(pos).token0().safeApprove(pos, MAX_UINT); IHypervisor(pos).token1().safeAppro...
0.7.6
/// @notice Get the amount of token to deposit for the given amount of pair token /// @param pos Hypervisor Address /// @param token Address of token to deposit /// @param _deposit Amount of token to deposit /// @return amountStart Minimum amounts of the pair token to deposit /// @return amountEnd Maximum amounts of th...
function getDepositAmount( address pos, address token, uint256 _deposit ) public view returns (uint256 amountStart, uint256 amountEnd) { require(token == address(IHypervisor(pos).token0()) || token == address(IHypervisor(pos).token1()), "token mistmatch"); require(_deposit > 0, "deposits can't be ...
0.7.6
/// @notice Check if the price change overflows or not based on given twap and threshold in the hypervisor /// @param pos Hypervisor Address /// @param _twapInterval Time intervals /// @param _priceThreshold Price Threshold /// @return price Current price
function checkPriceChange( address pos, uint32 _twapInterval, uint256 _priceThreshold ) public view returns (uint256 price) { uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(IHypervisor(pos).currentTick()); price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), 1e18, 2**(96 * 2)); ...
0.7.6
/// @notice Get the sqrt price before the given interval /// @param pos Hypervisor Address /// @param _twapInterval Time intervals /// @return sqrtPriceX96 Sqrt price before interval
function getSqrtTwapX96(address pos, uint32 _twapInterval) public view returns (uint160 sqrtPriceX96) { if (_twapInterval == 0) { /// return the current price if _twapInterval == 0 (sqrtPriceX96, , , , , , ) = IHypervisor(pos).pool().slot0(); } else { uint32[] memory secondsAgos = new uin...
0.7.6