comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/// @notice This function does all calculations to find trade dest amount without accounting /// for maxDestAmount. Part of this process includes: /// - Call kyberMatchingEngine to parse hint and get an optional reserve list to trade. /// - Query reserve rates and call kyberMatchingEngine to use b...
function calcRatesAndAmounts(TradeData memory tradeData, bytes memory hint) internal view returns (uint256 destAmount, uint256 rateWithNetworkFee) { validateFeeInput(tradeData.input, tradeData.networkFeeBps); // token -> eth: find best reserves match and calculate wei...
0.6.6
/// @dev Checks a trade input validity, including correct src amounts /// @param input Trade input structure
function validateTradeInput(TradeInput memory input) internal view { require(isEnabled, "network disabled"); require(kyberProxyContracts[msg.sender], "bad sender"); require(tx.gasprice <= maxGasPriceValue, "gas price"); require(input.srcAmount <= MAX_QTY, "srcAmt > MAX_QTY"); ...
0.6.6
/// @notice Update reserve data with selected reserves from kyberMatchingEngine
function updateReservesList(ReservesData memory reservesData, uint256[] memory selectedIndexes) internal pure { uint256 numReserves = selectedIndexes.length; require(numReserves <= reservesData.addresses.length, "doMatch: too many reserves"); IKyberReserve[] memory ...
0.6.6
/// @notice Verify split values bps and reserve ids, /// then calculate the destQty from srcAmounts and rates /// @dev Each split bps must be in range (0, BPS] /// @dev Total split bps must be 100% /// @dev Reserve ids must be increasing
function validateTradeCalcDestQtyAndFeeData( IERC20 src, ReservesData memory reservesData, TradeData memory tradeData ) internal pure returns (uint256 totalDestAmount) { uint256 totalBps; uint256 srcDecimals = (src == ETH_TOKEN_ADDRESS) ? ETH_DECIMALS : reservesData.dec...
0.6.6
/// @notice Recalculates tradeWei, network and platform fees, and actual source amount needed for the trade /// in the event actualDestAmount > maxDestAmount
function calcTradeSrcAmountFromDest(TradeData memory tradeData) internal pure virtual returns (uint256 actualSrcAmount) { uint256 weiAfterDeductingFees; if (tradeData.input.dest != ETH_TOKEN_ADDRESS) { weiAfterDeductingFees = calcTradeSrcAmount( ...
0.6.6
/// @notice Recalculates srcAmounts and stores into tradingReserves, given the new destAmount. /// Uses the original proportion of srcAmounts and rates to determine new split destAmounts, /// then calculate the respective srcAmounts /// @dev Due to small rounding errors, will fallback to current src amounts if ...
function calcTradeSrcAmount( uint256 srcAmount, uint256 srcDecimals, uint256 destDecimals, uint256 destAmount, ReservesData memory reservesData ) internal pure returns (uint256 newSrcAmount) { uint256 totalWeightedDestAmount; for (uint256 i = 0; i < re...
0.6.6
/* * Buy in function to be called mostly from the fallback function * @dev kept public in order to buy for someone else * @param beneficiary address */
function buyTokens(address beneficiary) private { require(beneficiary != 0x0); require(validPurchase()); // Check the register if the investor was approved require(register.approved(beneficiary)); uint256 weiAmount = msg.value; // calculate token amount to be ...
0.4.18
/** * @dev Batch Function to mark spender for approved for all. Does a check * for address(0) and throws if true * @notice Facilitates batch approveAll * @param _spenders The spenders * @param _approved The approved */
function batchSetApprovalForAll( address[] _spenders, bool _approved ) public { require (isBatchSupported); require (_spenders.length > 0); address _spender; for (uint256 i = 0; i < _spenders.length; ++i) { requir...
0.4.24
/** * @dev Only gov. Will revert if the destinationToken isn't on the allowed list * * @param _integrationName The name of the integration to interact with * @param _sourceToken The address of the token to spend * @param _sourceAmount The source amount to trade * @...
function trade( address, // Left here purely so that ABI is exactly the same as the trade module /* unused */ string memory _integrationName, address _sourceToken, uint256 _sourceAmount, address _destinationToken, uint256 _minimumDestinationAmount, bytes me...
0.6.12
// send ETH to the fund collection wallet(s)
function forwardFunds(uint256 partnerTokenAmount, uint256 weiMinusfee) internal { for (uint i=0;i<owners.length;i++) { uint percent = ownerAddresses[owners[i]]; uint amountToBeSent = weiMinusfee.mul(percent); amountToBeSent = amountToBeSent.div(100); owners[i].trans...
0.4.26
/** * @dev Function to request Detachment from our Contract * @notice a wallet can request to detach it collectible, so, that it can be used in other third-party contracts. * @param _tokenId The token identifier */
function requestDetachment( uint256 _tokenId ) public { //Request can only be made by owner or approved address require (isApprovedOrOwner(msg.sender, _tokenId)); uint256 isAttached = checkIsAttached(_tokenId); //If collectible is on a gamecard prevent...
0.4.24
/** * Set some Dorkis aside for giveaways. */
function reserveTokens() public onlyOwner { require(totalSupply().add(MAX_RESERVE) <= MAX_SLOTHS, "Reserve would exceed max supply of Dorkis"); uint supply = totalSupply(); for (uint i = 0; i < MAX_RESERVE; i++) { _safeMint(msg.sender, supply + i); } }
0.8.6
/** * Mints Sloths */
function mintSloths(uint numberOfTokens) public payable { require(numberOfTokens > 0, "numberOfNfts cannot be 0"); require(saleIsActive, "Sale must be active to mint tokens"); require(numberOfTokens <= MAX_PURCHASE, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOf...
0.8.6
/** * Get all tokens for a specific wallet * */
function getTokensForAddress(address fromAddress) external view returns (uint256 [] memory){ uint tokenCount = balanceOf(fromAddress); uint256[] memory tokensId = new uint256[](tokenCount); for(uint i = 0; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(fromAddress, i); ...
0.8.6
/** * @dev Facilitates Creating Sale using the Sale Contract. Forces owner check & collectibleId check * @notice Helps a wallet to create a sale using our Sale Contract * @param _tokenId The token identifier * @param _startingPrice The starting price * @param _endingPrice The endin...
function initiateCreateSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external { require (_tokenId != 0); // If DodgersNFT is already on any sale, this will throw // because it will be owned by the sale contract. address owner = owne...
0.4.24
/** * @dev Facilitates batch auction of collectibles, and enforeces strict checking on the collectibleId,starting/ending price, duration. * @notice Batch function to put 10 or less collectibles on sale * @param _tokenIds The token identifier * @param _startingPrices The starting pri...
function batchCreateAssetSale(uint256[] _tokenIds, uint256[] _startingPrices, uint256[] _endingPrices, uint256[] _durations) external whenNotPaused { require (_tokenIds.length > 0 && _startingPrices.length > 0 && _endingPrices.length > 0 && _durations.length > 0); // Sale contract checks i...
0.4.24
// Tests for uppercase characters in a given string
function allLower(string memory _string) internal pure returns (bool) { bytes memory bytesString = bytes(_string); for (uint i = 0; i < bytesString.length; i++) { if ((bytesString[i] >= 65) && (bytesString[i] <= 90)) { // Uppercase characters return false; }...
0.4.21
// Allows the Hydro API to delete official users iff they've signed keccak256("Delete") with their private key
function deleteUserForUser(string userName, uint8 v, bytes32 r, bytes32 s) public onlyOwner { bytes32 userNameHash = keccak256(userName); require(userNameHashTaken(userNameHash)); address userAddress = userDirectory[userNameHash].userAddress; require(isSigned(userAddress, keccak256("...
0.4.21
// Allows anyone to sign up as an unofficial application
function unofficialApplicationSignUp(string applicationName) public payable { require(bytes(applicationName).length < 100); require(msg.value >= unofficialApplicationSignUpFee); require(applicationName.allLower()); HydroToken hydro = HydroToken(hydroTokenAddress); uint256 ...
0.4.21
/// @dev Mints a new token. /// @param _to Address of token owner.
function mint(address _to) minterOnly returns (bool success) { // ensure that the token owner doesn't already own a token. if (balances[_to] != 0x0) return false; balances[_to] = 1; // log the minting of this token. Mint(_to); Transfer(0x0, _to, 1); Tok...
0.4.8
// @dev Mint many new tokens
function mint(address[] _to) minterOnly returns (bool success) { for(uint i = 0; i < _to.length; i++) { if(balances[_to[i]] != 0x0) return false; balances[_to[i]] = 1; Mint(_to[i]); Transfer(0x0, _to[i], 1); TokenEventLib._Transfer(0x0, _to[i]); ...
0.4.8
/// @dev Transfers sender token to given address. Returns success. /// @param _to Address of new token owner. /// @param _value Bytes32 id of the token to transfer.
function transfer(address _to, uint256 _value) public returns (bool success) { if (_value != 1) { // 1 is the only value that makes any sense here. return false; } else if (_to == 0x0) { // cannot transfer to the null address. ...
0.4.8
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success. /// @param _from Address of token owner. /// @param _to Address of new token owner. /// @param _value Bytes32 id of the token to transfer.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (_value != 1) { // Cannot transfer anything other than 1 token. return false; } else if (_to == 0x0) { // Ca...
0.4.8
/// @dev Sets approval spender to transfer ownership of token. Returns success. /// @param _spender Address of spender.. /// @param _value Bytes32 id of token that can be spend.
function approve(address _spender, uint256 _value) public returns (bool success) { if (_value != 1) { // cannot approve any value other than 1 return false; } else if (_spender == 0x0) { // cannot approve the null address as a spender. ...
0.4.8
// This function is for dev address migrate all balance to a multi sig address
function transferAll(address _to) public { _locks[_to] = _locks[_to].add(_locks[msg.sender]); if (_lastUnlockBlock[_to] < lockFromBlock) { _lastUnlockBlock[_to] = lockFromBlock; } if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) { _lastUnlockBlo...
0.6.12
/** * @notice function to propose * * @param targets - array of address * @param values - array of values * @param signatures - array of signatures * @param calldatas - array of data * @param description - array of descriptions * * @return id of proposal */
function propose( address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description ) external onlyMember returns (uint) { require( targets.length == valu...
0.6.12
/** * @notice function to execute on what is voted * * @param proposalId - id of proposal */
function execute( uint proposalId ) external onlyMember payable { // load the proposal Proposal storage proposal = proposals[proposalId]; // Require that proposal is not previously executed neither cancelled require(!proposal.executed && ...
0.6.12
/** * @notice function to cancel proposal * * @param proposalId - id of proposal */
function cancel( uint proposalId ) external onlyMember { Proposal storage proposal = proposals[proposalId]; // Require that proposal is not previously executed neither cancelled require(!proposal.executed && !proposal.canceled, "TokensFarmCongress:cancel: ...
0.6.12
/** * @notice function to see what was voted on * * @param proposalId - id proposal * * @return targets * @return values * @return signatures * @return calldatas */
function getActions( uint proposalId ) external view returns ( address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas ) { Proposal storage p = proposals[propo...
0.6.12
/** * @dev Return purchase receipt info at a given ID * @param _purchaseReceiptId The ID of the purchased content * @return The ID of the content host * @return The ID of the staked content * @return The ID of the content * @return address of the buyer * @return price of the content * @r...
function getById(bytes32 _purchaseReceiptId) external view returns (bytes32, bytes32, bytes32, address, uint256, uint256, uint256, string memory, address, uint256) { // Make sure the purchase receipt exist require (this.isExist(_purchaseReceiptId)); PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[pu...
0.5.4
/** * @dev Check whether or not the passed params valid * @param _buyer The address of the buyer * @param _contentHostId The ID of hosted content * @param _publicKey The public key of the request node * @param _publicAddress The public address of the request node * @return true if yes, false oth...
function _canBuy(address _buyer, bytes32 _contentHostId, string memory _publicKey, address _publicAddress ) internal view returns (bool) { (bytes32 _stakedContentId,,address _host,,) = _aoContentHost.getById(_contentHostId); // Make sure the content host exist return (_aoContentHost.isExist(_conte...
0.5.4
// Constructor function sets the BCDC Multisig address and // total number of locked tokens to transfer
function BCDCVault(address _bcdcMultisig,uint256 _numBlocksLockedForDev,uint256 _numBlocksLockedForFounders) { // If it's not bcdcMultisig address then throw if (_bcdcMultisig == 0x0) throw; // Initalized bcdcToken bcdcToken = BCDCToken(msg.sender); // Initalized bcdcMultisi...
0.4.18
// Transfer Development Team Tokens To MultiSigWallet - 30 Days Locked
function unlockForDevelopment() external { // If it has not reached 30 days mark do not transfer if (block.number < unlockedBlockForDev) throw; // If it is already unlocked then do not allowed if (unlockedAllTokensForDev) throw; // Mark it as unlocked unlockedAllTok...
0.4.18
// Transfer Founders Team Tokens To MultiSigWallet - 365 Days Locked
function unlockForFounders() external { // If it has not reached 365 days mark do not transfer if (block.number < unlockedBlockForFounders) throw; // If it is already unlocked then do not allowed if (unlockedAllTokensForFounders) throw; // Mark it as unlocked unlock...
0.4.18
// Transfer `value` BCDC tokens from sender's account // `msg.sender` to provided account address `to`. // @dev Required state: Success // @param to The address of the recipient // @param value The number of BCDC tokens to transfer // @return Whether the transfer was successful or not
function transfer(address to, uint value) returns (bool ok) { if (getState() != State.Success) throw; // Abort if crowdfunding was not a success. uint256 senderBalance = balances[msg.sender]; if ( senderBalance >= value && value > 0) { senderBalance = safeSub(senderBalance, value...
0.4.18
// Sale of the tokens. Investors can call this method to invest into BCDC Tokens // Only when it's in funding mode. In case of emergecy it will be halted.
function() payable stopIfHalted external { // Allow only to invest in funding state if (getState() != State.Funding) throw; // Sorry !! We do not allow to invest with 0 as value if (msg.value == 0) throw; // multiply by exchange rate to get newly created token amount ...
0.4.18
// To allocate tokens to Project Fund - eg. RecycleToCoin before Token Sale // Tokens allocated to these will not be count in totalSupply till the Token Sale Success and Finalized in finalizeCrowdfunding()
function preAllocation() onlyOwner stopIfHalted external { // Allow only in Pre Funding Mode if (getState() != State.PreFunding) throw; // Check if BCDC Reserve Fund is set or not if (bcdcReserveFund == 0x0) throw; // To prevent multiple call by mistake if (prealloc...
0.4.18
// BCDC accepts Early Investment through manual process in Fiat Currency // BCDC Team will assign the tokens to investors manually through this function
function earlyInvestment(address earlyInvestor, uint256 assignedTokens) onlyOwner stopIfHalted external { // Allow only in Pre Funding Mode And Funding Mode if (getState() != State.PreFunding && getState() != State.Funding) throw; // Check if earlyInvestor address is set or not if (e...
0.4.18
// Function will transfer the tokens to investor's address // Common function code for Early Investor and Crowdsale Investor
function assignTokens(address investor, uint256 tokens) internal { // Creating tokens and increasing the totalSupply totalSupply = safeAdd(totalSupply, tokens); // Assign new tokens to the sender balances[investor] = safeAdd(balances[investor], tokens); // Finally token...
0.4.18
// Call this function to get the refund of investment done during Crowdsale // Refund can be done only when Min Goal has not reached and Crowdsale is over
function refund() external { // Abort if not in Funding Failure state. if (getState() != State.Failure) throw; uint256 bcdcValue = balances[msg.sender]; if (bcdcValue == 0) throw; balances[msg.sender] = 0; totalSupply = safeSub(totalSupply, bcdcValue); ...
0.4.18
// This will return the current state of Token Sale // Read only method so no transaction fees
function getState() public constant returns (State){ if (block.number < fundingStartBlock) return State.PreFunding; else if (block.number <= fundingEndBlock && totalSupply < tokenSaleMax) return State.Funding; else if (totalSupply >= tokenSaleMin || upgradeAgentStatus) return State.Success; ...
0.4.18
/// @notice Upgrade tokens to the new token contract. /// @dev Required state: Success /// @param value The number of tokens to upgrade
function upgrade(uint256 value) external { if (!upgradeAgentStatus) throw; /*if (getState() != State.Success) throw; // Abort if not in Success state.*/ if (upgradeAgent.owner() == 0x0) throw; // need a real upgradeAgent address if (finalizedUpgrade) throw; // cannot upgrade if final...
0.4.18
/// @notice Set address of upgrade target contract and enable upgrade /// process. /// @dev Required state: Success /// @param agent The address of the UpgradeAgent contract
function setUpgradeAgent(address agent) external { if (getState() != State.Success) throw; // Abort if not in Success state. if (agent == 0x0) throw; // don't set agent to nothing if (msg.sender != upgradeMaster) throw; // Only a master can designate the next agent upgradeAgent = Upg...
0.4.18
/// @notice Set address of upgrade target contract and enable upgrade /// process. /// @dev Required state: Success /// @param master The address that will manage upgrades, not the upgradeAgent contract address
function setUpgradeMaster(address master) external { if (getState() != State.Success) throw; // Abort if not in Success state. if (master == 0x0) throw; if (msg.sender != upgradeMaster) throw; // Only a master can designate the next master upgradeMaster = master; }
0.4.18
// This method is only use for transfer bcdctoken from bcdcReserveFund // @dev Required state: is bcdcReserveFund set // @param to The address of the recipient // @param value The number of BCDC tokens to transfer // @return Whether the transfer was successful or not
function reserveTokenClaim(address claimAddress,uint256 token) onlyBcdcReserve returns (bool ok){ // Check if BCDC Reserve Fund is set or not if ( bcdcReserveFund == 0x0) throw; uint256 senderBalance = balances[msg.sender]; if(senderBalance >= token && token>0){ senderBalance = safe...
0.4.18
// This method is for getting bcdctoken as rewards // @param tokens The number of tokens back for rewards
function backTokenForRewards(uint256 tokens) external{ // Check that token available for transfer if(balances[msg.sender] < tokens && tokens <= 0) throw; // Debit tokens from msg.sender balances[msg.sender] = safeSub(balances[msg.sender], tokens); // Credit tokens into bcdcReserveFund ...
0.4.18
// Return the current schedule based on the timestamp // applicable based on startPeriod and endPeriod
function getCurrentSchedule() public view returns (uint) { require(now <= schedules[6].endPeriod, "Mintable periods have ended"); for (uint i = 0; i < INFLATION_SCHEDULES_LENGTH; i++) { if (schedules[i].startPeriod <= now && schedules[i].endPeriod >= now) { ...
0.4.25
/** * @notice Update the Synthetix Drawing Rights exchange rate based on other rates already updated. */
function updateXDRRate(uint timeSent) internal { uint total = 0; for (uint i = 0; i < xdrParticipants.length; i++) { total = rates(xdrParticipants[i]).add(total); } // Set the rate and update time _setRate("XDR", total, timeSent); // Emit our up...
0.4.25
/** * @notice Retrieve the last update time for a specific currency */
function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKey...
0.4.25
/** * @notice ERC223 transferFrom function */
function transferFrom(address from, address to, uint value, bytes data) public optionalProxy returns (bool) { require(from != 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef, "The fee address is not allowed"); // Skip allowance update in case of infinite allowance if (tok...
0.4.25
/** * @notice ERC223 transfer function. Does not conform with the ERC223 spec, as: * - Transaction doesn't revert if the recipient doesn't implement tokenFallback() * - Emits a standard ERC20 event without the bytes data parameter so as not to confuse * tooling such as Etherscan. */
function transfer(address to, uint value, bytes data) public optionalProxy returns (bool) { // Ensure they're not trying to exceed their locked amount require(value <= transferableSynthetix(messageSender), "Insufficient balance"); // Perform the transfer: if there is...
0.4.25
/** * @notice Issue synths against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. Amount should be larger than 0. * @param currencyKey The currency you wish to issue synths in, for example sUSD or sAUD * @param amount The amount of synths you wish to issue with a base of UNIT ...
function issueSynths(bytes32 currencyKey, uint amount) public optionalProxy // No need to check if price is stale, as it is checked in issuableSynths. { require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); // Keep track of the debt they...
0.4.25
/** * @notice Issue the maximum amount of Synths possible against the sender's SNX. * @dev Issuance is only allowed if the synthetix price isn't stale. * @param currencyKey The currency you wish to issue synths in, for example sUSD or sAUD */
function issueMaxSynths(bytes32 currencyKey) external optionalProxy { // Figure out the maximum we can issue in that currency uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); // Keep track of the debt they're about to create _addToDebtRegister(...
0.4.25
/** * @notice Burn synths to clear issued synths/free SNX. * @param currencyKey The currency you're specifying to burn * @param amount The amount (in UNIT base) you wish to burn * @dev The amount to burn is debased to XDR's */
function burnSynths(bytes32 currencyKey, uint amount) external optionalProxy // No need to check for stale rates as effectiveValue checks rates { // How much debt do they have? uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint existingDebt = debtBal...
0.4.25
/** * @notice Find the oldest debtEntryIndex for the corresponding closingDebtIndex * @param account users account * @param closingDebtIndex the last periods debt index on close */
function applicableIssuanceData(address account, uint closingDebtIndex) external view returns (uint, uint) { IssuanceData[FEE_PERIOD_LENGTH] memory issuanceData = accountIssuanceLedger[account]; // We want to use the user's debtEntryIndex at when the period closed ...
0.4.25
/** * @notice Logs an accounts issuance data in the current fee period which is then stored historically * @param account Message.Senders account address * @param debtRatio Debt of this account as a percentage of the global debt. * @param debtEntryIndex The index in the global debt ledger. synthetix.synthetixState(...
function appendAccountIssuanceRecord(address account, uint debtRatio, uint debtEntryIndex, uint currentPeriodStartDebtIndex) external onlyFeePool { // Is the current debtEntryIndex within this fee period if (accountIssuanceLedger[account][0].debtEntryIndex < currentPeriodStartDebtInd...
0.4.25
/** * @notice Pushes down the entire array of debt ratios per fee period */
function issuanceDataIndexOrder(address account) private { for (uint i = FEE_PERIOD_LENGTH - 2; i < FEE_PERIOD_LENGTH; i--) { uint next = i + 1; accountIssuanceLedger[account][next].debtPercentage = accountIssuanceLedger[account][i].debtPercentage; accountIssuance...
0.4.25
/** * @notice Import issuer data from synthetixState.issuerData on FeePeriodClose() block # * @dev Only callable by the contract owner, and only for 6 weeks after deployment. * @param accounts Array of issuing addresses * @param ratios Array of debt ratios * @param periodToInsert The Fee Period to insert the histo...
function importIssuerData(address[] accounts, uint[] ratios, uint periodToInsert, uint feePeriodCloseIndex) external onlyOwner onlyDuringSetup { require(accounts.length == ratios.length, "Length mismatch"); for (uint i = 0; i < accounts.length; i++) { accountIssu...
0.4.25
/** * @notice The RewardsDistribution contract informs us how many SNX rewards are sent to RewardEscrow to be claimed. */
function setRewardsToDistribute(uint amount) external { require(messageSender == rewardsAuthority || msg.sender == rewardsAuthority, "Caller is not rewardsAuthority"); // Add the amount of SNX rewards to distribute on top of any rolling unclaimed amount _recentFeePeriodsStorage(0).re...
0.4.25
/** * @notice Admin function to import the FeePeriod data from the previous contract */
function importFeePeriod( uint feePeriodIndex, uint feePeriodId, uint startingDebtIndex, uint startTime, uint feesToDistribute, uint feesClaimed, uint rewardsToDistribute, uint rewardsClaimed) public optionalProxy_onlyOwner onlyDuringSetup { require (startingD...
0.4.25
/** * @notice Send the rewards to claiming address - will be locked in rewardEscrow. * @param account The address to send the fees to. * @param snxAmount The amount of SNX. */
function _payRewards(address account, uint snxAmount) internal notFeeAddress(account) { require(account != address(0), "Account can't be 0"); require(account != address(this), "Can't send rewards to fee pool"); require(account != address(proxy), "Can't send rewards to proxy")...
0.4.25
/** * @notice Calculate the fee charged on top of a value being sent via an exchange * @return Return the fee charged */
function exchangeFeeIncurred(uint value) public view returns (uint) { return value.multiplyDecimal(exchangeFeeRate); // Exchanges less than the reciprocal of exchangeFeeRate should be completely eaten up by fees. // This is on the basis that exchanges less than this ...
0.4.25
/** * @notice The total fees available in the system to be withdrawn, priced in currencyKey currency * @param currencyKey The currency you want to price the fees in */
function totalFeesAvailable(bytes32 currencyKey) external view returns (uint) { uint totalFees = 0; // Fees in fee period [0] are not yet available for withdrawal for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalFees = totalFees.add(_recentFeePeriodsSt...
0.4.25
/** * @notice The total SNX rewards available in the system to be withdrawn */
function totalRewardsAvailable() external view returns (uint) { uint totalRewards = 0; // Rewards in fee period [0] are not yet available for withdrawal for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalRewards = totalRewards.add(_recentFeePeriodsStorag...
0.4.25
/** * @notice The fees available to be withdrawn by a specific account, priced in currencyKey currency * @dev Returns two amounts, one for fees and one for SNX rewards * @param currencyKey The currency you want to price the fees in */
function feesAvailable(address account, bytes32 currencyKey) public view returns (uint, uint) { // Add up the fees uint[2][FEE_PERIOD_LENGTH] memory userFees = feesByPeriod(account); uint totalFees = 0; uint totalRewards = 0; // Fees & Rewards in fee...
0.4.25
/** * @notice Check if a particular address is able to claim fees right now * @param account The address you want to query for */
function isFeesClaimable(address account) public view returns (bool) { // Threshold is calculated from ratio % above the target ratio (issuanceRatio). // 0 < 10%: Claimable // 10% > above: Unable to claim uint ratio = synthetix.collateralisationRatio(acc...
0.4.25
/** * @notice ownershipPercentage is a high precision decimals uint based on * wallet's debtPercentage. Gives a precise amount of the feesToDistribute * for fees in the period. Precision factor is removed before results are * returned. * @dev The reported fees owing for the current period [0] are just a * running...
function _feesAndRewardsFromPeriod(uint period, uint ownershipPercentage, uint debtEntryIndex) view internal returns (uint, uint) { // If it's zero, they haven't issued, and they have no fees OR rewards. if (ownershipPercentage == 0) return (0, 0); uint debtOwnership...
0.4.25
/** * @notice A method to add a bearer to a role * @param _account The account to add as a bearer. * @param _role The role to add the bearer to. */
function addBearer(address _account, uint256 _role) external { require( _role < roles.length, "Role doesn't exist." ); require( hasRole(msg.sender, roles[_role].admin), "User can't add bearers." ); require( !hasRole(_account, _role), "Account is...
0.5.17
/** @notice Initializes TWAP start point, starts countdown to first rebase * */
function init_twap() public { require(timeOfTWAPInit == 0, "already activated"); (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); require(blockTimestamp > 0, "no trades"); blockTimestampL...
0.5.17
/** @notice Activates rebasing * @dev One way function, cannot be undone, callable by anyone */
function activate_rebasing() public { require(timeOfTWAPInit > 0, "twap wasnt intitiated, call init_twap()"); // cannot enable prior to end of rebaseDelay require(now >= timeOfTWAPInit + rebaseDelay, "!end_delay"); rebasingActive = false; // disable rebase, originally...
0.5.17
/** * @notice given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset * * @param amountIn input amount of the asset * @param reserveIn reserves of the asset being sold * @param reserveOut reserves if the asset being purchased */
function getAmountOut( uint amountIn, uint reserveIn, uint reserveOut ) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Librar...
0.5.17
/** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be a...
function getTWAP() internal returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period ...
0.5.17
/** * @notice Calculates current TWAP from uniswap * */
function getCurrentTWAP() public view returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired ...
0.5.17
/** * @return Computes in % how far off market is from peg */
function computeOffPegPerc(uint256 rate) private view returns (uint256, bool) { if (withinDeviationThreshold(rate)) { return (0, false); } // indexDelta = (rate - targetRate) / targetRate if (rate > targetRate) { return (ra...
0.5.17
// recommended fix for known attack on any ERC20
function safeApprove( address _spender, uint256 _currentValue, uint256 _value ) public returns (bool success) { // If current allowance for _spender is equal to _currentValue, then // overwrite it with _value and return true, otherwi...
0.4.25
// Ethereum Token Definition
function approveAndCall( address spender, uint256 value, bytes context ) public returns (bool success) { if ( approve(spender, value) ) { tokenRecipient recip = tokenRecipient( spender ); recip.receiveApproval( msg.sender, value, cont...
0.4.25
// Ethereum Token
function burnFrom( address from, uint256 value ) public returns (bool success) { require( balances_[from] >= value ); require( value <= allowances_[from][msg.sender] ); balances_[from] -= value; allowances_[from][msg.sender] -= value; totalSupply -= value; emit Burn( from, value ...
0.4.25
// ERC223 Transfer and invoke specified callback
function transfer( address to, uint value, bytes data, string custom_fallback ) public returns (bool success) { _transfer( msg.sender, to, value, data ); if ( isContract(to) ) { ContractReceiver rx = ContractReceiver( to ); ...
0.4.25
// ERC223 Transfer to a contract or externally-owned account
function transfer( address to, uint value, bytes data ) public returns (bool success) { if (isContract(to)) { return transferToContract( to, value, data ); } _transfer( msg.sender, to, value, data ); return true; }
0.4.25
// ERC223 Transfer to contract and invoke tokenFallback() method
function transferToContract( address to, uint value, bytes data ) private returns (bool success) { _transfer( msg.sender, to, value, data ); ContractReceiver rx = ContractReceiver(to); rx.tokenFallback( msg.sender, value, data ); return true; }
0.4.25
/** * create new game **/
function createGame (uint _gameBet, uint _endTime, string _questionText, address _officialAddress) public adminOnly payable { gameCount ++; address newGameAddress = new MajorityGame(gameCount, _gameBet, _endTime, _questionText, _officialAddress); deployedGames.push(newGameAddress); g...
0.4.25
/** * player submit their option **/
function submitChooseByFactory(address playerAddress, uint _chooseValue) public payable adminOnly notEnded withinGameTime { require(!option1List[playerAddress] && !option2List[playerAddress]); require(msg.value == gameBet); if (_chooseValue == 1) { option1List[playerAddress] = ...
0.4.25
/** * calculate the winner side * calculate the award to winner **/
function endGame() public afterGameTime { require(winnerSide == 0); finalBalance = address(this).balance; // 10% for commision uint totalAward = finalBalance * 9 / 10; uint option1Count = uint(option1AddressList.length); uint option2Count = uint(option2Address...
0.4.25
/** * send award to winner **/
function sendAward() public isEnded { require(awardCounter > 0); uint count = awardCounter; if (awardCounter > 400) { for (uint i = 0; i < 400; i++) { this.sendAwardToLastOne(); } } else { for (uint j = 0; j < count; j++) { ...
0.4.25
/** * send award to last winner of the list **/
function sendAwardToLastOne() public isEnded { require(awardCounter > 0); if(winnerSide == 1){ address(option1AddressList[awardCounter - 1]).transfer(award); }else{ address(option2AddressList[awardCounter - 1]).transfer(award); } awardCounter--; ...
0.4.25
/** @dev The constructor sets the initial balance to 30 million tokens. @dev 27 million assigned to the contract owner. @dev 3 million reserved and locked. (except bounty) @dev Holders history is updated for data integrity. @dev Burn functionality are enabled by default. */
function LWFToken() { totalSupply = 30 * (10**6) * (10**decimals); burnAllowed = true; maintenance = false; require(_setup(0x927Dc9F1520CA2237638D0D3c6910c14D9a285A8, 2700000000, false)); require(_setup(0x7AE7155fF280D5da523CDDe3855b212A8381F9E8, 30000000, false)); ...
0.4.16
/** @dev Gets the balance of the specified address at the first block minor or equal the specified block @param _owner The address to query the the balance of @param _block The block @return An uint256 representing the amount owned by the passed address at the specified block. */
function balanceAt(address _owner, uint256 _block) external constant returns (uint256 balance) { uint256 i = accounts[_owner].history.length; do { i--; } while (i > 0 && accounts[_owner].history[i].block > _block); uint256 matchingBlock = accounts[_owner].history[i].bloc...
0.4.16
/** @dev Authorized contracts can burn tokens. @param _amount Quantity of tokens to burn @return A bool set true if successful, false otherwise */
function burn(address _address, uint256 _amount) onlyBurners disabledInMaintenance external returns (bool) { require(burnAllowed); var _balance = accounts[_address].balance; accounts[_address].balance = _balance.sub(_amount); // update history with recent burn require(_u...
0.4.16
/** @dev Transfer tokens from one address to another @param _from address The address which you want to send tokens from @param _to address The address which you want to transfer to @param _amount the amount of tokens to be transferred @return A bool set true if successful, false otherwise */
function transferFrom(address _from, address _to, uint256 _amount) returns (bool) { require(!isLocked(_from)); require(_to != address(0)); var _allowance = accounts[_from].allowed[msg.sender]; // Check is not needed because sub(_allowance, _amount) will already throw if this cond...
0.4.16
/** @dev Function implementing the shared logic of 'transfer()' and 'transferFrom()' @param _from address sending tokens @param _recipient address receiving tokens @param _amount tokens to send @return A bool set true if successful, false otherwise */
function _transfer(address _from, address _recipient, uint256 _amount) internal disabledInMaintenance trackNewUsers(_recipient) returns (bool) { accounts[_from].balance = balanceOf(_from).sub(_amount); accounts[_recipient].balance = balanceOf(_recipient).add(_amount); // save this transac...
0.4.16
/// @notice Allow pre-approved user to take ownership of a dividend card. /// @param _divCardId The ID of the card that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance.
function takeOwnership(uint _divCardId) public isNotContract { address newOwner = msg.sender; address oldOwner = divCardIndexToOwner[_divCardId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approve...
0.4.24
/// For creating a dividend card
function _createDivCard(string _name, address _owner, uint _price, uint _percentIncrease) private { Card memory _divcard = Card({ name: _name, percentIncrease: _percentIncrease }); uint newCardId = divCards.push(_divcard) - 1; // It's probably never going to happen, 4 billion...
0.4.24
/// @dev Assigns ownership of a specific Card to an address.
function _transfer(address _from, address _to, uint _divCardId) private { // Since the number of cards is capped to 2^32 we can't overflow this ownershipDivCardCount[_to]++; //transfer ownership divCardIndexToOwner[_divCardId] = _to; // When creating new div cards _from is 0x0, but we...
0.4.24
/** * @dev Mints a token to an address with a tokenURI. * @param _tos address of the future owner of the token */
function mintTo(address[] calldata _tos, uint256 _amount) public onlyOwner { uint256 _mintedAmt = _totalMinted(); uint256 _mintAmt = _tos.length * _amount; require( _mintedAmt + _mintAmt <= MAX_LIMIT, "MetaMech: reached max limit" ); for (uint256 i = 0; i ...
0.8.4
/** * @dev See {IERC721-isApprovedForAll}. */
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry....
0.8.4
// Update the given pool's MVS allocation point. Can only be called by the owner.
function set( uint256 _pid, uint256 _allocPoint, uint256 _rewardEndBlock, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _all...
0.6.12
// sets inital vest amount and bool for a vested address and transfers tokens to address so they collect dividends
function airdrop(address[] calldata addresses, uint256[] calldata amounts) external onlyOwner(){ uint256 i = 0; while(i < addresses.length){ require(addresses.length == amounts.length, "Array sizes must be equal"); uint256 _amount = amounts[i] *10**18; _transfer(...
0.7.6
// TODO TEST
function setNewTerrain(uint x, uint y, bytes32 newTerrain) public xyBounded(x, y) validNewTerrain(x, y, newTerrain) payable returns (bool) { Plot storage plot = plots[x][y]; require(plot.owned); require(plot.owner == msg.sender); uint setPrice = getSetNewTerrainPrice(x, y, newTerrain); require(...
0.4.19
/** * Allows members to buy cannabis. * @param _price The total amount of ELYC tokens that should be paid. * @param _milligrams The total amount of milligrams which is being purchased * @param _vendor The vendors address * @return true if the function executes successfully, false otherwise * */
function buyCannabis(uint256 _price, uint256 _milligrams, address _vendor) public onlyMembers returns(bool) { require(_milligrams > 0 && _price > 0 && _vendor != address(0)); require(_milligrams <= getMilligramsMemberCanBuy(msg.sender)); ELYC.transferFrom(msg.sender, _vendor, _price); ...
0.4.25
/** * Allows the owner of this contract to add new members. * @param _addr The address of the new member. * @return true if the function executes successfully, false otherwise. * */
function addMember(address _addr) public onlyOwner returns(bool) { require(!addrIsMember[_addr]); addrIsMember[_addr] = true; numOfMembers += 1; memberIdByAddr[_addr] = numOfMembers; memberAddrById[numOfMembers] = _addr; emit NewMemberAdded(_addr, numOfMembers, bloc...
0.4.25