comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/// @notice Get total locked tokens of a specific recipient. /// @dev Reverts if any of the recipients is terminated. /// @param recipient A non-terminated recipient address. /// @return Total locked tokens of a specific recipient.
function totalLockedOf(address recipient) public view recipientIsNotTerminated(recipient) returns (uint256) { // get recipient Recipient memory _recipient = recipients[recipient]; // We know that vestingPerSec is constant for a recipient for entirety of their vesting period // locked = ...
0.7.6
/// @notice Allows owner to transfer the ERC20 assets (other than token) to the "to" address in case of any emergency /// @dev It is assumed that the "to" address is NOT malicious /// Only owner of the vesting escrow can invoke this function. /// Reverts if the asset address is a zero address or the token add...
function inCaseAssetGetStuck(address asset, address to) external onlyOwner returns (uint256 rescued) { // asset address should NOT be a 0 address require(asset != address(0), "inCaseAssetGetStuck: asset cannot be 0 address"); // asset address should NOT be the token address require(asset...
0.7.6
/// @notice Transfers the dust to the SAFE_ADDRESS. /// @dev It is assumed that the SAFE_ADDRESS is NOT malicious. /// Only owner of the vesting escrow can invoke this function. /// @return Amount of dust to the SAFE_ADDRESS.
function transferDust() external onlyOwner returns (uint256) { // precaution for reentrancy attack if (dust > 0) { uint256 _dust = dust; dust = 0; IERC20(token).safeTransfer(SAFE_ADDRESS, _dust); return _dust; } return 0; }
0.7.6
/// @notice Transfers the locked (non-vested) tokens of the passed recipients to the SAFE_ADDRESS /// @dev It is assumed that the SAFE_ADDRESS is NOT malicious /// Only owner of the vesting escrow can invoke this function. /// Reverts if any of the recipients is terminated. /// Can only be invoked if the...
function seizeLockedTokens(address[] calldata _recipients) external onlyOwner returns (uint256 totalSeized) { // only seize if escrow is terminated require(ESCROW_TERMINATED, "seizeLockedTokens: escrow not terminated"); // get the total tokens to be seized for (uint256 i = 0; i < _recipi...
0.7.6
// Controller only function for creating additional rewards from dust
function withdraw(IERC20 _asset) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); require(crv != address(_asset), "crv"); require(ydai != address(_asset), "ydai"); require(dai != address(_asset),...
0.5.17
// --- Primary Functions ---
function sellGem(address usr, uint256 gemAmt) external { uint256 gemAmt18 = mul(gemAmt, to18ConversionFactor); uint256 fee = mul(gemAmt18, tin) / WAD; uint256 daiAmt = sub(gemAmt18, fee); gemJoin.join(address(this), gemAmt, msg.sender); vat.frob(ilk, address(this), address(t...
0.6.7
/// start exceptions
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external { if (isFunding) revert(); if (_fundingStartBlock >= _fundingStopBlock) revert(); if (block.number >= _fundingStartBlock) revert(); fundingStartBlock = _fundingStartBlock; fundin...
0.4.26
// migrate to Contract address
function migrate() external { if(isFunding) revert(); if(newContractAddr == address(0x0)) revert(); uint256 tokens = balances[msg.sender]; if (tokens == 0) revert(); balances[msg.sender] = 0; tokenMigrated = safeAdd(tokenMigrated, tokens); IMigrationC...
0.4.26
// let Contract token allocate to the address
function allocateToken (address _addr, uint256 _eth) isOwner external { if (_eth == 0) revert(); if (_addr == address(0x0)) revert(); uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate); if (tokens + tokenRaised > currentSupply) revert(); tokenRaised = saf...
0.4.26
// buy token
function () payable public{ if (!isFunding) revert(); if (msg.value == 0) revert(); if (block.number < fundingStartBlock) revert(); if (block.number > fundingStopBlock) revert(); uint256 tokens = safeMult(msg.value, tokenExchangeRate); if (tokens + tokenRaised >...
0.4.26
// Single Address - Multiple Tokens _mintBatch
function mintSingleToMultipleBatch(address to, uint256[] memory ids, bytes memory data) public onlyOwner { uint256 _length= ids.length; uint256[] memory amounts = new uint256[](_length); for (uint256 i = 0; i < ids.length; i++) { require(!tokenCheck[ids[i]], "Token with this ID a...
0.8.7
// Single Address - Multiple Tokens
function mintSingleToMultiple(address account, uint256[] memory ids) public onlyOwner { for (uint256 i = 0; i < ids.length; i++) { require(!tokenCheck[ids[i]], "Token with this ID already exists"); _mint(account, ids[i], 1, ""); tokenCheck[ids[i]] = true; } ...
0.8.7
// Main function. Allows user (msg.sender) to withdraw funds from DAO. // _amount - amount of DAO tokens to exhange // _token - token of DAO to exchange // _targetToken - token to receive in exchange // _optimisticPrice - an optimistic price of DAO token. Used to check if DAO Agent // have enough fun...
function withdraw( uint256 _amount, address _token, address _targetToken, uint256 _optimisticPrice, uint256 _optimisticPriceTimestamp, bytes memory _signature ) public withValidOracleData( _token, _optimisticPrice, _...
0.8.4
// Validates oracle price signature //
function recover( uint256 _price, uint256 _timestamp, address _token, bytes memory _signature ) public pure returns (address) { bytes32 dataHash = keccak256( abi.encodePacked(_price, _timestamp, _token) ); bytes32 signedMessageHash = keccak256( ...
0.8.4
// Computes an amount of _targetToken that user will get in exchange for // a given amount for DAO tokens // _amount - amount of DAO tokens // _price - price in 6 decimals per 10e18 of DAO token // _targetToken - target token to receive //
function computeExchange( uint256 _amount, uint256 _price, address _targetToken ) public view returns (uint256) { IERC20Metadata targetToken = IERC20Metadata(_targetToken); uint256 result = _amount * _price / 10 ** (24 - targetToken.decimals()); require(result > 0, "I...
0.8.4
// Call function processFee() at the end of main function for correct gas usage calculation. // txGas - is gasleft() on start of calling contract. Put `uint256 txGas = gasleft();` as a first command in function // feeAmount - fee amount that user paid // licenseeVault - address that licensee received on registration an...
function processFee(uint256 txGas, uint256 feeAmount, address licenseeVault, address user) internal { if (address(reimbursementContract) == address(0)) { payable(user).transfer(feeAmount); // return fee to sender if no reimbursement contract return; } uint256 licen...
0.8.7
/** * @dev Multiplies two unsigned integers, returns 2^256 - 1 on overflow. */
function mulCap(uint _a, uint _b) internal pure returns (uint) { // Gas optimization: this is cheaper than requiring '_a' not being zero, but the // benefit is lost if '_b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) ...
0.5.17
/** * @dev call by the owner, set/unset bulk _addresses into the blacklist */
function setBlacklistBulk(address[] calldata _addresses, bool _bool) public onlyOwner { require(_addresses.length != 0, "Blacklisted: the length of addresses is zero"); for (uint256 i = 0; i < _addresses.length; i++) { setBlacklist(_addresses[i], _bool); } }
0.7.1
// for compatibility for older versions
function changeMPCOwner(address newVault) external returns (bool) { // require vault has access now // require(hasRole(OPERATOR_ROLE, _msgSender()) || _msgSender() == vault ,"DOES NOT HAVE RIGHT TO CHANGE VAULT"); vault = newVault; // give vault minting burning...
0.8.7
/// @dev Sets `value` as allowance of `spender` account over `owner` account's AnyswapV3ERC20 token, given `owner` account's signed approval. /// Emits {Approval} event. /// Requirements: /// - `deadline` must be timestamp in future. /// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account ov...
function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit"); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, ...
0.8.7
// function to change the swapAndLiquify contract //
function setSwapAndLiquifyContractAddress(address newAddress) public onlyOperator { address oldAddress = swap_and_liquify_contract; swap_and_liquify_contract = newAddress; // Approve the new router to spend contract's tokens. _approve(address(this), newAddress, MAX_INT); ...
0.8.7
// Retrieves rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity for provided tAmount.
function _getValues(uint256 tAmount, bool takeFee) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { if(!takeFee) { uint256 rTokens = tAmount * _getRate(); return (rTokens, rTokens, 0, tAmount, 0, 0, 0); } (uint256 tTransferAmount...
0.8.7
/** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */
function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (pause...
0.5.16
// Transfers `amountIn` token to mint `amountIn - fees` of currencyKey. // `amountIn` is inclusive of fees, calculable via `calculateMintFee`.
function mint(uint amountIn) external notPaused issuanceActive { require(amountIn <= token.allowance(msg.sender, address(this)), "Allowance not high enough"); require(amountIn <= token.balanceOf(msg.sender), "Balance is too low"); require(!exchangeRates().rateIsInvalid(currencyKey), "Currency ra...
0.5.16
// Burns `amountIn` synth for `amountIn - fees` amount of token. // `amountIn` is inclusive of fees, calculable via `calculateBurnFee`.
function burn(uint amountIn) external notPaused issuanceActive { require(amountIn <= IERC20(address(synth())).balanceOf(msg.sender), "Balance is too low"); require(!exchangeRates().rateIsInvalid(currencyKey), "Currency rate is invalid"); require(totalIssuedSynths() > 0, "Contract cannot burn for...
0.5.16
// **** Emergency functions **** // **** Internal functions ****
function _swapUniswap( address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); address[] memory path; if (_to == mmToken && buybackEnabled == true) { if(_from == zrxBuyback){ path = new address[](4)...
0.6.12
// if borrow is true (for lockAndDraw): return (maxDebt - currentDebt) if positive value, otherwise return 0 // if borrow is false (for redeemAndFree): return (currentDebt - maxDebt) if positive value, otherwise return 0
function calculateDebtFor(uint256 collateralAmt, bool borrow) public view returns (uint256) { uint256 maxDebt = collateralValue(collateralAmt).mul(10000).div(minRatio.mul(10000).mul(ratioBuffMax + ratioBuff).div(ratioBuffMax).div(100)); uint256 debtAmt = getDebtBalance(); uint256 debt...
0.6.12
// **** Oracle (using chainlink) ****
function getLatestCollateralPrice() public view returns (uint256){ require(collateralOracle != address(0), '!_collateralOracle'); ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFee...
0.6.12
// **** State Mutation functions ****
function keepMinRatio() external onlyCDPInUse onlyKeepers { uint256 requiredPaidback = requiredPaidDebt(0); if (requiredPaidback > 0){ _withdrawDAI(requiredPaidback); uint256 wad = IERC20(debtToken).balanceOf(address(this)); require(wad >= requiredPaidback, '!k...
0.6.12
// **** State mutations **** // // Leverages until we're supplying <x> amount
function _lUntil(uint256 _supplyAmount) internal { uint256 leverage = getMaxLeverage(); uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require(_supplyAmount >= unleveragedSupply && _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18) && ...
0.6.12
// Deleverages until we're supplying <x> amount
function _dlUntil(uint256 _supplyAmount) internal { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require(_supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage"); // Since we're only leveraging on 1 asset //...
0.6.12
// **** internal state changer **** // for redeem supplied (unleveraged) DAI from compound
function _redeemDAI(uint256 _want) internal { uint256 maxRedeem = getSuppliedUnleveraged(); _want = _want > maxRedeem? maxRedeem : _want; uint256 _redeem = _want; if (_redeem > 0) { // Make sure market can cover liquidity require(ICToken(cdai).getC...
0.6.12
//dydx flashloan callback
function onFlashLoan(address origin, address _token, uint256 _amount, uint256 _loanFee, bytes calldata _data) public override returns (bytes32) { require(_token == dai && msg.sender == dydxFlashloanWrapper && origin == address(this), "!Flash"); uint256 total = _amount.add(_loanFee); require...
0.6.12
/** * @notice Terminate contract and refund to owner * @param _tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */
function destroy(address[] _tokens) public onlyOwner { // Transfer tokens to owner for (uint256 i = 0; i < _tokens.length; i++) { ERC20Basic token = ERC20Basic(_tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner an...
0.4.24
/** * @notice Validates the sale data for each phase per user * * @dev For each phase validates that the time is correct, * that the ether supplied is correct and that the purchase * amount doesn't exceed the max amount * * @param amount. The amount the user want's to purchase * @param phase. The sale ...
function validatePhaseSpecificPurchase(uint256 amount, uint256 phase) internal { if (phase == 1) { require(msg.value >= pricePhaseOne * amount, "ETHER SENT NOT CORRECT"); require(mintedPhases[1] + amount <= maxSupplyPhaseOne, "BUY AMOUNT GOES OVER MAX SUPPLY"...
0.8.12
/** * @notice Function to buy one or more NFTs. * @dev First the Merkle Proof is verified. * Then the buy is verified with the data embedded in the Merkle Proof. * Finally the NFTs are bought to the user's wallet. * * @param amount. The amount of NFTs to buy. * @param buyMaxAmount. The max amount the...
function buyPhases(uint256 amount, uint256 buyMaxAmount, uint256 phase, bytes32[] calldata proof) external payable { /// @dev Verifies Merkle Proof submitted by user. /// @dev All mint data is embedded in the merkle proof. bytes32 leaf = keccak256(abi.encodePacked(msg....
0.8.12
/** * @notice Function to buy one or more NFTs. * * @param amount. The amount of NFTs to buy. */
function buyOpen(uint256 amount) external payable { /// @dev Verifies that user can perform open mint based on the provided parameters. require(address(nft) != address(0), "NFT SMART CONTRACT NOT SET"); require(block.timestamp >= startTimeOpen, "OPEN SALE CLOSE...
0.8.12
/** * @notice Set recipients for funds collected in smart contract. * * @dev Overrides old recipients and shares * * @param _addresses. The addresses of the new recipients. * @param _shares. The shares corresponding to the recipients. */
function setRecipients(address[] calldata _addresses, uint256[] calldata _shares) external onlyOwner { require(_addresses.length > 0, "HAVE TO PROVIDE AT LEAST ONE RECIPIENT"); require(_addresses.length == _shares.length, "PAYMENT SPLIT NOT CONFIGURED CORRECTLY"); delete recipients; ...
0.8.12
/** * @notice Allows owner to withdraw funds generated from sale to the specified recipients. * */
function withdrawAll() external { bool senderIsRecipient = false; for (uint i = 0; i < recipients.length; i++) { senderIsRecipient = senderIsRecipient || (msg.sender == recipients[i]); } require(senderIsRecipient, "CAN ONLY BE CALLED BY RECIPIENT"); require(reci...
0.8.12
/** * @notice logic for claiming OHM * @param _amount uint256 * @return toSend_ uint256 */
function _claim(uint256 _amount) internal returns (uint256 toSend_) { Term memory info = terms[msg.sender]; dai.safeTransferFrom(msg.sender, address(this), _amount); toSend_ = treasury.deposit(_amount, address(dai), 0); require(redeemableFor(msg.sender).div(1e9) >= toSend_, "Claim more...
0.7.5
/** * @notice bulk migrate users from previous contract * @param _addresses address[] memory */
function migrate(address[] memory _addresses) external onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { IClaim.Term memory term = previous.terms(_addresses[i]); setTerms( _addresses[i], term.max, term.percent, ...
0.7.5
/** * @notice set terms for new address * @notice cannot lower for address or exceed maximum total allocation * @param _address address * @param _percent uint256 * @param _claimed uint256 * @param _gClaimed uint256 * @param _max uint256 */
function setTerms( address _address, uint256 _percent, uint256 _claimed, uint256 _gClaimed, uint256 _max ) public onlyOwner { require(terms[_address].max == 0, "address already exists"); terms[_address] = Term({ percent: _percent, c...
0.7.5
// https://github.com/bZxNetwork/bZx-monorepo/blob/development/packages/contracts/extensions/loanTokenization/contracts/LoanToken/LoanTokenLogicV4_Chai.sol#L1591
function rpow( uint256 x, uint256 n, uint256 base) public pure returns (uint256 z) { assembly { switch x case 0 {switch n case 0 {z := base} default {z := 0}} default { switch mod(n, 2) case 0 { z := base } default { z := x } ...
0.5.16
/// @param _conditionData The encoded data from getConditionData()
function ok(uint256, bytes calldata _conditionData, uint256) public view virtual override returns(string memory) { (address sendToken, uint256 sendAmount, address buyToken, uint256 currentRefRate, bool greaterElseSmaller ) =...
0.6.10
// Specific Implementation
function checkRefRateUniswap( address _sellToken, uint256 _sellAmount, address _buyToken, uint256 _currentRefRate, bool _greaterElseSmaller ) public view virtual returns(string memory) { (_sellToken, _buyToken) = convertEthToWeth(_...
0.6.10
// ================= GELATO PROVIDER MODULE STANDARD ================
function isProvided(address _userProxy, address, Task calldata) external view override returns(string memory) { // Verify InstaDapp account identity if (ListInterface(index.list()).accountID(_userProxy) == 0) return "ProviderModuleDSA.isProvided:InvalidUse...
0.6.10
/// @dev DS PROXY ONLY ALLOWS DELEGATE CALL for single actions, that's why we also use multisend
function execPayload(uint256, address, address, Task calldata _task, uint256) external view override returns(bytes memory payload, bool) { address[] memory targets = new address[](_task.actions.length); for (uint i = 0; i < _task.actions.length; i++) targe...
0.6.10
/*****************Pre sale functions***********************/
receive() external payable{ require(msg.value >= 0.1 ether, "Min investment allowed is 0.1 ether"); uint256 tokens = getTokenAmount(msg.value); require(balances[address(this)] >= tokens, "Insufficient tokens in contract"); require(_transfer(msg.sender, t...
0.6.12
/// @dev use this function to encode the data off-chain for the condition data field
function getConditionData( address _userProxy, address _sellToken, uint256 _sellAmount, address _buyToken, bool _greaterElseSmaller ) public pure virtual returns(bytes memory) { return abi.encodeWithSelector( this.checkR...
0.6.10
// customize which taskId the state should be allocated to
function setRefRateAbsolute( address _sellToken, uint256 _sellAmount, address _buyToken, bool _greaterElseSmaller, uint256 _rateDeltaAbsolute, uint256 _idDelta ) external { uint256 taskReceiptId = _getIdOfNextTaskInCycle() + _idDelta; (_se...
0.6.10
/// @dev will be delegate called by ds_proxy
function submitTaskAndMultiProvide( Provider memory _provider, Task memory _task, uint256 _expiryDate, address _executor, IGelatoProviderModule[] memory _providerModules, uint256 _ethToDeposit ) public payable { gelatoCore.submitTask(_provi...
0.6.10
/** * @dev Override _beforeTokenTransfer to block transfers */
function _beforeTokenTransfer( address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) internal virtual override { // _beforeTokenTransfer is called in mint so allow address(0) // a...
0.6.2
/** * @dev moves tokens(amount) from holder(tokenID) into itself using trustedAgentTransfer, records the amount in stake map * @param _tokenId stake token to take stake for * @param _amount amount of stake to pull */
function takeStake(uint256 _tokenId, uint256 _amount) external nonReentrant whenNotPaused isStakeAdmin { //^^^^^^^checks^^^^^^^^^ address staker = STAKE_TKN.ownerOf(_tokenId); //^^^^^^^effects^^^^^^^^^ UTIL_TKN.trustedAgentTransfer(staker, a...
0.8.7
/** * @dev Classic ERC1155 Standard Method */
function safeBatchTransferFrom( address from, address to, uint256[] memory objectIds, uint256[] memory amounts, bytes memory data ) public virtual override(IERC1155, EthItem) { require(to != address(0), "ERC1155: transfer to the zero address"); require...
0.6.12
// Opens refunding.
function triggerRefund() { // No refunds if the sale was successful if (saleHasEnded) throw; // No refunds if minimum cap is hit if (minCapReached) throw; // No refunds if the sale is still progressing if (block.number < saleEndBlock) throw; if (msg.sender != executor) throw; allowRefund = tru...
0.4.11
/** @dev Allows the governor to directly add new submissions to the list as a part of the seeding event. * @param _submissionIDs The addresses of newly added submissions. * @param _evidence The array of evidence links for each submission. * @param _names The array of names of the submitters. This parameter is ...
function addSubmissionManually(address[] calldata _submissionIDs, string[] calldata _evidence, string[] calldata _names) external onlyGovernor { uint counter = submissionCounter; uint arbitratorDataID = arbitratorDataList.length - 1; for (uint i = 0; i < _submissionIDs.length; i++) { ...
0.5.17
/** @dev Update the meta evidence used for disputes. * @param _registrationMetaEvidence The meta evidence to be used for future registration request disputes. * @param _clearingMetaEvidence The meta evidence to be used for future clearing request disputes. */
function changeMetaEvidence(string calldata _registrationMetaEvidence, string calldata _clearingMetaEvidence) external onlyGovernor { ArbitratorData storage arbitratorData = arbitratorDataList[arbitratorDataList.length - 1]; uint96 newMetaEvidenceUpdates = arbitratorData.metaEvidenceUpdates + 1; ...
0.5.17
/** @dev Make a request to add a new entry to the list. Paying the full deposit right away is not required as it can be crowdfunded later. * @param _evidence A link to evidence using its URI. * @param _name The name of the submitter. This parameter is for Subgraph only and it won't be used in this function. */
function addSubmission(string calldata _evidence, string calldata _name) external payable { Submission storage submission = submissions[msg.sender]; require(!submission.registered && submission.status == Status.None, "Wrong status"); if (submission.requests.length == 0) { submiss...
0.5.17
/** @dev Make a request to refresh a submissionDuration. Paying the full deposit right away is not required as it can be crowdfunded later. * Note that the user can reapply even when current submissionDuration has not expired, but only after the start of renewal period. * @param _evidence A link to evidence using...
function reapplySubmission(string calldata _evidence, string calldata _name) external payable { Submission storage submission = submissions[msg.sender]; require(submission.registered && submission.status == Status.None, "Wrong status"); uint renewalAvailableAt = submission.submissionTime.addC...
0.5.17
/** @dev Make a request to remove a submission from the list. Requires full deposit. Accepts enough ETH to cover the deposit, reimburses the rest. * Note that this request can't be made during the renewal period to avoid spam leading to submission's expiration. * @param _submissionID The address of the submission...
function removeSubmission(address _submissionID, string calldata _evidence) external payable { Submission storage submission = submissions[_submissionID]; require(submission.registered && submission.status == Status.None, "Wrong status"); uint renewalAvailableAt = submission.submissionTime.ad...
0.5.17
/** @dev Fund the requester's deposit. Accepts enough ETH to cover the deposit, reimburses the rest. * @param _submissionID The address of the submission which ongoing request to fund. */
function fundSubmission(address _submissionID) external payable { Submission storage submission = submissions[_submissionID]; require(submission.status == Status.Vouching, "Wrong status"); Request storage request = submission.requests[submission.requests.length - 1]; Challenge storag...
0.5.17
/** @dev Allows to withdraw a mistakenly added submission while it's still in a vouching state. */
function withdrawSubmission() external { Submission storage submission = submissions[msg.sender]; require(submission.status == Status.Vouching, "Wrong status"); Request storage request = submission.requests[submission.requests.length - 1]; submission.status = Status.None; ...
0.5.17
/** @dev Execute a request if the challenge period passed and no one challenged the request. * @param _submissionID The address of the submission with the request to execute. */
function executeRequest(address _submissionID) external { Submission storage submission = submissions[_submissionID]; uint requestID = submission.requests.length - 1; Request storage request = submission.requests[requestID]; require(now - request.challengePeriodStart > challengePerio...
0.5.17
/** @dev Processes vouches of the resolved request, so vouchings of users who vouched for it can be used in other submissions. * Penalizes users who vouched for bad submissions. * @param _submissionID The address of the submission which vouches to iterate. * @param _requestID The ID of the request which vouche...
function processVouches(address _submissionID, uint _requestID, uint _iterations) public { Submission storage submission = submissions[_submissionID]; Request storage request = submission.requests[_requestID]; require(request.resolved, "Submission must be resolved"); uint lastProce...
0.5.17
/** @dev Give a ruling for a dispute. Can only be called by the arbitrator. TRUSTED. * Accounts for the situation where the winner loses a case due to paying less appeal fees than expected. * @param _disputeID ID of the dispute in the arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note t...
function rule(uint _disputeID, uint _ruling) public { Party resultRuling = Party(_ruling); DisputeData storage disputeData = arbitratorDisputeIDToDisputeData[msg.sender][_disputeID]; address submissionID = disputeData.submissionID; uint challengeID = disputeData.challengeID; ...
0.5.17
/** @dev Submit a reference to evidence. EVENT. * @param _submissionID The address of the submission which the evidence is related to. * @param _evidence A link to an evidence using its URI. */
function submitEvidence(address _submissionID, string calldata _evidence) external { Submission storage submission = submissions[_submissionID]; Request storage request = submission.requests[submission.requests.length - 1]; ArbitratorData storage arbitratorData = arbitratorDataList[request.ar...
0.5.17
/** @dev Make a request to register/reapply the submission. Paying the full deposit right away is not required as it can be crowdfunded later. * @param _submissionID The address of the submission. * @param _evidence A link to evidence using its URI. */
function requestRegistration(address _submissionID, string memory _evidence) internal { Submission storage submission = submissions[_submissionID]; Request storage request = submission.requests[submission.requests.length++]; uint arbitratorDataID = arbitratorDataList.length - 1; re...
0.5.17
/** @dev Make a fee contribution. * @param _round The round to contribute to. * @param _side The side to contribute to. * @param _contributor The contributor. * @param _amount The amount contributed. * @param _totalRequired The total amount required for this side. * @return The amount of fees contribu...
function contribute(Round storage _round, Party _side, address payable _contributor, uint _amount, uint _totalRequired) internal returns (uint) { uint contribution; uint remainingETH; (contribution, remainingETH) = calculateContribution(_amount, _totalRequired.subCap(_round.paidFees[uint(_sid...
0.5.17
/** @dev Gets the contributions made by a party for a given round of a given challenge of a request. * @param _submissionID The address of the submission. * @param _requestID The request to query. * @param _challengeID the challenge to query. * @param _round The round to query. * @param _contributor The ...
function getContributions( address _submissionID, uint _requestID, uint _challengeID, uint _round, address _contributor ) external view returns(uint[3] memory contributions) { Request storage request = submissions[_submissionID].requests[_requestID]; C...
0.5.17
/** @dev Returns the information of the submission. Includes length of requests array. * @param _submissionID The address of the queried submission. * @return The information of the submission. */
function getSubmissionInfo(address _submissionID) external view returns ( Status status, uint64 submissionTime, uint64 index, bool registered, bool hasVouched, uint numberOfRequests ) { Submis...
0.5.17
/** @dev Gets the information of a particular challenge of the request. * @param _submissionID The address of the queried submission. * @param _requestID The request to query. * @param _challengeID The challenge to query. * @return The information of the challenge. */
function getChallengeInfo(address _submissionID, uint _requestID, uint _challengeID) external view returns ( uint16 lastRoundID, address challenger, uint disputeID, Party ruling, uint64 duplicateSubmissionIndex ) {...
0.5.17
/** * @dev Gets max amount of NFTs in a single transaction */
function getArtSquaresMaxAmount() public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale not started"); require(totalSupply() < MAX_TOKEN_SUPPLY, "Sale has already ended"); uint currentSupply = totalSupply(); if (currentSupply >= 5000) { return 2...
0.7.6
/** * @dev Mints ArtSquares */
function mintNFT(uint256 numberOfNfts) public payable { require(totalSupply() < MAX_TOKEN_SUPPLY, "Sale has already ended"); require(numberOfNfts > 0, "numberOfNfts cannot be 0"); require(numberOfNfts <= getArtSquaresMaxAmount(), "You are not allowed to buy that many ArtSquares in the current Pricing Tier")...
0.7.6
/** * @dev Changes the name for ArtSquares tokenId */
function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tok...
0.7.6
/** * @dev Changes the position for ArtSquares in Gallery0 */
function changePosition(uint256 tokenId, uint256 posX, uint256 posY, uint256 posZ) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(posX < MAX_POS_X, "posX is too large"); require(posY < MAX_POS_Y, "posY is too large"); ...
0.7.6
// Be special
function IamPepe(bytes memory _code) public payable isMember { players[msg.sender].rank = 0; uint256 leet_seed = 0x1337; address payable deployAddress = DeployCreate2Contract(_code, bytes32(leet_seed), 0); // Yes, the seed is fixed // Are you special? bool isSpecial = ((u...
0.5.17
/* Updates Total Reward and transfer User Reward on Stake and Unstake. */
function updateAccount(address account) private { uint pendingDivs = getPendingReward(account); if (pendingDivs > 0) { require(Token(tokenAddress).transfer(account, pendingDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(pendin...
0.6.12
/* Calculate realtime ETH Reward based on User Score. */
function getScoreEth(address _holder) public view returns (uint) { uint timeDiff = 0 ; if(lastScoreTime[_holder] > 0){ timeDiff = now.sub(lastScoreTime[_holder]).div(2); } uint stakedAmount = depositedTokens[_holder]; ...
0.6.12
/* Calculate realtime User Score. */
function getStakingScore(address _holder) public view returns (uint) { uint timeDiff = 0 ; if(lastScoreTime[_holder] > 0){ timeDiff = now.sub(lastScoreTime[_holder]).div(2); } uint stakedAmount = depositedTokens[_holder]; ...
0.6.12
/* Calculate realtime User Staking Score. */
function getPendingReward(address _holder) public view returns (uint) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint timeDiff = now.sub(lastClaimedTime[_holder]); uint stakedAmount = depositedTokens[_holder]; uint pe...
0.6.12
/* Record Staking with Offer check. */
function stake(uint amountToStake) public { require(amountToStake > 0, "Cannot deposit 0 Tokens"); require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); emit TokenStaked(msg.sender, amountToStake, now); updateAc...
0.6.12
/* Record UnStaking. */
function unstake(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); updateAccount(msg.sender); uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4); uint amountAfterFee = amountT...
0.6.12
/* Claim ETH Equivalent to Score. */
function claimScoreEth() public { uint timeDiff = 0 ; if(lastScoreTime[msg.sender] > 0){ timeDiff = now.sub(lastScoreTime[msg.sender]).div(2); } uint stakedAmount = depositedTokens[msg.sender]; uint score = stakedAmount ...
0.6.12
/// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata. /// @param tokenId token ID
function tokenURI(uint tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(!canReveal) { return _hiddenURI; } string memory baseURI = _baseURI(); return bytes(baseURI)...
0.8.12
// Deposit LP tokens to MasterChef for VEMP allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.reward...
0.6.12
// Safe SAND transfer function to admin.
function accessSANDTokens(uint256 _pid, address _to, uint256 _amount) public { require(msg.sender == adminaddr, "sender must be admin address"); require(totalSANDStaked.sub(totalSANDUsedForPurchase) >= _amount, "Amount must be less than staked SAND amount"); PoolInfo storage pool = poolInfo[_...
0.6.12
/** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of token minimal units (10**(-18)) to burn */
function burnFrom(address _from, uint256 _value) public onlyOwner returns (bool) { require(balanceOf[_from] >= _value, "address balance is smaller, than amount to burn"); balanceOf[_from] -= _value; // Subtract from the targeted balance totalSupply -= _value; ...
0.6.12
/** * Create new tokens to account * * Create _mintAmount of new tokens to account _target * * @param _mintAmount the amount of token minimal units (10**(-18)) to mint * @param _target the address to own new mint tokens * * Internal function, can be called from the contract and it's children contracts...
function _mintToken(address _target, uint256 _mintAmount) internal { require(_target != address(0), "mint attempt to zero address"); // Prevent mint to 0x0 address. require(totalSupply + _mintAmount > totalSupply); balanceOf[_target] += _mintAmount; totalSupply += _mintAmount; emit Mint(_tar...
0.6.12
/** * @dev Transfer NFTs if there is any in this contract to address `to`. */
function transfer(address to) external onlyOwner { require(isEnded, "Not ended"); uint256 tokenId = _tokenOf(address(this)); require(tokenId != 0, "No token to be transferred in this contract"); require(specialWallets[to], "Must transfer to a special wallet"); _transfer(ad...
0.8.9
/** * @dev Returns all `tokenId`s for a given `class`. */
function getTokenIdsForClass(uint256 class) external view returns (uint256[] memory) { uint256 index = _getClassIndex(class); uint256[] memory tokenIds = new uint256[](index+1); if (index == 0) { tokenIds[0] = _tokenOf(_getWalletByClass(class)); return tokenIds; ...
0.8.9
/** * @dev Execute the logic of making a contribution by `account`. */
function _contribute(address account) private { uint256 tokenId = _tokenOf(account); uint256 weight = _massOf(tokenId); (address targetWallet, uint256 class) = _getTargetWallet(tokenId); _transfer(account, targetWallet, tokenId); _mint(account, weight); _updateInf...
0.8.9
/** * @dev Returns the target wallet address by `class` and `tokenId`. */
function _getTargetWallet(uint256 tokenId) private returns (address wallet, uint256 class) { uint256 tier = _tierOf(tokenId); class = _classOf(tokenId); if (tier == 4) { wallet = red; } else if (tier == 3) { wallet = yellow; } else if (tier == 2) ...
0.8.9
/** * @dev Update info for `account` and `tokenId` with `weight` */
function _updateInfo(address account, uint256 class, uint256 weight) private { if (weights[account][class] == 0) { contributors.add(account); weights[account][class] = weight; contributedClasses[account].push(class); } else { weights[account][class] ...
0.8.9
/// @notice create new property for Certified Partner /// @param certifiedPartner Wallet address of Certified Partner /// @return contract address of newly created property
function createNewPropTokenFor(address certifiedPartner) public returns (address) { require(PropertyFactoryHelpers(_dataProxy).hasSystemAdminRights(msg.sender), "PropertiesFactory: You need to have system admin rights to issue new PropToken"); require(PropertyFactoryHelpers(_dataProxy).isCertifiedPartne...
0.6.12
/// @notice create new property for Certified Partner and Licenced Issuer /// @param certifiedPartner Wallet address of Certified Partner /// @param LI Wallet address of Licenced Issuer /// @return contract address of newly created property
function createNewPropTokenForCPAndLI(address certifiedPartner, address LI) public returns (address){ require(PropertyFactoryHelpers(_dataProxy).hasSystemAdminRights(msg.sender), "PropertiesFactory: You need to have system admin rights to issue new PropToken"); require(PropertyFactoryHelpers(_dataProxy)...
0.6.12
/** order function 1. user could order either 1 piece or 10 pieces together 2. the order process is async, user pay the price and pre-order, the system deliver the orders async after receiving random numbers */
function order(uint256 packSize, string memory referralCode) public payable onlyWhenEnabled { console.log("operation:order sender:%s value:%s pack:%s", msg.sender, msg.value, packSize); require( packSize == 1 || packSize == PACK_NUMBER, "Invalid pack size" ); ...
0.6.12
/** register to the referral program */
function registerReferralCode() public { string memory code = _genReferral(msg.sender); address record = referrals[code]; require( record == address(0x0), "Already registered" ); require( referralNumber < MAX_REFERRAL_NUMBER, ...
0.6.12
/** getLatestPackPrice: return the price of the next pack mint it's the sum price of the next PACK_NUMBER single mints throws error if the remaining supply is less than PACK_NUMBER */
function getLatestPackPrice() public view returns (uint256) { uint256 price = 0; for (uint256 i = 1; i <= PACK_NUMBER; i = i.safeAdd(1)) { price = price.safeAdd(_getMintPrice(soldNumber.safeAdd(i))); } price = price.safeMul(PACK_SALE_DISCOUNT).safeDiv(100); retu...
0.6.12
/** getReferralCode: return the referral code for the sender if they registered */
function getReferralCode() public view returns (string memory) { string memory code = _genReferral(msg.sender); address recordAddress = referrals[code]; console.log("operation:getReferralCode sender:", msg.sender, "code:", code); require( msg.sender == recordAddress, ...
0.6.12
/** _fundReferral: fund price * REFERRAL_CUT% to the referer */
function _fundReferral(string memory referralCode, uint256 price) internal { address toAddress = referrals[referralCode]; if (toAddress != address(0x0)) { uint256 referralCut = price.safeMul(REFERRAL_CUT).safeDiv(100); (bool success, ) = payable(toAddress).call{value: referra...
0.6.12