comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @dev Use only for some special tokens */
function manualApproveAllowance( IERC20[] calldata tokens, address[] calldata spenders, uint256 allowance ) external onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { for (uint256 j = 0; j < spenders.length; j++) { tokens[i].safeApprove(spen...
0.6.12
/** * @dev Add liquidity to Kyber dmm pool, support adding to new pool or an existing pool */
function _addLiquidityToDmmPool( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, PoolInfo memory poolInfo, uint256 deadline ) internal returns ( ...
0.6.12
/** * @dev Add liquidity to an existing pool, and return back tokens to users if any */
function _addLiquidityExistingPool( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address dmmPool, uint256 deadline ) internal returns ( u...
0.6.12
/** * @dev Add liquidity to a new pool, and return back tokens to users if any */
function _addLiquidityNewPool( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, uint32 amps, uint256 deadline ) internal returns ( uint256 am...
0.6.12
/** * @dev Re-write remove liquidity function from Uniswap */
function _removeUniLiquidity( address pair, address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline ) internal { require(deadline >= block.timestamp, "Migratior: EXPIRED"); IERC20(pa...
0.6.12
/** * @dev Copy logic of sort token from Uniswap lib */
function _sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "Migrator: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 !=...
0.6.12
// DTHPool(address _daoAddress, address _delegate, uint _maxTimeBlocked, string _delegateName, string _delegateUrl, string _tokenSymbol);
function DTHPool( address _daoAddress, address _delegate, uint _maxTimeBlocked, string _delegateName, string _delegateUrl, string _tokenSymbol ) { daoAddress = _daoAddress; delegate = _delegate; delegateUrl = _delegateUrl; ma...
0.3.4
//internal func
function burn (uint256 amount) internal { SafeMath.assert(amount >= 100000000000); if (amount >= 100000000000) { uint256 _value = amount / 100000000000; uint256 _tmp = _value * 100000000000; SafeMath.assert(_tmp == amount); vips[msg.sender] += a...
0.4.21
//transfer shares
function transferShares(address _to, uint _value){ SafeMath.assert(vips[msg.sender] >= _value && _value > 0); var _skey = msg.sender; uint _svalue = 0; var _tkey = _to; uint _tvalue = 0; for (var i = IterableMapping.iterate_start(data); IterableMapping.iterate_valid...
0.4.21
//only ower exec,distribute dividends
function distributeDividends() onlyOwner public noEth(){ for (var i = IterableMapping.iterate_start(data); IterableMapping.iterate_valid(data, i); i = IterableMapping.iterate_next(data, i)) { var (key, value) = IterableMapping.iterate_get(data, i); uint tmp = balances[dividen...
0.4.21
/** * If the user sends 0 ether, he receives 500tokens. * If he sends 0.001 ether, he receives 2000tokens * If he sends 0.005 ether he receives 22,000tokens * If he sends 0.01ether, he receives 48,000 tokens * If he sends 0.02ether he receives 100000tokens * If he sends 0.05ether, he receives 270,000tokens ...
function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) { uint256 amountOfTokens = 0; if(_weiAmount == 0){ amountOfTokens = 500 * (10**uint256(decimals)); } if( _weiAmount == 0.001 ether){ amountOfTokens = 2000 * 10**3 * (10**uint...
0.4.24
/// @dev increase the token's supply
function increaseSupply (uint256 _value) isOwner external { uint256 value = formatDecimals(_value); require (value + currentSupply <= totalSupply); require (balances[msg.sender] >= value && value>0); balances[msg.sender] -= value; currentSupply = safeAdd(currentSupply, value...
0.4.26
/// buys the tokens
function () payable { require (isFunding); require(msg.value > 0); require(block.number >= fundingStartBlock); require(block.number <= fundingStopBlock); uint256 tokens = safeMult(msg.value, tokenExchangeRate); require(tokens + tokenRaised <= currentSupply); ...
0.4.26
/** * @notice Requests randomness * @dev Warning: if the VRF response is delayed, avoid calling requestRandomness repeatedly * as that would give miners/VRF operators latitude about which VRF response arrives first. * @dev You must review your implementation details with extreme care. * * @return bytes32 */
function rollDice() public onlyOwner returns (bytes32) { require(LINK.balanceOf(address(this)) >= s_fee, "Not enough LINK to pay fee"); require(result == 0, "Already rolled"); requestId = requestRandomness(s_keyHash, s_fee); result = BIG_PRIME; emit DiceRolled(requestId, msg.send...
0.8.7
/** * @notice Get the random number of token with id tokenId * @param _offset uint256 * @param _limit uint256 * @return array of random number as a uint256[] */
function getBatchRandomNumbers(uint256 _offset, uint256 _limit) public view returns (uint256[] memory) { require(_offset + _limit <= GHOST_SUPPLY, "Exceeded total supply"); uint256[] memory numbers = new uint[](_limit); for (uint256 i = 0; i < _limit; i++) { numbers[i] = getRandomNum...
0.8.7
/** * @notice Add credit to a job to be paid out for work * @param credit the credit being assigned to the job * @param job the job being credited * @param amount the amount of credit being added to the job */
function addCredit(address credit, address job, uint amount) external nonReentrant { require(jobs[job], "addCreditETH: !job"); uint _before = IERC20(credit).balanceOf(address(this)); IERC20(credit).safeTransferFrom(msg.sender, address(this), amount); uint _received = IERC20(credit).b...
0.6.12
/** * @notice Allows liquidity providers to submit jobs * @param liquidity the liquidity being added * @param job the job to assign credit to * @param amount the amount of liquidity tokens to use */
function addLiquidityToJob(address liquidity, address job, uint amount) external nonReentrant { require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); IERC20(liquidity).safeTransferFrom(msg.sender, address(this), amount); liquidityProvided[msg.sender][liquidity][job] = liquidityPr...
0.6.12
/** * @notice Applies the credit provided in addLiquidityToJob to the job * @param provider the liquidity provider * @param liquidity the pair being added as liquidity * @param job the job that is receiving the credit */
function applyCreditToJob(address provider, address liquidity, address job) external { require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); require(liquidityApplied[provider][liquidity][job] != 0, "credit: no bond"); require(liquidityApplied[provider][liquidity][job] < now, "cre...
0.6.12
/** * @notice Unbond liquidity for a job * @param liquidity the pair being unbound * @param job the job being unbound from * @param amount the amount of liquidity being removed */
function unbondLiquidityFromJob(address liquidity, address job, uint amount) external { require(liquidityAmount[msg.sender][liquidity][job] == 0, "credit: pending credit"); liquidityUnbonding[msg.sender][liquidity][job] = now.add(UNBOND); liquidityAmountsUnbonding[msg.sender][liquidity][job] ...
0.6.12
/** * @notice Allows liquidity providers to remove liquidity * @param liquidity the pair being unbound * @param job the job being unbound from */
function removeLiquidityFromJob(address liquidity, address job) external { require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "removeJob: unbond"); require(liquidityUnbonding[msg.sender][liquidity][job] < now, "removeJob: unbonding"); uint _amount = liquidityAmountsUnbonding[msg.sen...
0.6.12
/** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */
function workReceipt(address keeper, uint amount) public { require(jobs[msg.sender], "workReceipt: !job"); require(amount <= KPRH.getQuoteLimit(_gasUsed.sub(gasleft())), "workReceipt: max limit"); credits[msg.sender][address(this)] = credits[msg.sender][address(this)].sub(amount, "workReceipt...
0.6.12
/** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @param keeper the keeper being investigated * @param minBond the minimum requirement for the asset provided in bond * @param earned the total funds earned in the keepers lifetime * @para...
function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][address(this)].add(votes[keeper]) >= minBond && workCompleted[keeper] >= earned && now.su...
0.6.12
/** * @notice begin the bonding process for a new keeper * @param bonding the asset being bound * @param amount the amount of bonding asset being bound */
function bond(address bonding, uint amount) external nonReentrant { require(!blacklist[msg.sender], "bond: blacklisted"); bondings[msg.sender][bonding] = now.add(BOND); if (bonding == address(this)) { _transferTokens(msg.sender, address(this), amount); } else { ...
0.6.12
/** * @notice withdraw funds after unbonding has finished * @param bonding the asset to withdraw from the bonding pool */
function withdraw(address bonding) external nonReentrant { require(unbondings[msg.sender][bonding] != 0 && unbondings[msg.sender][bonding] < now, "withdraw: unbonding"); require(!disputes[msg.sender], "withdraw: disputes"); if (bonding == address(this)) { _transferTokens(addres...
0.6.12
/** * @notice allows governance to slash a keeper based on a dispute * @param bonded the asset being slashed * @param keeper the address being slashed * @param amount the amount being slashed */
function slash(address bonded, address keeper, uint amount) public nonReentrant { require(msg.sender == governance, "slash: !gov"); if (bonded == address(this)) { _transferTokens(address(this), governance, amount); } else { IERC20(bonded).safeTransfer(governance, amo...
0.6.12
/// @dev overrides transfer function to meet tokenomics of COINAGE
function _transfer(address sender, address recipient, uint256 amount) internal virtual override { // swap and liquify if ( swapAndLiquifyEnabled == true && _inSwapAndLiquify == false && address(coinageFinanceRouter) != address(0) && coinageFinancePai...
0.6.12
/// @dev Swap and liquify
function swapAndLiquify() private lockTheSwap transferTaxFree { uint256 contractTokenBalance = balanceOf(address(this)); uint256 maxTransferAmount = maxTransferAmount(); contractTokenBalance = contractTokenBalance > maxTransferAmount ? maxTransferAmount : contractTokenBalance; if (...
0.6.12
/// @dev Swap tokens for eth
function swapTokensForEth(uint256 tokenAmount) private { // generate the coinageFinance pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = coinageFinanceRouter.WETH(); _approve(address(this), address(coinageFinanceRouter...
0.6.12
/// @dev Add liquidity
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(coinageFinanceRouter), tokenAmount); // add the liquidity coinageFinanceRouter.addLiquidityETH{value: ethAmount}( ...
0.6.12
/** mint */
function _mintSeed(uint256 num, address to) internal { require(totalSupply() + num <= totalLimit, "exceed limit"); for(uint256 i = 0; i < num; i++) { uint256 tokenIndex = totalSupply(); _safeMint(to, tokenIndex); } }
0.8.4
// claim for dao holder
function claimDAO() public nonReentrant { require(!msg.sender.isContract(), "contract not allowed"); require(onClaim, "not on claim"); require( rally.balanceOf(msg.sender) >= rallyBalance || bank.balanceOf(msg.sender) >= bankBalance || fwb.balanceOf(msg.sende...
0.8.4
// mint for whitelist
function mintWhiteList(uint256 id, bytes32[] calldata proof) external nonReentrant { require(!minted[id][msg.sender], "already minted"); require(supply > 0, "out of supply"); require( MerkleProof.verify( proof, roots[id], keccak256(abi.encodePacked(msg.sender)) ...
0.8.4
/** @dev Initialize the contract, preventing any more changes not made through slate governance */
function init() public { require(msg.sender == owner, "Only the owner can initialize the ParameterStore"); require(initialized == false, "Contract has already been initialized"); initialized = true; // Do not allow initialization unless the gatekeeperAddress is set // Ch...
0.5.11
/** @dev Create multiple proposals to set values. @param keys The keys to set @param values The values to set for the keys @param metadataHashes Metadata hashes describing the proposals */
function createManyProposals( string[] calldata keys, bytes32[] calldata values, bytes[] calldata metadataHashes ) external { require(initialized, "Contract has not yet been initialized"); require( keys.length == values.length && values.length == metadataHa...
0.5.11
/** @dev Execute a proposal to set a parameter. The proposal must have been included in an accepted governance slate. @param proposalID The proposal */
function setValue(uint256 proposalID) public returns(bool) { require(proposalID < proposalCount(), "Invalid proposalID"); require(initialized, "Contract has not yet been initialized"); Proposal memory p = proposals[proposalID]; Gatekeeper gatekeeper = Gatekeeper(p.gatekeeper); ...
0.5.11
/** @dev Withdraw tokens previously staked on a slate that was accepted through slate governance. @param slateID The slate to withdraw the stake from */
function withdrawStake(uint slateID) public returns(bool) { require(slateID < slateCount(), "No slate exists with that slateID"); // get slate Slate memory slate = slates[slateID]; require(slate.status == SlateStatus.Accepted, "Slate has not been accepted"); require(msg....
0.5.11
/** @dev Deposit `numToken` tokens into the Gatekeeper to use in voting Assumes that `msg.sender` has approved the Gatekeeper to spend on their behalf @param numTokens The number of tokens to devote to voting */
function depositVoteTokens(uint numTokens) public returns(bool) { require(isCurrentGatekeeper(), "Not current gatekeeper"); address voter = msg.sender; // Voter must have enough tokens require(token.balanceOf(msg.sender) >= numTokens, "Insufficient token balance"); // Tr...
0.5.11
/** @dev Withdraw `numTokens` vote tokens to the caller and decrease voting power @param numTokens The number of tokens to withdraw */
function withdrawVoteTokens(uint numTokens) public returns(bool) { require(commitPeriodActive() == false, "Tokens locked during voting"); address voter = msg.sender; uint votingRights = voteTokenBalance[voter]; require(votingRights >= numTokens, "Insufficient vote token balance")...
0.5.11
/** @dev Submit a commitment for the current ballot @param voter The voter to commit for @param commitHash The hash representing the voter's vote choices @param numTokens The number of vote tokens to use */
function commitBallot(address voter, bytes32 commitHash, uint numTokens) public { uint epochNumber = currentEpochNumber(); require(commitPeriodActive(), "Commit period not active"); require(didCommit(epochNumber, voter) == false, "Voter has already committed for this ballot"); re...
0.5.11
/** @dev Reveal ballots for multiple voters */
function revealManyBallots( uint256 epochNumber, address[] memory _voters, bytes[] memory _ballots, uint[] memory _salts ) public { uint numBallots = _voters.length; require( _salts.length == _voters.length && _ballots.length == _voters.length, ...
0.5.11
/** @dev Get the number of second-choice votes cast for the given slate and resource @param epochNumber The epoch @param resource The resource @param slateID The slate */
function getSecondChoiceVotes(uint epochNumber, address resource, uint slateID) public view returns(uint) { // for each option that isn't this one, get the second choice votes Contest storage contest = ballots[epochNumber].contests[resource]; uint numSlates = contest.stakedSlates.length; ...
0.5.11
/** @dev Get the details of the specified contest */
function contestDetails(uint256 epochNumber, address resource) external view returns( ContestStatus status, uint256[] memory allSlates, uint256[] memory stakedSlates, uint256 lastStaked, uint256 voteWinner, uint256 voteRunnerUp, ...
0.5.11
/** @dev Send tokens of the rejected slates to the token capacitor. @param epochNumber The epoch @param resource The resource */
function donateChallengerStakes(uint256 epochNumber, address resource, uint256 startIndex, uint256 count) public { Contest storage contest = ballots[epochNumber].contests[resource]; require(contest.status == ContestStatus.Finalized, "Contest is not finalized"); uint256 numSlates = contest.s...
0.5.11
/** @dev Request permission to perform the action described in the metadataHash @param metadataHash A reference to metadata about the action */
function requestPermission(bytes memory metadataHash) public returns(uint) { require(isCurrentGatekeeper(), "Not current gatekeeper"); require(metadataHash.length > 0, "metadataHash cannot be empty"); address resource = msg.sender; uint256 epochNumber = currentEpochNumber(); ...
0.5.11
/** @dev Update a slate and its associated requests @param slateID The slate to update */
function acceptSlate(uint slateID) private { // Mark the slate as accepted Slate storage s = slates[slateID]; s.status = SlateStatus.Accepted; // Record the incumbent if (incumbent[s.resource] != s.recommender) { incumbent[s.resource] = s.recommender; ...
0.5.11
// --- Prepare --- // Sets the two deployer dependencies. This needs to be called by the deployUsr
function prepare(address lender_, address borrower_, address oracle_, address[] memory poolAdmins_) public { require(deployUsr == msg.sender); borrowerDeployer = BorrowerDeployerLike(borrower_); lenderDeployer = LenderDeployerLike_1(lender_); oracle = oracle_; poolAdmins...
0.7.6
// --- Deploy --- // After going through the deploy process on the lender and borrower method, this method is called to connect // lender and borrower contracts.
function deploy() public { require(address(borrowerDeployer) != address(0) && address(lenderDeployer) != address(0) && deployed == false); deployed = true; address reserve_ = lenderDeployer.reserve(); address shelf_ = borrowerDeployer.shelf(); // Borrower depends Depend...
0.7.6
//////////////////// /// @notice get all nfts of a person
function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) tokenIds[i] = tokenOfOwnerByIndex(_owner, i); return tokenI...
0.8.13
// transferOwnership add a pending owner
function transferOwnership(address newOwner) public override onlyOwner { require(!isBlackListed[newOwner], "Pending owner can not be in blackList"); require(newOwner != owner(), "Pending owner and current owner need to be different"); require(newOwner != address(0), "Pending owner can not be ...
0.8.3
// acceptOwnership allows the pending owner to accept the ownership of the SPWN token contract // along with grant new owner MINT_BURN_ROLE role and remove MINT_BURN_ROLE from old owner
function acceptOwnership() public { require(_pendingOwner != address(0), "Please set pending owner first"); require(_pendingOwner == msg.sender, "Only pending owner is able to accept the ownership"); require(!isBlackListed[msg.sender], "Pending owner can not be in blackList"); addr...
0.8.3
// internal function _revokeAccess revokes account with given role
function _revokeAccess(bytes32 role, address account) internal { if (DEFAULT_ADMIN_ROLE == role) { require(account != owner(), "owner can not revoke himself from admin role"); } revokeRole(role, account); emit RoleRevoked(role, account, owner()); }
0.8.3
/** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param Account address * * @param _value the amount of money to burn * * Safely check if total supply is not overdrawn */
function burnFrom(address Account, uint256 _value) public returns (bool success) { require (LockList[msg.sender] == false,"ERC20: User Locked !"); require (LockList[Account] == false,"ERC20: Owner Locked !"); uint256 stage; require(Account != address(0), "ERC20: Burn from the...
0.5.0
/** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * Emits Approval Event * @param _spender The address authorized to spend * @param _value the max amount they can spend */
function approve(address _spender, uint256 _value) public returns (bool success) { uint256 unapprovbal; // Do not allow approval if amount exceeds locked amount unapprovbal=balanceOf[msg.sender].sub(_value,"ERC20: Allowance exceeds balance of approver"); require(unapprovba...
0.5.0
// -------------------------------------------------------- // FUNCTION HANDLER // --------------------------------------------------------
function withdraw() public { uint256 tokenPending = 0; bool isWithdraw = false; require(block.timestamp - timestampLastReceived >= 5 * month, 'You can not withdraw token now'); for(uint8 i = 0; i < 13 ; i++) { if( times[i] != true ) { times[i] = true...
0.8.0
// --- Approve by signature ---
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(...
0.5.17
/** * @dev Adds a new pool. Admin only * * Params: * _allocPoint: the allocation points to be assigned to this pool * _lpToken: the token that this pool accepts * _withUpdate: whether or not to update all pools */
function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyAdmin isInitialized { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocP...
0.6.12
/** * @dev View function to see pending Stars on frontend. * * Params: * _user: address of the stars to view the pending rewards for. */
function pendingStars(uint256 _pid, address _user) external view isInitialized returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; if (pool.poolSupply == 0) { return 0; } uint...
0.6.12
/** * @dev An internal function to calculate the total accumulated Stars per * share, assuming the stars per share remained the same since staking * began. * * Params: * blocks: The number of blocks to calculate for */
function accStarsPerShareAtCurrRate(uint256 blocks, uint256 poolSupply) public view returns (uint256) { if (blocks > epochs[2]) { return totalStarsPerEpoch[0] .add(totalStarsPerEpoch[1]) .add(totalStarsPerEpoch[2]) ...
0.6.12
/** * @dev A function for the front-end to see information about the current rewards. */
function starsPerBlock() public view isInitialized returns (uint256 amount) { uint256 blocks = uint256(block.number).sub(startBlock); if (blocks >= epochs[2]) { return 0; } else if (blocks >= epochs[1]) { return rewardAmounts[2]; ...
0.6.12
/** * @dev Calculates the additional stars per share that have been accumulated * since lastRewardBlock, and updates accStarsPerShare and lastRewardBlock * accordingly. */
function updatePool(uint256 _pid) public isInitialized { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } if (pool.poolSupply != 0) { uint256 currRateEndStarsPerShare = accStarsPerShareAtCurrRate( ...
0.6.12
/** * @dev Collect rewards owed. * * Params: * _pid: the pool id */
function collectRewards(uint256 _pid) public isInitialized { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accStarsPerShare).div(1e12...
0.6.12
/** * @dev Deposit stars for staking. The sender's pending rewards are * sent to the sender, and the sender's information is updated accordingly. * * Params: * _pid: the pool id * _amount: amount of Stars to deposit */
function deposit(uint256 _pid, uint256 _amount) public isInitialized { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amo...
0.6.12
/** * @dev Withdraw Stars from the amount that the user is staking and collect * pending rewards. * * Params: * _pid: the pool id * _amount: amount of Stars to withdraw * * Requirements: * _amount is less than or equal to the amount of Stars the the user has * deposited to the contract */
function withdraw(uint256 _pid, uint256 _amount) public isInitialized { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); pool.lpToken.safeTransfer(address(msg.sende...
0.6.12
/// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer...
0.4.21
/// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract.
function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work bool re...
0.4.21
/// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); ...
0.4.21
/// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param...
function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction ...
0.4.21
/// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId) external payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit i...
0.4.21
//Creates a unique key based on the artwork name, author, and series
function getUniqueKey(string name, string author, uint32 _version) internal pure returns(bytes32) { string memory version = _uintToString(_version); string memory main = _strConcat(name, author, version, "$%)"); string memory lowercased = _toLower(main); return keccak256(lowercased)...
0.4.21
//https://gist.github.com/thomasmaclean/276cb6e824e48b7ca4372b194ec05b97 //transform to lowercase
function _toLower(string str) internal pure returns (string) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character... if ((bStr[i] >= 65) && (bStr[i] <= 90)) { // So we add 32 to make it lowercase bLowe...
0.4.21
//creates a unique key from all variables
function _strConcat(string _a, string _b, string _c, string _separator) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_separator); bytes memory _bc = bytes(_b); bytes memory _bd = bytes(_separator); bytes memory _be = bytes(_c); ...
0.4.21
/// title String Utils - String utility functions /// @author Piper Merriam - <pipermerriam@gmail.com> ///https://github.com/pipermerriam/ethereum-string-utils
function _uintToBytes(uint v) private pure returns (bytes32 ret) { if (v == 0) { ret = "0"; } else { while (v > 0) { ret = bytes32(uint(ret) / (2 ** 8)); ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31)); v /= 10; ...
0.4.21
/// @notice Grant another address the right to transfer a specific Artwork via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Artwork that can be...
function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId...
0.4.21
/// @notice Transfer a Artwork owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Artwork to be transfered. /// @param _to The address that should take ownership of the Artwork. Can be any address, /// incl...
function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent acc...
0.4.21
/// @notice Transfers a Artwork to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoArtworks specifically) or your Artwork may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tok...
function transfer(address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any Artworks (...
0.4.21
/// @notice Returns a list of all Artwork IDs assigned to an address. /// @param _owner The owner whose Artworks we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Artwork array looking for arts belonging to owner), /// but it ...
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](toke...
0.4.21
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private view { // Copy word-length chunks while possible for (; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Co...
0.4.21
/// @dev Put a artwork up for auction. /// Does some ownership trickery to create auctions in one tx.
function createSaleAuction( uint256 _artworkId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If artwork is already on any auction, this will throw ...
0.4.21
/// @dev we can create promo artworks, up to a limit. Only callable by COO /// @param _owner the future owner of the created artworks. Default to contract COO
function createPromoArtwork(string _name, string _author, uint32 _series, address _owner) external onlyCOO { bytes32 uniqueKey = getUniqueKey(_name, _author, _series); (require(!uniqueArtworks[uniqueKey])); if (_series != 0) { bytes32 uniqueKeyForZero = getUniqueKey(_name, _autho...
0.4.21
/// @dev Creates a new artwork with the given name and author and /// creates an auction for it.
function createArtworkAuction(string _name, string _author, uint32 _series) external onlyCOO { bytes32 uniqueKey = getUniqueKey(_name, _author, _series); (require(!uniqueArtworks[uniqueKey])); require(artsCreatedCount < CREATION_LIMIT); if (_series != 0) { bytes32 unique...
0.4.21
/// @dev Computes the next gen0 auction starting price, given /// the average of the past 5 prices + 50%.
function _computeNextArtworkPrice() internal view returns (uint256) { uint256 avePrice = saleAuction.averageArtworkSalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); ...
0.4.21
/// @notice Creates the main CryptoArtworks smart contract instance.
function ArtworkCore() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // start with the art ...
0.4.21
/// @notice Returns all the relevant information about a specific artwork. /// @param _id The ID of the artwork of interest.
function getArtwork(uint256 _id) external view returns ( uint256 birthTime, string name, string author, uint32 series ) { Artwork storage art = artworks[_id]; birthTime = uint256(art.birthTime); name = string(art.name); ...
0.4.21
/** * @param solidBondID is a solid bond ID * @param SBTAmount is solid bond token amount * @return poolID is a pool ID * @return IDOLAmount is iDOL amount obtained */
function _swapSBT2IDOL( bytes32 solidBondID, address SBTAddress, uint256 SBTAmount ) internal returns (bytes32 poolID, uint256 IDOLAmount) { // 1. approve ERC20(SBTAddress).approve(address(_IDOLContract), SBTAmount); // 2. mint (SBT -> iDOL) (poolID,...
0.6.6
/** * @notice swap (LBT -> iDOL) * @param LBTAddress is liquid bond token contract address * @param LBTAmount is liquid bond amount * @param timeout (uniswap) * @param isLimit (uniswap) */
function _swapLBT2IDOL( address LBTAddress, uint256 LBTAmount, uint256 timeout, bool isLimit ) internal isNotEmptyExchangeInstance { address _boxExchangeAddress = _exchangeLBTAndIDOLFactoryContract .addressToExchangeLookup(LBTAddress); // 1. approv...
0.6.6
/** * @notice swap (SBT -> LBT) * @param solidBondID is a solid bond ID * @param liquidBondID is a liquid bond ID * @param timeout (uniswap) * @param isLimit (uniswap) */
function swapSBT2LBT( bytes32 solidBondID, bytes32 liquidBondID, uint256 SBTAmount, uint256 timeout, bool isLimit ) public override { (address SBTAddress, , , ) = _bondMakerContract.getBond(solidBondID); require(SBTAddress != address(0), "the bond is n...
0.6.6
/** * @notice find a solid bond in given bond group * @param bondGroupID is a bond group ID */
function _findSBTAndLBTBondGroup(uint256 bondGroupID) internal view returns (bytes32 solidBondID, bytes32[] memory liquidBondIDs) { (bytes32[] memory bondIDs, ) = _bondMakerContract.getBondGroup( bondGroupID ); bytes32 solidID = bytes32(0); ...
0.6.6
/** * @notice ETH -> LBT & iDOL * @param bondGroupID is a bond group ID * @return poolID is a pool ID * @return IDOLAmount is iDOL amount obtained */
function issueLBTAndIDOL(uint256 bondGroupID) public override payable returns ( bytes32, uint256, uint256 ) { ( bytes32 solidBondID, bytes32[] memory liquidBondIDs ) = _findSBTAndLBTBondG...
0.6.6
/** * @notice ETH -> iDOL * @param bondGroupID is a bond group ID * @param timeout (uniswap) * @param isLimit (uniswap) */
function issueIDOLOnly( uint256 bondGroupID, uint256 timeout, bool isLimit ) public override payable { // 0. uses: ETH ( bytes32 solidBondID, bytes32[] memory liquidBondIDs ) = _findSBTAndLBTBondGroup(bondGroupID); // find SBT & LBT ...
0.6.6
/* * return 5 values - the canClaim returns the number of claimerContract token that can claim */
function triBalanceOf(address addr) view public returns (uint nwoBal,uint moriesBal,uint lossamosBal,uint moriesCanClaim,uint lossamosCanClaim){ uint moriesBal = mories.balanceOf(addr); uint lossamosBal=lossamos.balanceOf(addr); uint tokenId; uint moriesCanClaim = 0; ...
0.7.3
/** * Claim token for los samos owners */
function claimNTokens(uint[] memory tokenIds,ClaimerContract claimerContract, uint claimRatio,uint startIndex,uint maxSupply,uint firtsTokenId) public { require(claimIsActive, "Claim must be active"); require(tokenIds.length>0, "Must claim at least one token."); require(totalSupply(...
0.7.3
/** * Internal transfer, only can be called by this contract * * @param _from - address of the contract * @param _to - address of the investor * @param _value - tokens for the investor */
function _transfer(address _from, address _to, uint256 _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf...
0.4.19
/* * Make discount */
function countDiscount(uint256 amount) internal returns(uint256) { uint256 _amount = (amount.mul(DEC)).div(buyPrice); if (1 == stage) { _amount = _amount.add(withDiscount(_amount, ICO.discount)); } else if (2 == stage) { if (now <= I...
0.4.19
/** * Expanding of the functionality * * @param _numerator - Numerator - value (10000) * @param _denominator - Denominator - value (10000) * * example: price 1000 tokens by 1 ether = changeRate(1, 1000) */
function changeRate(uint256 _numerator, uint256 _denominator) public onlyOwner returns (bool success) { if (_numerator == 0) _numerator = 1; if (_denominator == 0) _denominator = 1; buyPrice = (_numerator.mul(DEC)).div(_denominator); return true; }
0.4.19
/* * Function show in contract what is now * */
function crowdSaleStatus() internal constant returns (string) { if (1 == stage) { return "Pre-ICO"; } else if(2 == stage) { return "ICO first stage"; } else if (3 == stage) { return "ICO second stage"; } else if (4 >= stage) { ...
0.4.19
/* * Seles manager * */
function paymentManager(address sender, uint256 value) internal { uint256 discountValue = countDiscount(value); bool conf = confirmSell(discountValue); if (conf) { sell(sender, discountValue); weisRaised = weisRaised.add(value); if (now >= I...
0.4.19
/* * Function for start crowdsale (any) * * @param _tokens - How much tokens will have the crowdsale - amount humanlike value (10000) * @param _startDate - When crowdsale will be start - unix timestamp (1512231703 ) * @param _endDate - When crowdsale will be end - humanlike value (7) same as 7 days * @param...
function startCrowd(uint256 _tokens, uint _startDate, uint _endDate, uint8 _discount, uint8 _discountFirstDayICO) public onlyOwner { require(_tokens * DEC <= avaliableSupply); // require to set correct tokens value for crowd ICO = Ico (_tokens * DEC, _startDate, _startDate + _endDate * 1 days , ...
0.4.19
// @notice Allow pre-approved user to take ownership of a token // @param _tokenId The ID of the Token that can be transferred if this call succeeds.
function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = tokenIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved ...
0.4.18
// @dev Creates a new promo Token with the given name, with given _price and assignes it to an address.
function createPromoToken(address _owner, string _name, uint256 _price) public onlyCOO { require(promoCreatedCount < PROMO_CREATION_LIMIT); address tokenOwner = _owner; if (tokenOwner == address(0)) { tokenOwner = cooAddress; } if (_price <= 0) { ...
0.4.18
/** Delegate votes from signatory to `delegatee`. @param delegatee The address to delegate votes to. @param nonce The contract state required for signature matching. @param expiry The time at which to expire the signature. @param v The recovery byte of the signature. @param r Half of the ECDSA signature ...
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256( ...
0.6.12