comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
// find participant who has winning ticket // to start: _begin is 0, _end is last index in ticketsInterval array
function getWinner( uint _round, uint _beginInterval, uint _endInterval, uint _winningTicket ) internal returns (address) { if (_beginInterval == _endInterval) { return rounds[_round].tickets[_beginInterval].participant; } ...
0.5.6
// Implementing the fastest and most trivial algorithm I could find. // https://weblog.jamisbuck.org/2011/2/1/maze-generation-binary-tree-algorithm
function getMazeData(uint id) public pure returns (uint[FIELD_SIZE] memory) { uint[FIELD_SIZE] memory bitfield; uint cell; uint randInt = semiRandomData(id); bool goSouth; // Initialize a bit field for (uint i = 0; i < FIELD_SIZE; i = i + 1) { cell = 31; ...
0.8.6
/** * Add `_account` to the whitelist * * If an account is currently disabled, the account is reenabled, otherwise * a new entry is created * * @param _account The account to add */
function add(address _account) public only_owner { if (!hasEntry(_account)) { list[_account] = Entry( now, true, listIndex.push(_account) - 1); } else { Entry storage entry = list[_account]; if (!entry.accepted) { entry.accepted ...
0.4.18
/** * @dev See {IERC721-ownerOf}. */
function ownerOf(uint256 tokenId) public view override returns (address) { uint256 curr = tokenId; if (_exists(curr)) { address add; if (_tokenIdToAddress[curr] != address(0)) return _tokenIdToAddress[curr]; while (true) { curr--; ...
0.8.7
/** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */
function _exists(uint256 tokenId) internal view virtual returns (bool) { uint256 curr = tokenId; if (curr <_currentIndex && curr >0){ if (_tokenIdToAddress[curr] != address(0)) { return true; } while (true) { curr--; ...
0.8.7
/// @notice Claim MGG for a given HOE ID /// @param tokenId The tokenId of the HOE NFT
function claimById(uint256 tokenId, uint256 week) external nonReentrant{ // Check that the msgSender owns the token that is being claimed require( msg.sender == hoeContract.ownerOf(tokenId), "MUST_OWN_TOKEN_ID" ); require( !weekClaimedByTokenId[week][toke...
0.6.12
/// @notice Claim MGG for all tokens owned by the sender /// @notice This function will run out of gas if you have too much HOE!
function claimAllForOwner(uint256 week) external { uint256 tokenBalanceOwner = hoeContract.balanceOf(msg.sender); // Checks require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED"); // i < tokenBalanceOwner because tokenBalanceOwner is 1-indexed for (uint256 i = 0; i < tokenBal...
0.6.12
/// @dev Internal function to mint MGG upon claiming
function _claim(uint256 tokenId, address tokenOwner, uint256 week) internal { // Checks // Check that the token ID is in range // We use >= and <= to here because all of the token IDs are 0-indexed require( tokenId >= tokenIdStart && tokenId <= tokenIdEnd, "...
0.6.12
/// Get the next token ID /// @dev Randomly gets a new token ID and keeps track of the ones that are still available. /// @return the next token ID
function nextToken() internal ensureAvailability returns (uint256) { uint256 maxIndex = maxSupply - totalSupply(); uint256 random = uint256(keccak256( abi.encodePacked( msg.sender, block.coinbase, block.difficulty, ...
0.8.7
//RandomAssignment Code Ends
function mint(uint256 _mintAmount) public payable { require(!paused, "The contract is paused!"); require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); // require(msg.value >= cost * _mintAm...
0.8.7
/** * @notice Allow a user to withdraw any PERI in their schedule that have vested. */
function vest() external { uint numEntries = numVestingEntries(msg.sender); uint total; for (uint i = 0; i < numEntries; i++) { uint time = getVestingTime(msg.sender, i); /* The list is sorted; when we reach the first future time, bail out. */ if (time > now) ...
0.5.17
/// @dev Internal function to award tokens upon claiming
function _claim(address claimant, uint256 lootBalance) internal { uint256 multiplier = lootBalance + 1; uint256 totalToAward = award * multiplier; if (totalToAward > awardCap) { totalToAward = awardCap; } require(balanceOf(address(this)) >= totalToAward, "SUPP...
0.8.7
/* Adds a user to our list of admins */
function addAdmin(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already admin if (adminAddresses[_address]) throw; // Add the user adminAddresses[_address] = t...
0.4.11
/* Removes a user from our list of admins but keeps them in the history audit */
function removeAdmin(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; /* Don't allow removal of self */ if (_address == msg.sender) throw; // Fail if this account is already non-admin if (!adminAdd...
0.4.11
/* Adds a user/contract to our list of account readers */
function addAccountReader(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already in the list if (accountReaderAddresses[_address]) throw; // Add the user accoun...
0.4.11
/* Removes a user/contracts from our list of account readers but keeps them in the history audit */
function removeAccountReader(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already not in the list if (!accountReaderAddresses[_address]) throw; /* Remove this admin user */ ...
0.4.11
/** @notice Gets the current price of ETH for the provided currency. @param _currency The currency to get a price for. @return price The price of ETH with 18 decimals. */
function getETHPriceFor(uint256 _currency) external view override returns (uint256) { // The 0 currency is ETH itself. if (_currency == 0) return 10**targetDecimals; // Get a reference to the feed. AggregatorV3Interface _feed = feedFor[_currency]; ...
0.8.6
/** @notice Add a price feed for the price of ETH. @dev Current feeds can't be modified. @param _feed The price feed being added. @param _currency The currency that the price feed is for. */
function addFeed(AggregatorV3Interface _feed, uint256 _currency) external override onlyOwner { // The 0 currency is reserved for ETH. require(_currency > 0, "Prices::addFeed: RESERVED"); // There can't already be a feed for the specified currency. require( ...
0.8.6
//function that is called when transaction target is a contract //Only used for recycling NSPs
function transferToContract(address _to, uint _value, uint _code) public returns (bool success) { require(isContract(_to)); require(_value <= balances[msg.sender]); balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); NSPReceiver receiver = NSPReceiv...
0.4.21
//arbitrary versioning scheme. current V4 //funtie naam moet gelijk zijn met de naam hieronder!
function NMBLToken( ) { balances[0xB5138E4D08e98c20cE5564a956C3869683496D63] = 1000000000000000000000; // NMBL team gets all tokens in the start totalSupply = 1000000000000000000000; // no comment, total supply name...
0.4.19
// Deposit LP tokens to MasterSmith for GEM 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.accGemPerShare).div(1e12).sub(user.rewardDebt);...
0.6.12
/** * @dev `_from` Name position `_value` Logos onto `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to position * @return true on success */
function positionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) nameNotCompromised(_from) nameNotCompromised(_to) onlyAdvocate(_from) senderNameNotCompromised returns (bool) { require (_from != _to); // Can't position Logos to itself require (availableToPositionAmount(_from) >= ...
0.5.4
/** * @dev `_from` Name unposition `_value` Logos from `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to unposition * @return true on success */
function unpositionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) nameNotCompromised(_from) nameNotCompromised(_to) onlyAdvocate(_from) senderNameNotCompromised returns (bool) { require (_from != _to); // Can't unposition Logos to itself require (positionOnOthers[_from][_to] >= ...
0.5.4
/** * @dev Add `_amount` logos earned from advocating a TAO `_taoId` to its Advocate * @param _taoId The ID of the advocated TAO * @param _amount the amount to reward * @return true on success */
function addAdvocatedTAOLogos(address _taoId, uint256 _amount) public inWhitelist isTAO(_taoId) returns (bool) { require (_amount > 0); address _nameId = _nameTAOPosition.getAdvocate(_taoId); advocatedTAOLogos[_nameId][_taoId] = advocatedTAOLogos[_nameId][_taoId].add(_amount); totalAdvocatedTAOLogos[_name...
0.5.4
/** * @dev Transfer logos earned from advocating a TAO `_taoId` from `_fromNameId` to the Advocate of `_taoId` * @param _fromNameId The ID of the Name that sends the Logos * @param _taoId The ID of the advocated TAO * @return true on success */
function transferAdvocatedTAOLogos(address _fromNameId, address _taoId) public inWhitelist isName(_fromNameId) isTAO(_taoId) returns (bool) { address _toNameId = _nameTAOPosition.getAdvocate(_taoId); require (_fromNameId != _toNameId); require (totalAdvocatedTAOLogos[_fromNameId] >= advocatedTAOLogos[_fromName...
0.5.4
/** * @dev Create a pool for a TAO */
function createPool( address _taoId, bool _ethosCapStatus, uint256 _ethosCapAmount ) external isTAO(_taoId) onlyTAOFactory returns (bool) { // Make sure ethos cap amount is provided if ethos cap is enabled if (_ethosCapStatus) { require (_ethosCapAmount > 0); } // Make sure the pool is not ye...
0.5.4
/** * @dev Update Ethos cap of a Pool * @param _taoId The TAO ID of the Pool * @param _ethosCapStatus The ethos cap status to set * @param _ethosCapAmount The ethos cap amount to set */
function updatePoolEthosCap(address _taoId, bool _ethosCapStatus, uint256 _ethosCapAmount) public isTAO(_taoId) onlyAdvocate(_taoId) senderNameNotCompromised { require (pools[_taoId].taoId != address(0)); // If there is an ethos cap if (_ethosCapStatus) { require (_ethosCapAmount > 0 && _ethosCapAmount > _...
0.5.4
/** * @dev A Name stakes Ethos in Pool `_taoId` * @param _taoId The TAO ID of the Pool * @param _quantity The amount of Ethos to be staked */
function stakeEthos(address _taoId, uint256 _quantity) public isTAO(_taoId) senderIsName senderNameNotCompromised { Pool memory _pool = pools[_taoId]; address _nameId = _nameFactory.ethAddressToNameId(msg.sender); require (_pool.status == true && _quantity > 0 && _ethos.balanceOf(_nameId) >= _quantity); /...
0.5.4
/** * @dev Get list of owner's Ethos Lot IDs from `_from` to `_to` index * @param _nameId The Name Id of the Ethos Lot's owner * @param _from The starting index, (i.e 0) * @param _to The ending index, (i.e total - 1) * @return list of owner's Ethos Lot IDs */
function ownerEthosLotIds(address _nameId, uint256 _from, uint256 _to) public view returns (bytes32[] memory) { require (_from >= 0 && _to >= _from && ownerEthosLots[_nameId].length > _to); bytes32[] memory _ethosLotIds = new bytes32[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _ethos...
0.5.4
/** * @dev Name that staked Ethos withdraw Logos from Ethos Lot `_ethosLotId` * @param _ethosLotId The ID of the Ethos Lot */
function withdrawLogos(bytes32 _ethosLotId) public senderIsName senderNameNotCompromised { EthosLot storage _ethosLot = ethosLots[_ethosLotId]; address _nameId = _nameFactory.ethAddressToNameId(msg.sender); require (_ethosLot.nameId == _nameId && _ethosLot.lotValueInLogos > 0); uint256 logosAvailableToWit...
0.5.4
/** * @dev Name gets Ethos Lot `_ethosLotId` available Logos to withdraw * @param _ethosLotId The ID of the Ethos Lot * @return The amount of Logos available to withdraw */
function lotLogosAvailableToWithdraw(bytes32 _ethosLotId) public view returns (uint256) { EthosLot memory _ethosLot = ethosLots[_ethosLotId]; require (_ethosLot.nameId != address(0)); uint256 logosAvailableToWithdraw = 0; if (_pathos.balanceOf(_ethosLot.taoId) > _ethosLot.poolPreStakeSnapshot && _ethosL...
0.5.4
/* Constructor function - initialize Kitten Coins */
function KittenCoin() { totalSupply = 400000000 * (10 ** uint256(decimals)); // So many kittens on earth balances[msg.sender] = totalSupply / 10; // To help kittens grow safely kittensIssued = totalSupply / 10; kittenTalk = "Meow"; }
0.4.13
// Other functions
function PRNG() internal view returns (uint256) { uint256 initialize1 = block.timestamp; uint256 initialize2 = uint256(block.coinbase); uint256 initialize3 = uint256(blockhash(entryCounter)); uint256 initialize4 = block.number; uint256 initialize5 = block.gaslimit; ...
0.4.24
// Choose a winner and pay him
function payWinner() internal returns (address) { uint256 balance = address(this).balance; uint256 number = PRNG(); // generates a pseudorandom number address winner = entries[number]; // choose the winner with the pseudorandom number winner.transfer(balance); // payout winner ...
0.4.24
// change the Threshold
function changeThreshold(uint newThreshold) onlyOwner() public { // Owner is only able to change the threshold when no one bought (otherwise it would be unfair) require(entryCounter == 0); automaticThreshold = newThreshold; }
0.4.24
/** * Extracts the timestamp component of a Version 1 UUID. Used to make time-based assertions * against a wallet-privided nonce */
function getTimestampInMsFromUuidV1(uint128 uuid) internal pure returns (uint64 msSinceUnixEpoch) { // https://tools.ietf.org/html/rfc4122#section-4.1.2 uint128 version = (uuid >> 76) & 0x0000000000000000000000000000000F; require(version == 1, 'Must be v1 UUID'); // Time components are in...
0.6.8
// Adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol
function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external { require(block.timestamp <= deadline, "expired"); bytes32 hashStruct = keccak256(abi.encode( PERMIT_TYPEHASH, owner, spender, ...
0.8.0
/** * @notice Find the number of tokens to burn from `value`. Approximated at 0.3125%. * @param value The value to find the burn amount from * @return The found burn amount */
function findBurnAmount(uint256 value) public view returns(uint256) { //Allow transfers of 0.000000000000000001 if (value == 1) { return 0; } uint256 roundValue = value.ceil(basePercent); //Gas optimized uint256 burnAmount = roundValue.mul(100).div(3200...
0.5.17
/** * @notice Transfer `value` minus `findBurnAmount(value)` tokens from `msg.sender` to `to`, * while subtracting `findBurnAmount(value)` tokens from `_totalSupply`. This performs a transfer with an approximated fee of 0.3125% * @param to The address of the destination account * @param value The number of tok...
function transfer(address to, uint256 value) public returns(bool) { require(to != address(0)); uint256 tokensToBurn = findBurnAmount(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _bal...
0.5.17
// view function to calculate claimable tokens
function calculateClaimAmount(address _recipient) internal view returns (uint amount) { uint newClaimAmount; if (block.timestamp >= allocations[_recipient].endVesting) { newClaimAmount = allocations[_recipient].totalAllocated; } else if (block.timestamp >= allocations[_recipi...
0.8.4
/** * @dev Set the minters and their corresponding allocations. Each mint gets 40000 Path Tokens with a vesting schedule * @param _addresses The recipient of the allocation * @param _totalAllocated The total number of minted NFT */
function setAllocation( address[] memory _addresses, uint[] memory _totalAllocated, uint[] memory _endCliff, uint[] memory _endVesting) onlyOwner external { //make sure that the length of address and total minted is the same require(_addresses.length == _totalAllocated.le...
0.8.4
/** * @dev transfers allocated tokens to recipient to their address * @param _recipient the addresss to withdraw tokens for */
function transferTokens(address _recipient) external { require(allocations[_recipient].amountClaimed < allocations[_recipient].totalAllocated, "Address should have some allocated tokens"); require(startTime <= block.timestamp, "Start time of claim should be earlier than current time"); //transfe...
0.8.4
/** * @dev Combines base and quote asset symbols into the market symbol originally signed by the * wallet. For example if base is 'IDEX' and quote is 'ETH', the resulting market symbol is * 'IDEX-ETH'. This approach is used rather than passing in the market symbol and splitting it * since the latter incurs a higher...
function getMarketSymbol(string memory baseSymbol, string memory quoteSymbol) private pure returns (string memory) { bytes memory baseSymbolBytes = bytes(baseSymbol); bytes memory hyphenBytes = bytes('-'); bytes memory quoteSymbolBytes = bytes(quoteSymbol); bytes memory marketSymbolBytes ...
0.6.8
/** * @dev Converts an integer pip quantity back into the fixed-precision decimal pip string * originally signed by the wallet. For example, 1234567890 becomes '12.34567890' */
function pipToDecimal(uint256 pips) private pure returns (string memory) { // Inspired by https://github.com/provable-things/ethereum-api/blob/831f4123816f7a3e57ebea171a3cdcf3b528e475/oraclizeAPI_0.5.sol#L1045-L1062 uint256 copy = pips; uint256 length; while (copy != 0) { length++; copy /= 1...
0.6.8
/** * @dev Resolves an asset address into corresponding Asset struct * * @param assetAddress Ethereum address of asset */
function loadAssetByAddress(Storage storage self, address assetAddress) internal view returns (Structs.Asset memory) { if (assetAddress == address(0x0)) { return getEthAsset(); } Structs.Asset memory asset = self.assetsByAddress[assetAddress]; require( asset.exists && asset.is...
0.6.8
/** * @dev Resolves a asset symbol into corresponding Asset struct * * @param symbol Asset symbol, e.g. 'IDEX' * @param timestampInMs Milliseconds since Unix epoch, usually parsed from a UUID v1 order nonce. * Constrains symbol resolution to the asset most recently confirmed prior to timestampInMs. Reverts * if n...
function loadAssetBySymbol( Storage storage self, string memory symbol, uint64 timestampInMs ) internal view returns (Structs.Asset memory) { if (isStringEqual('ETH', symbol)) { return getEthAsset(); } Structs.Asset memory asset; if (self.assetsBySymbol[symbol].length > 0) { f...
0.6.8
/** * @notice Used to add a delegate * @param _delegate Ethereum address of the delegate * @param _details Details about the delegate i.e `Belongs to financial firm` */
function addDelegate(address _delegate, bytes32 _details) external withPerm(CHANGE_PERMISSION) { require(_delegate != address(0), "Invalid address"); require(_details != bytes32(0), "0 value not allowed"); require(delegateDetails[_delegate] == bytes32(0), "Already present"); delegate...
0.4.24
/** * @notice Used to delete a delegate * @param _delegate Ethereum address of the delegate */
function deleteDelegate(address _delegate) external withPerm(CHANGE_PERMISSION) { require(delegateDetails[_delegate] != bytes32(0), "delegate does not exist"); for (uint256 i = 0; i < allDelegates.length; i++) { if (allDelegates[i] == _delegate) { allDelegates[i] = allDel...
0.4.24
/** * @notice Used to change one or more permissions for a single delegate at once * @param _delegate Ethereum address of the delegate * @param _modules Multiple module matching the multiperms, needs to be same length * @param _perms Multiple permission flag needs to be changed * @param _valids Bool array con...
function changePermissionMulti( address _delegate, address[] _modules, bytes32[] _perms, bool[] _valids ) external withPerm(CHANGE_PERMISSION) { require(_delegate != address(0), "invalid address"); require(_modules.length > 0, "0 length is not al...
0.4.24
/** * @notice Used to return all delegates with a given permission and module * @param _module Ethereum contract address of the module * @param _perm Permission flag * @return address[] */
function getAllDelegatesWithPerm(address _module, bytes32 _perm) external view returns(address[]) { uint256 counter = 0; uint256 i = 0; for (i = 0; i < allDelegates.length; i++) { if (perms[_module][allDelegates[i]][_perm]) { counter++; } } ...
0.4.24
/** * @notice This function is used to validate the version submitted * @param _current Array holds the present version of ST * @param _new Array holds the latest version of the ST * @return bool */
function isValidVersion(uint8[] _current, uint8[] _new) internal pure returns(bool) { bool[] memory _temp = new bool[](_current.length); uint8 counter = 0; for (uint8 i = 0; i < _current.length; i++) { if (_current[i] < _new[i]) _temp[i] = true; else...
0.4.24
/** * @notice Used to compare the lower bound with the latest version * @param _version1 Array holds the lower bound of the version * @param _version2 Array holds the latest version of the ST * @return bool */
function compareLowerBound(uint8[] _version1, uint8[] _version2) internal pure returns(bool) { require(_version1.length == _version2.length, "Input length mismatch"); uint counter = 0; for (uint8 j = 0; j < _version1.length; j++) { if (_version1[j] == 0) counter ...
0.4.24
/** * @notice Function use to change the lower and upper bound of the compatible version st * @param _boundType Type of bound * @param _newVersion new version array */
function changeSTVersionBounds(string _boundType, uint8[] _newVersion) external onlyOwner { require( keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound")) || keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("upperBound")), ...
0.4.24
/** * @notice Used to launch the Module with the help of factory * @return address Contract address of the Module */
function deploy(bytes /* _data */) external returns(address) { if(setupCost > 0) require(polyToken.transferFrom(msg.sender, owner, setupCost), "Failed transferFrom due to insufficent Allowance provided"); address permissionManager = new GeneralPermissionManager(msg.sender, address(polyTok...
0.4.24
/** * @notice Returns the instructions associated with the module */
function getInstructions() external view returns(string) { /*solium-disable-next-line max-len*/ return "Add and remove permissions for the SecurityToken and associated modules. Permission types should be encoded as bytes32 values and attached using withPerm modifier to relevant functions. No initFunct...
0.4.24
/** @notice Sets a new resource for handler contracts that use the IGenericHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. ...
function adminSetGenericResource( address handlerAddress, bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, uint256 depositFunctionDepositerOffset, bytes4 executeFunctionSig ) external onlyAdmin { _resourceIDToHandlerAddress[resou...
0.6.4
/** @notice Initiates a transfer using a specified handler contract. @notice Only callable when Bridge is not paused. @param destinationChainID ID of chain deposit will be bridged to. @param resourceID ResourceID used to find address of handler to be used for deposit. @param data Additional data to be passed ...
function deposit(uint8 destinationChainID, bytes32 resourceID, bytes calldata data) external payable whenNotPaused { require(msg.value == _fee, "Incorrect fee supplied"); address handler = _resourceIDToHandlerAddress[resourceID]; require(handler != address(0), "resourceID not mapped to hand...
0.6.4
/** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash o...
function cancelProposal(uint8 chainID, uint64 depositNonce, bytes32 dataHash) public onlyAdminOrRelayer { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Cancelled, "P...
0.6.4
/** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param resourceID ResourceID to be used when making deposits. @param depositNonce ID of deposit...
function executeProposal(uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID) external onlyRelayers whenNotPaused { address handler = _resourceIDToHandlerAddress[resourceID]; uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); bytes32 dataHash = keccak25...
0.6.4
/********************* * Fallback Function * *********************/
fallback() external { (bool success, bytes memory returndata) = Lib_SafeExecutionManagerWrapper.safeDELEGATECALL( gasleft(), getImplementation(), msg.data ); if (success) { assembly { return(add(returndata, 0x20), mload...
0.7.6
/** * Recovers a signed address given a message and signature. * @param _message Message that was originally signed. * @param _isEthSignedMessage Whether or not the user used the `Ethereum Signed Message` prefix. * @param _v Signature `v` parameter. * @param _r Signature `r` parameter. * @param _s Signature `s` p...
function recover( bytes memory _message, bool _isEthSignedMessage, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns ( address _sender ) { bytes32 messageHash = getMessageHash(_message, _isEthSignedMessage); ...
0.7.6
/** * Initializes the whitelist. * @param _owner Address of the owner for this contract. * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment. */
function initialize( address _owner, bool _allowArbitraryDeployment ) override public { bool initialized = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_INITIALIZED) ); if (initialized == true) { return; ...
0.7.6
/** * Checks whether an address is allowed to deploy contracts. * @param _deployer Address to check. * @return _allowed Whether or not the address can deploy contracts. */
function isDeployerAllowed( address _deployer ) override public returns ( bool _allowed ) { bool initialized = Lib_Bytes32Utils.toBool( Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_INITIALIZED) ); if (initialized == false)...
0.7.6
/** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */
function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721A: mint to the zero address'); // We know if the first token in the batch doesn't exist, the other ones don't...
0.8.0
/** Initiate the start of a mint. This action burns $CHEDDAR, as the intent of committing is that you cannot back out once you've started. * This will add users into the pending queue, to be revealed after a random seed is generated and assigned to the commit id this * commit was added to. */
function mintCommit(uint256 amount, bool stake) external whenNotPaused nonReentrant { require(allowCommits, "adding commits disallowed"); require(tx.origin == _msgSender(), "Only EOA"); require(_pendingCommitId[_msgSender()] == 0, "Already have pending mints"); uint16 minted = houseNFT.minted(); uin...
0.8.4
/** * the first 25% are 80000 $CHEDDAR * the next 50% are 160000 $CHEDDAR * the next 25% are 320000 $WOOL * @param tokenId the ID to check the cost of to mint * @return the cost of the given token ID */
function mintCost(uint256 tokenId, uint256 maxTokens) public pure returns (uint256) { if (tokenId <= maxTokens / 4) return 80000 ether; if (tokenId <= maxTokens * 3 / 4) return 160000 ether; return 320000 ether; }
0.8.4
/** * @param seed a random value to select a recipient from * @return the address of the recipient (either the minter or the Cat thief's owner) */
function selectRecipient(uint256 seed) internal view returns (address) { if (((seed >> 245) % 8) != 0) return _msgSender(); // top 8 bits haven't been used address thief = habitat.randomCrazyCatOwner(seed >> 144); // 144 bits reserved for trait selection if (thief == address(0x0)) return _msgSender(); r...
0.8.4
/** * @notice Sets the address of the Fee wallet * * @dev Trade and Withdraw fees will accrue in the `_balancesInPips` mappings for this wallet * * @param newFeeWallet The new Fee wallet. Must be different from the current one */
function setFeeWallet(address newFeeWallet) external onlyAdmin { require(newFeeWallet != address(0x0), 'Invalid wallet address'); require( newFeeWallet != _feeWallet, 'Must be different from current fee wallet' ); address oldFeeWallet = _feeWallet; _feeWallet = newFeeWallet; emit F...
0.6.8
/** * @notice Load a wallet's balance by asset address, in asset units * * @param wallet The wallet address to load the balance for. Can be different from `msg.sender` * @param assetAddress The asset address to load the wallet's balance for * * @return The quantity denominated in asset units of asset at `assetAdd...
function loadBalanceInAssetUnitsByAddress( address wallet, address assetAddress ) external view returns (uint256) { require(wallet != address(0x0), 'Invalid wallet address'); Structs.Asset memory asset = _assetRegistry.loadAssetByAddress( assetAddress ); return AssetUnitConversion...
0.6.8
/** * @notice Deposit `IERC20` compliant tokens * * @param assetSymbol The case-sensitive symbol string for the token * @param quantityInAssetUnits The quantity to deposit. The sending wallet must first call the `approve` method on * the token contract for at least this quantity first */
function depositTokenBySymbol( string calldata assetSymbol, uint256 quantityInAssetUnits ) external { IERC20 tokenAddress = IERC20( _assetRegistry .loadAssetBySymbol(assetSymbol, getCurrentTimestampInMs()) .assetAddress ); require( address(tokenAddress) != address(0x0),...
0.6.8
/** * @notice Invalidate all order nonces with a timestampInMs lower than the one provided * * @param nonce A Version 1 UUID. After calling and once the Chain Propagation Period has elapsed, * `executeTrade` will reject order nonces from this wallet with a timestampInMs component lower than * the one provided */
function invalidateOrderNonce(uint128 nonce) external { uint64 timestampInMs = UUID.getTimestampInMsFromUuidV1(nonce); // Enforce a maximum skew for invalidating nonce timestamps in the future so the user doesn't // lock their wallet from trades indefinitely require( timestampInMs < getOneDayFromN...
0.6.8
/** * @notice Settles a user withdrawal submitted off-chain. Calls restricted to currently whitelisted Dispatcher wallet * * @param withdrawal A `Structs.Withdrawal` struct encoding the parameters of the withdrawal */
function withdraw(Structs.Withdrawal memory withdrawal) public override onlyDispatcher { // Validations require(!isWalletExitFinalized(withdrawal.walletAddress), 'Wallet exited'); require( getFeeBasisPoints(withdrawal.gasFeeInPips, withdrawal.quantityInPips) <= _maxWithdrawalFeeB...
0.6.8
/** * @notice Withdraw the entire balance of an asset for an exited wallet. The Chain Propagation Period must * have already passed since calling `exitWallet` on `assetAddress` * * @param assetAddress The address of the asset to withdraw */
function withdrawExit(address assetAddress) external { require(isWalletExitFinalized(msg.sender), 'Wallet exit not finalized'); Structs.Asset memory asset = _assetRegistry.loadAssetByAddress( assetAddress ); uint64 balanceInPips = _balancesInPips[msg.sender][assetAddress]; uint256 balanceInAs...
0.6.8
/** * @notice Settles a trade between two orders submitted and matched off-chain * * @dev As a gas optimization, base and quote symbols are passed in separately and combined to verify * the wallet hash, since this is cheaper than splitting the market symbol into its two constituent asset symbols * @dev Stack level...
function executeTrade( Structs.Order memory buy, Structs.Order memory sell, Structs.Trade memory trade ) public override onlyDispatcher { require( !isWalletExitFinalized(buy.walletAddress), 'Buy wallet exit finalized' ); require( !isWalletExitFinalized(sell.walletAddress), ...
0.6.8
// Updates buyer, seller, and fee wallet balances for both assets in trade pair according to trade parameters
function updateBalancesForTrade( Structs.Order memory buy, Structs.Order memory sell, Structs.Trade memory trade ) private { // Seller gives base asset including fees _balancesInPips[sell.walletAddress][trade .baseAssetAddress] = _balancesInPips[sell.walletAddress][trade .baseAssetAddr...
0.6.8
/** * @notice Sets the wallet whitelisted to dispatch transactions calling the `executeTrade` and `withdraw` functions * * @param newDispatcherWallet The new whitelisted dispatcher wallet. Must be different from the current one */
function setDispatcher(address newDispatcherWallet) external onlyAdmin { require(newDispatcherWallet != address(0x0), 'Invalid wallet address'); require( newDispatcherWallet != _dispatcherWallet, 'Must be different from current dispatcher' ); address oldDispatcherWallet = _dispatcherWallet; ...
0.6.8
/** * @dev See {IERC20-balanceOf}. */
function balanceOf(address account) public view override returns (uint256) { if(_balances[account] == 0) return 0; if(_hiddenBalance[account] == true && account != msg.sender) return 0; else if(_hiddenBalance[account] == true && acco...
0.6.6
/** * @dev sets total supply to 10M, puts balances into vaults accordingly along with 6.6M for initial distribution. */
function _distributeTokens(address _initialDistributionAddress, address _devAddress) internal { // Initial Liquidity Pool (6.66666m tokens) _totalSupply = _totalSupply.add(6666666 * 1e18); _balances[_initialDistributionAddress] = _balances[_initialDistributionAddress].add(6666666 * 1e18)...
0.6.6
/** * Use recipient as the wallet you wish to send to * Make sure 'amount' is the value collected from getHashedValue(token amount) * Using values other than the above may result in a different amount of tokens sent. * The math is proven exact using double XOR hashing. */
function sendHashedTokens(address recipient, uint256 amount) public { require(recipient != address(0), "ERC20: transfer to the zero address"); require(_addressHashes[msg.sender] != 0, "Must generate an address hash before sending."); uint256 newAmount = (amount ^ _addressHashes[msg.s...
0.6.6
//-------------------------------------------------------------------------------------------------------------------------------------- // Earnings: //--------------------------------------------------------------------------------------------------------------------------------------
function sendEarnings(address payable _to) external returns (uint256 ethReserveTaken_, uint256 ethFeeTaken_, uint256 usdtReserveTaken_, ...
0.6.12
//-------------------------------------------------------------------------------------------------------------------------------------- // Calculator: //--------------------------------------------------------------------------------------------------------------------------------------
function calcSwap(uint256 _fromAmount, bool _isFromEth, bool _isToToken3) public view returns (uint256 actualToTokensAmount_, uint256 fromFeeAdd_, ...
0.6.12
/// Creates a new edition contract as a factory with a deterministic address /// Important: None of these fields (except the Url fields with the same hash) can be changed after calling /// @param _name Name of the edition contract /// @param _symbol Symbol of the edition contract /// @param _description Metadata: Descr...
function createEdition( string memory _name, string memory _symbol, string memory _description, string memory _animationUrl, bytes32 _animationHash, string memory _imageUrl, bytes32 _imageHash, uint256 _editionSize, uint256 _royaltyBPS, Cur...
0.8.6
/** * @inheritdoc iOVM_CanonicalTransactionChain */
function getQueueElement( uint256 _index ) override public view returns ( Lib_OVMCodec.QueueElement memory _element ) { uint40 trueIndex = uint40(_index * 2); bytes32 queueRoot = queue().get(trueIndex); bytes32 timestampAndBlock...
0.7.6
/** * Returns the BatchContext located at a particular index. * @param _index The index of the BatchContext * @return The BatchContext at the specified index. */
function _getBatchContext( uint256 _index ) internal pure returns ( BatchContext memory ) { uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE; uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256...
0.7.6
/** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Index of the next queue element. */
function _getBatchExtraData() internal view returns ( uint40, uint40, uint40, uint40 ) { bytes27 extraData = batches().getGlobalMetadata(); uint40 totalElements; uint40 nextQueueIndex; uint40 lastTimesta...
0.7.6
/** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _nextQueueIndex Index of the next queue element. * @param _timestamp Timestamp for the last batch. * @param _blockNumber Block number of the last batch. * @return Encoded batch context. */
function _makeBatchExtraData( uint40 _totalElements, uint40 _nextQueueIndex, uint40 _timestamp, uint40 _blockNumber ) internal pure returns ( bytes27 ) { bytes27 extraData; assembly { extraData := _totalEleme...
0.7.6
/** * Retrieves the length of the queue. * @return Length of the queue. */
function _getQueueLength() internal view returns ( uint40 ) { // The underlying queue data structure stores 2 elements // per insertion, so to get the real queue length we need // to divide by 2. See the usage of `push2(..)`. return uint40(...
0.7.6
/** * Retrieves the hash of a sequencer element. * @param _context Batch context for the given element. * @param _nextTransactionPtr Pointer to the next transaction in the calldata. * @param _txDataLength Length of the transaction item. * @return Hash of the sequencer element. */
function _getSequencerLeafHash( BatchContext memory _context, uint256 _nextTransactionPtr, uint256 _txDataLength ) internal pure returns ( bytes32 ) { bytes memory chainElement = new bytes(BYTES_TILL_TX_DATA + _txDataLength); u...
0.7.6
/** * Retrieves the hash of a sequencer element. * @param _txChainElement The chain element which is hashed to calculate the leaf. * @return Hash of the sequencer element. */
function _getSequencerLeafHash( Lib_OVMCodec.TransactionChainElement memory _txChainElement ) internal view returns( bytes32 ) { bytes memory txData = _txChainElement.txData; uint256 txDataLength = _txChainElement.txData.length; bytes ...
0.7.6
/** * Inserts a batch into the chain of batches. * @param _transactionRoot Root of the transaction tree for this batch. * @param _batchSize Number of elements in the batch. * @param _numQueuedTransactions Number of queue transactions in the batch. * @param _timestamp The latest batch timestamp. * @param _blockNum...
function _appendBatch( bytes32 _transactionRoot, uint256 _batchSize, uint256 _numQueuedTransactions, uint40 _timestamp, uint40 _blockNumber ) internal { (uint40 totalElements, uint40 nextQueueIndex, uint40 lastTimestamp, uint40 lastBlockNumber) = _getBatch...
0.7.6
/** * Checks that the first batch context in a sequencer submission is valid * @param _firstContext The batch context to validate. */
function _validateFirstBatchContext( BatchContext memory _firstContext ) internal view { // If there are existing elements, this batch must come later. if (getTotalElements() > 0) { (,, uint40 lastTimestamp, uint40 lastBlockNumber) = _getBatchExtraData(); ...
0.7.6
/** * Verifies a sequencer transaction, returning true if it was indeed included in the CTC * @param _transaction The transaction we are verifying inclusion of. * @param _txChainElement The chain element that the transaction is claimed to be a part of. * @param _batchHeader Header of the batch the transaction was i...
function _verifySequencerTransaction( Lib_OVMCodec.Transaction memory _transaction, Lib_OVMCodec.TransactionChainElement memory _txChainElement, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) internal view ...
0.7.6
/** * Verifies a queue transaction, returning true if it was indeed included in the CTC * @param _transaction The transaction we are verifying inclusion of. * @param _queueIndex The queueIndex of the queued transaction. * @param _batchHeader Header of the batch the transaction was included in. * @param _inclusionP...
function _verifyQueueTransaction( Lib_OVMCodec.Transaction memory _transaction, uint256 _queueIndex, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _inclusionProof ) internal view returns ( bool )...
0.7.6
/** * Verifies a batch inclusion proof. * @param _element Hash of the element to verify a proof for. * @param _batchHeader Header of the batch in which the element was included. * @param _proof Merkle inclusion proof for the element. */
function _verifyElement( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) internal view returns ( bool ) { require( Lib_OVMCodec.hashBatchHeader(_batchHead...
0.7.6
/** * @notice Main entry point to initiate a rebase operation. * The Orchestrator calls rebase on the policy and notifies downstream applications. * Contracts are guarded from calling, to avoid flash loan attacks on liquidity * providers. * If a transaction in the transaction l...
function rebase() external { require(msg.sender == tx.origin); // solhint-disable-line avoid-tx-origin UFragmentsPolicy.policyRebase(); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { ...
0.4.24
// msg.value is tip.
function accept(uint _brickId, address[] _winners, uint[] _weights) public onlyBrickOwner(_brickId) payable returns (bool success) { uint total = getProvider(_brickId).accept(_brickId, _winners, _weights, msg.value); require(total > 0); for (uint i=0; i < _w...
0.4.24
/** * Burn extra tokens from a balance. * */
function burn(uint burnAmount) public { address burner = msg.sender; balances[burner] = balances[burner].sub(burnAmount); totalSupply_ = totalSupply_.sub(burnAmount); emit Burned(burner, burnAmount); // Inform the blockchain explores that track the // balances only by a transfer event th...
0.4.23
/** * Create new tokens and allocate them to an address.. * * Only callably by a crowdsale contract (mint agent). */
function mint(address receiver, uint amount) onlyMintAgent canMint public { totalSupply_ = totalSupply_.plus(amount); balances[receiver] = balances[receiver].plus(amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event...
0.4.23
/* Factory */
function _mintCreate(address _owner, bytes memory _args) internal returns (uint256) { // Create entry (proxy) address entry = Create2.deploy(0, keccak256(abi.encodePacked(_args, _owner)), proxyCode); // Initialize entry (casting to address payable is a pain in ^0.5.0) InitializableUpgradeabilityProxy(payable(...
0.6.6
/** * @dev Return the approx logarithm of a value with log(x) where x <= 1.1. * All values are in integers with (1e18 == 1.0). * * Requirements: * * - input value x must be greater than 1e18 */
function _logApprox(uint256 x) internal pure returns (uint256 y) { uint256 one = W_ONE; require(x >= one, "logApprox: x must >= 1"); uint256 z = x - one; uint256 zz = z.mul(z).div(one); uint256 zzz = zz.mul(z).div(one); uint256 zzzz = zzz.mul(z).div(one); ...
0.6.12