Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
113
// Mapping of shields so we don't reward them for U.F.
mapping (address => bool) public arShields;
mapping (address => bool) public arShields;
10,263
36
// Burning disabled. Returns the total number of tokens burned. /
// function _totalBurned() internal view virtual returns (uint256) { // return _burnCounter; // }
// function _totalBurned() internal view virtual returns (uint256) { // return _burnCounter; // }
24,521
21
// Governs how many validator validators a single account can vote for.
uint256 public maxNumValidatorsVotedFor;
uint256 public maxNumValidatorsVotedFor;
19,061
8
// allows anybody to execute given they have a signed messaged from an executor
function executeRelayedCall( address signedFor, bytes memory _data, uint256 _nonce, bytes memory _signature
function executeRelayedCall( address signedFor, bytes memory _data, uint256 _nonce, bytes memory _signature
27,863
4
// IERC20(_token).transferFrom(msg.sender, address(this), amt);
IERC20(_token).transferFrom(msg.sender,addr, amt_to_send);
IERC20(_token).transferFrom(msg.sender,addr, amt_to_send);
6,277
36
// update state
_weiRaised = _weiRaised.add(weiAmount); tokensPerAddress[sender] += tokens;
_weiRaised = _weiRaised.add(weiAmount); tokensPerAddress[sender] += tokens;
2,705
134
// Pie Distribution Admin //Set PIE speed for a single marketpToken The market whose PIE speed to updatepieSpeed New PIE speed for market/
function _setPieSpeed(address pToken, uint pieSpeed) public { require(msg.sender == admin, "only admin can set pie speed"); setPieSpeedInternal(pToken, pieSpeed); }
function _setPieSpeed(address pToken, uint pieSpeed) public { require(msg.sender == admin, "only admin can set pie speed"); setPieSpeedInternal(pToken, pieSpeed); }
3,220
63
// Adjust collateral and amountToBorrow to asset tokens
uint adjustedCollateral = numberOfTokensReceived.mul(collateral).div(collateral.add(amountToBorrow)); uint adjustedAmountToBorrow = numberOfTokensReceived.mul(amountToBorrow).div(collateral.add(amountToBorrow));
uint adjustedCollateral = numberOfTokensReceived.mul(collateral).div(collateral.add(amountToBorrow)); uint adjustedAmountToBorrow = numberOfTokensReceived.mul(amountToBorrow).div(collateral.add(amountToBorrow));
24,326
204
// the percentage of sale that an artist gets on secondary sales
uint256 public artistSecondSalePercentage;
uint256 public artistSecondSalePercentage;
15,251
25
// buy
if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) { require(_tradingOpen, "Trading not yet enabled."); require(block.timestamp != _launchedAt, "pls no snip"); if((_launchedAt + (1 hours)) > block.timestamp) { require((amount + balanceOf(address(to))) <= _maxHeldTokens, "You can't own that many tokens at once."); // 5% }
if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) { require(_tradingOpen, "Trading not yet enabled."); require(block.timestamp != _launchedAt, "pls no snip"); if((_launchedAt + (1 hours)) > block.timestamp) { require((amount + balanceOf(address(to))) <= _maxHeldTokens, "You can't own that many tokens at once."); // 5% }
2,522
2
// fired at end of buy or reload
event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName,
event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName,
21,050
7
// See {ERC20Pausable} and {Pausable-_pause}. Requirements:the caller must have the `PAUSER_ROLE`. /
function pause() external virtual { require( hasRole(PAUSER_ROLE, _msgSender()), "Token: must have pauser role to pause" ); _pause(); }
function pause() external virtual { require( hasRole(PAUSER_ROLE, _msgSender()), "Token: must have pauser role to pause" ); _pause(); }
52,429
54
// Daily allocationdays since mint - claimed
return (ships[shipInstances[tokenId].name].dailyAllocation
return (ships[shipInstances[tokenId].name].dailyAllocation
27,203
4
// A The input array to search a The address to remove /
function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } }
function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } }
6,559
5,124
// 2563
entry "tweenaged" : ENG_ADJECTIVE
entry "tweenaged" : ENG_ADJECTIVE
19,175
24
// ๅทฒๆ™ฎ้€šๆ็Žฐ้ขๅบฆ
uint256 public totalCommonWithdrawSupply;
uint256 public totalCommonWithdrawSupply;
38,375
204
// burn the tokens that have not been sold yet
function burnUnmintedTokens() public onlyOwner { maxTotalTokens = totalSupply(); maxTokensPresale = totalSupply(); }
function burnUnmintedTokens() public onlyOwner { maxTotalTokens = totalSupply(); maxTokensPresale = totalSupply(); }
41,269
27
// The job creator can choose an applicant for his job Need to flesh out a little... Give applicant the choice to still choose the job before money is staked (do in signing process) For the above, make sure the states are worked out chosenApplicant The applicant who is accepted jobID The ID of a specific job /
{ finalApplicant[jobID] = chosenApplicant; jobs[jobID].state = State.Signing; emit ApplicantChosen(chosenApplicant, jobID); }
{ finalApplicant[jobID] = chosenApplicant; jobs[jobID].state = State.Signing; emit ApplicantChosen(chosenApplicant, jobID); }
10,391
45
// Approves a third-party spender
function approve(address _spender, uint256 _amount) public returns (bool)
function approve(address _spender, uint256 _amount) public returns (bool)
38,999
38
// Step4. Claim reward
function _claim(uint _tokenType, uint16 _tokenId) internal { // ์ „์ฒด ๋ฆฌ์›Œ๋“œ๋ฅผ ๊ณ„์‚ฐํ•˜์—ฌ ๋ฐ›์•„์˜ต๋‹ˆ๋‹ค. uint256 _myReward = _calReward(_tokenType, _tokenId); // ERC-20 ํ† ํฐ ๋ฐœํ–‰ ํ•จ์ˆ˜๋กœ ๊ต์ฒด rewardVault.transferToken(msg.sender, _myReward); // ๋ธ”๋กํƒ€์ž„ ์ดˆ๊ธฐํ™” if(_tokenType==0){ inStakedtmhc[_tokenId].lastUpdateBlock = block.timestamp; }else if(_tokenType==1){ inStakedmomo[_tokenId].lastUpdateBlock = block.timestamp; } // ์‚ฌ์šฉ์ž ๋ฆฌ์›Œ๋“œ ์ง€๊ธ‰ ์ •๋ณด ์ €์žฅ users[msg.sender].rewardsEarned += _myReward; // ๋ณด์ƒ์ด ์ง€๊ธ‰๋˜์—ˆ์Œ์„ ๋‚˜ํƒ€๋‚ด๋Š” ์ด๋ฒคํŠธ ๋ฐœ์ƒ emit RewardPaid(msg.sender, _myReward); }
function _claim(uint _tokenType, uint16 _tokenId) internal { // ์ „์ฒด ๋ฆฌ์›Œ๋“œ๋ฅผ ๊ณ„์‚ฐํ•˜์—ฌ ๋ฐ›์•„์˜ต๋‹ˆ๋‹ค. uint256 _myReward = _calReward(_tokenType, _tokenId); // ERC-20 ํ† ํฐ ๋ฐœํ–‰ ํ•จ์ˆ˜๋กœ ๊ต์ฒด rewardVault.transferToken(msg.sender, _myReward); // ๋ธ”๋กํƒ€์ž„ ์ดˆ๊ธฐํ™” if(_tokenType==0){ inStakedtmhc[_tokenId].lastUpdateBlock = block.timestamp; }else if(_tokenType==1){ inStakedmomo[_tokenId].lastUpdateBlock = block.timestamp; } // ์‚ฌ์šฉ์ž ๋ฆฌ์›Œ๋“œ ์ง€๊ธ‰ ์ •๋ณด ์ €์žฅ users[msg.sender].rewardsEarned += _myReward; // ๋ณด์ƒ์ด ์ง€๊ธ‰๋˜์—ˆ์Œ์„ ๋‚˜ํƒ€๋‚ด๋Š” ์ด๋ฒคํŠธ ๋ฐœ์ƒ emit RewardPaid(msg.sender, _myReward); }
20,603
38
// Remove a rebase hook. _index Index of the transaction to remove. /
function removeTransaction(uint256 _index) external onlyGovernance { require(_index < transactions.length, "index out of bounds"); if (_index < transactions.length - 1) { transactions[_index] = transactions[transactions.length - 1]; } transactions.pop(); }
function removeTransaction(uint256 _index) external onlyGovernance { require(_index < transactions.length, "index out of bounds"); if (_index < transactions.length - 1) { transactions[_index] = transactions[transactions.length - 1]; } transactions.pop(); }
12,032
4
// set the rest of the contract variables
pancakeswapV2Router = _pancakeswapV2Router;
pancakeswapV2Router = _pancakeswapV2Router;
31,347
1
// [ERC1400ERC20 CONSTRUCTOR] Initialize ERC71400ERC20 and CertificateController parameters + registerthe contract implementation in ERC1820Registry. name Name of the token. symbol Symbol of the token. granularity Granularity of the token. controllers Array of initial controllers. certificateSigner Address of the off-chain service which signs theconditional ownership certificates required for token transfers, issuance,redemption (Cf. CertificateController.sol). /
constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bytes32[] memory tokenDefaultPartitions )
constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bytes32[] memory tokenDefaultPartitions )
33,067
5
// Validate and update nonce
_validateNonce(_nonce);
_validateNonce(_nonce);
9,703
63
// ERC20 token implementation, inherited by CoFiXPair contract, no owner or governance
contract CoFiXERC20 is ICoFiXERC20 { using SafeMath for uint; string public constant nameForDomain = 'CoFiX Pool Token'; uint8 public override constant decimals = 18; uint public override totalSupply; mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; bytes32 public override DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public override constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public override nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(nameForDomain)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external override returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { require(deadline >= block.timestamp, 'CERC20: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'CERC20: INVALID_SIGNATURE'); _approve(owner, spender, value); } }
contract CoFiXERC20 is ICoFiXERC20 { using SafeMath for uint; string public constant nameForDomain = 'CoFiX Pool Token'; uint8 public override constant decimals = 18; uint public override totalSupply; mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; bytes32 public override DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public override constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public override nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(nameForDomain)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external override returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external override { require(deadline >= block.timestamp, 'CERC20: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'CERC20: INVALID_SIGNATURE'); _approve(owner, spender, value); } }
13,177
13
// make sure they&39;re an owner
if (ownerIndex == 0) return; uint ownerIndexBit = 2**ownerIndex; PendingState storage pending = m_pending[_operation]; if (pending.ownersDone & ownerIndexBit > 0) { pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; emit Revoke(msg.sender, _operation); }
if (ownerIndex == 0) return; uint ownerIndexBit = 2**ownerIndex; PendingState storage pending = m_pending[_operation]; if (pending.ownersDone & ownerIndexBit > 0) { pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; emit Revoke(msg.sender, _operation); }
34,164
19
// Function to finish a raffle campaign
function finishRaffleCampaign() public onlyOwner onlyRaffle whenStarted { require(!finished, "Campaign already finished"); finished = true; // Request a random number // randomNumberContract.getRandomNumber(block.timestamp); emit CampaignFinished(); }
function finishRaffleCampaign() public onlyOwner onlyRaffle whenStarted { require(!finished, "Campaign already finished"); finished = true; // Request a random number // randomNumberContract.getRandomNumber(block.timestamp); emit CampaignFinished(); }
3,151
126
// Transfer ETH reward to caller of the ripcord function. If the ETH balance on this contract is less than required incentive quantity, then transfer contract balance instead to prevent reverts. return uint256 Amount of ETH transferred to caller /
function _transferEtherRewardToCaller(uint256 _etherReward) internal returns(uint256) { uint256 etherToTransfer = _etherReward < address(this).balance ? _etherReward : address(this).balance; msg.sender.transfer(etherToTransfer); return etherToTransfer; }
function _transferEtherRewardToCaller(uint256 _etherReward) internal returns(uint256) { uint256 etherToTransfer = _etherReward < address(this).balance ? _etherReward : address(this).balance; msg.sender.transfer(etherToTransfer); return etherToTransfer; }
34,741
45
// ๅฎž้™…ๅบ”่ฏฅๅ‡ๅŽป็š„ๆ•ฐ้‡
uint _newPrice = _initPrice.add(_singlePrice.mul(_ratio)); uint _price = uint(1).mul(1e18).div(_newPrice); return _price;
uint _newPrice = _initPrice.add(_singlePrice.mul(_ratio)); uint _price = uint(1).mul(1e18).div(_newPrice); return _price;
9,683
72
// function to get stakeholders addresses
function getStakeholdersAddresses() external view returns (address[] memory)
function getStakeholdersAddresses() external view returns (address[] memory)
37,540
104
// Update per investor amount
investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount);
investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount);
68,285
14
// Calculates the total amount of {want} held by the strategywhich is the balance of want + the total amount supplied to Excalibur. /
function balanceOf() public view override returns (uint256) { return balanceOfWant() + balanceOfPool(); }
function balanceOf() public view override returns (uint256) { return balanceOfWant() + balanceOfPool(); }
36,888
10
// Check whether a voucher has been executed./_inboxInputIndex The index of the input in the input box/_outputIndex The index of output emitted by the input/ return Whether the voucher has been executed before
function wasVoucherExecuted( uint256 _inboxInputIndex, uint256 _outputIndex ) external view returns (bool);
function wasVoucherExecuted( uint256 _inboxInputIndex, uint256 _outputIndex ) external view returns (bool);
12,334
513
// See {IERC721-safeTransferFrom}. /
function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); }
function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); }
2,667
8
// A mix-in contract to decode AML payloads.This should be a library, but for the complexity and toolchain fragility risks involving of linking library inside library, we put this as a mix-in. /
contract KYCPayloadDeserializer { using BytesDeserializer for bytes; /** * This function takes the dataframe and unpacks it * We have the users ETH address for verification that they are using their own signature * CustomerID so we can track customer purchases * Min/Max ETH to invest for AML/CTF purposes - this can be supplied by the user OR by the back-end. */ function getKYCPayload(bytes dataframe) public pure returns(address whitelistedAddress, uint128 customerId, uint32 minEth, uint32 maxEth) { address _whitelistedAddress = dataframe.sliceAddress(0); uint128 _customerId = uint128(dataframe.slice16(20)); uint32 _minETH = uint32(dataframe.slice4(36)); uint32 _maxETH = uint32(dataframe.slice4(40)); return (_whitelistedAddress, _customerId, _minETH, _maxETH); } }
contract KYCPayloadDeserializer { using BytesDeserializer for bytes; /** * This function takes the dataframe and unpacks it * We have the users ETH address for verification that they are using their own signature * CustomerID so we can track customer purchases * Min/Max ETH to invest for AML/CTF purposes - this can be supplied by the user OR by the back-end. */ function getKYCPayload(bytes dataframe) public pure returns(address whitelistedAddress, uint128 customerId, uint32 minEth, uint32 maxEth) { address _whitelistedAddress = dataframe.sliceAddress(0); uint128 _customerId = uint128(dataframe.slice16(20)); uint32 _minETH = uint32(dataframe.slice4(36)); uint32 _maxETH = uint32(dataframe.slice4(40)); return (_whitelistedAddress, _customerId, _minETH, _maxETH); } }
42,097
3
// Returns the max amount of Base that can be sold to the pool
function maxBaseIn() external view returns (uint128) ;
function maxBaseIn() external view returns (uint128) ;
28,286
13
// This allows the owner to change the operator.
function setOperator(address newOperator) external onlyOwner { operator = newOperator; }
function setOperator(address newOperator) external onlyOwner { operator = newOperator; }
30,321
94
// Forward ERC20 methods to upgraded contract if this one is deprecated
function totalSupply() public view returns (uint256) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).totalSupplyByLegacy(); } else { return totalSupply_; } }
function totalSupply() public view returns (uint256) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).totalSupplyByLegacy(); } else { return totalSupply_; } }
12,574
43
// an approved spender can transfer currency from one account to another up to their spending limit
function transferFrom(address from, address to, uint value) public override returns(bool) { require(allowances[from][msg.sender] > 0, "No Allowance for this address."); require(allowances[from][msg.sender] >= value, "Allowance too low for transfer."); require(balances[from] >= value, "Balance is too low to make transfer."); balances[to] += value; balances[from] -= value; emit Transfer(from, to, value); return true; }
function transferFrom(address from, address to, uint value) public override returns(bool) { require(allowances[from][msg.sender] > 0, "No Allowance for this address."); require(allowances[from][msg.sender] >= value, "Allowance too low for transfer."); require(balances[from] >= value, "Balance is too low to make transfer."); balances[to] += value; balances[from] -= value; emit Transfer(from, to, value); return true; }
3,085
2
// Immutabel state
ISnapshotableToken private SHARE_TOKEN;
ISnapshotableToken private SHARE_TOKEN;
1,474
444
// attempt to add borrower to the market
Error err = addToMarketInternal(PToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); }
Error err = addToMarketInternal(PToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); }
13,759
263
// replaced Address lib with custom MyAddress to avoid delegateCall (its not allowed for Proxied contract)
using AddressUtil for address; using Strings for uint256;
using AddressUtil for address; using Strings for uint256;
53,608
294
// we want to use statechanging for safety
(uint256 deposits, uint256 borrows) = getLivePosition();
(uint256 deposits, uint256 borrows) = getLivePosition();
13,176
96
// Returns e.g. https:mirror-api.com/editions/[editionId]/[tokenId]
function tokenURI(uint256 tokenId) public view override returns (string memory)
function tokenURI(uint256 tokenId) public view override returns (string memory)
13,496
11
// Delete the index for the deleted slot
delete set._indexes[value]; return true;
delete set._indexes[value]; return true;
41,390
6
// Check if goal was reached Checks if the goal or time limit has been reached and ends the campaign /
function checkGoalReached() public afterDeadline { if (amountRaised >= fundingGoal){ fundingGoalReached = true; emit GoalReached(beneficiary, amountRaised); }
function checkGoalReached() public afterDeadline { if (amountRaised >= fundingGoal){ fundingGoalReached = true; emit GoalReached(beneficiary, amountRaised); }
22,251
70
// Checks an address for the total amount of base rewards they can claim for owning one or more Gen1 & Gen2 NFTs. Note these NFTs may have already been claimed by a previous owner, as the base claim is tracked by token id.
function checkBaseReward(address recipient) external view returns (uint256) { uint256 gen1Count = TPTGen1.balanceOf(recipient); require(gen1Count > 0, "Wallet must own a Genesis NFT"); uint256 gen2Count = TPTGen2.balanceOf(recipient); require(gen2Count > 0, "Wallet must own a Gen2 NFT"); uint256[] memory gen2TokenIds = new uint256[](gen2Count); uint256 gen2TokenIdsLength; for (uint256 i; i < gen2Count; i++) { uint256 gen2TokenId = TPTGen2.tokenOfOwnerByIndex(recipient, i); if (_gen2BaseClaimed[gen2TokenId] == false) { gen2TokenIds[gen2TokenIdsLength] = gen2TokenId; gen2TokenIdsLength++; } } require(gen2TokenIdsLength > 0, "No unclaimed Gen2 NFTs available"); uint256 total; for (uint256 i; i < gen1Count; i++) { uint256 gen1TokenId = TPTGen1.tokenOfOwnerByIndex(recipient, i); if (_gen1BaseClaimed[gen1TokenId] == false && gen2TokenIdsLength > 0) { gen2TokenIdsLength--; total += levels[_rewardLevel[gen1TokenId]].baseClaim; } } return total; }
function checkBaseReward(address recipient) external view returns (uint256) { uint256 gen1Count = TPTGen1.balanceOf(recipient); require(gen1Count > 0, "Wallet must own a Genesis NFT"); uint256 gen2Count = TPTGen2.balanceOf(recipient); require(gen2Count > 0, "Wallet must own a Gen2 NFT"); uint256[] memory gen2TokenIds = new uint256[](gen2Count); uint256 gen2TokenIdsLength; for (uint256 i; i < gen2Count; i++) { uint256 gen2TokenId = TPTGen2.tokenOfOwnerByIndex(recipient, i); if (_gen2BaseClaimed[gen2TokenId] == false) { gen2TokenIds[gen2TokenIdsLength] = gen2TokenId; gen2TokenIdsLength++; } } require(gen2TokenIdsLength > 0, "No unclaimed Gen2 NFTs available"); uint256 total; for (uint256 i; i < gen1Count; i++) { uint256 gen1TokenId = TPTGen1.tokenOfOwnerByIndex(recipient, i); if (_gen1BaseClaimed[gen1TokenId] == false && gen2TokenIdsLength > 0) { gen2TokenIdsLength--; total += levels[_rewardLevel[gen1TokenId]].baseClaim; } } return total; }
9,605
29
// In case there is still small error, you, the caller please pay for it.
IERC20(registry.tidalToken()).transferFrom(msg.sender, address(this), payoutInfo[payoutId_].total - payoutInfo[payoutId_].paid); payoutInfo[payoutId_].paid = payoutInfo[payoutId_].total;
IERC20(registry.tidalToken()).transferFrom(msg.sender, address(this), payoutInfo[payoutId_].total - payoutInfo[payoutId_].paid); payoutInfo[payoutId_].paid = payoutInfo[payoutId_].total;
35,661
245
// CurveGaugeV2ActionsMixin Contract/Enzyme Council <[email protected]nance>/Mixin contract for interacting with any Curve LiquidityGaugeV2 contract
abstract contract CurveGaugeV2ActionsMixin is AssetHelpers { uint256 private constant CURVE_GAUGE_V2_MAX_REWARDS = 8; /// @dev Helper to claim pool-specific rewards function __curveGaugeV2ClaimRewards(address _gauge, address _target) internal { ICurveLiquidityGaugeV2(_gauge).claim_rewards(_target); } /// @dev Helper to get list of pool-specific rewards tokens function __curveGaugeV2GetRewardsTokens(address _gauge) internal view returns (address[] memory rewardsTokens_) { address[] memory lpRewardsTokensWithEmpties = new address[](CURVE_GAUGE_V2_MAX_REWARDS); uint256 rewardsTokensCount; for (uint256 i; i < CURVE_GAUGE_V2_MAX_REWARDS; i++) { address rewardToken = ICurveLiquidityGaugeV2(_gauge).reward_tokens(i); if (rewardToken != address(0)) { lpRewardsTokensWithEmpties[i] = rewardToken; rewardsTokensCount++; } else { break; } } rewardsTokens_ = new address[](rewardsTokensCount); for (uint256 i; i < rewardsTokensCount; i++) { rewardsTokens_[i] = lpRewardsTokensWithEmpties[i]; } return rewardsTokens_; } /// @dev Helper to stake LP tokens function __curveGaugeV2Stake( address _gauge, address _lpToken, uint256 _amount ) internal { __approveAssetMaxAsNeeded(_lpToken, _gauge, _amount); ICurveLiquidityGaugeV2(_gauge).deposit(_amount, address(this)); } /// @dev Helper to unstake LP tokens function __curveGaugeV2Unstake(address _gauge, uint256 _amount) internal { ICurveLiquidityGaugeV2(_gauge).withdraw(_amount); } }
abstract contract CurveGaugeV2ActionsMixin is AssetHelpers { uint256 private constant CURVE_GAUGE_V2_MAX_REWARDS = 8; /// @dev Helper to claim pool-specific rewards function __curveGaugeV2ClaimRewards(address _gauge, address _target) internal { ICurveLiquidityGaugeV2(_gauge).claim_rewards(_target); } /// @dev Helper to get list of pool-specific rewards tokens function __curveGaugeV2GetRewardsTokens(address _gauge) internal view returns (address[] memory rewardsTokens_) { address[] memory lpRewardsTokensWithEmpties = new address[](CURVE_GAUGE_V2_MAX_REWARDS); uint256 rewardsTokensCount; for (uint256 i; i < CURVE_GAUGE_V2_MAX_REWARDS; i++) { address rewardToken = ICurveLiquidityGaugeV2(_gauge).reward_tokens(i); if (rewardToken != address(0)) { lpRewardsTokensWithEmpties[i] = rewardToken; rewardsTokensCount++; } else { break; } } rewardsTokens_ = new address[](rewardsTokensCount); for (uint256 i; i < rewardsTokensCount; i++) { rewardsTokens_[i] = lpRewardsTokensWithEmpties[i]; } return rewardsTokens_; } /// @dev Helper to stake LP tokens function __curveGaugeV2Stake( address _gauge, address _lpToken, uint256 _amount ) internal { __approveAssetMaxAsNeeded(_lpToken, _gauge, _amount); ICurveLiquidityGaugeV2(_gauge).deposit(_amount, address(this)); } /// @dev Helper to unstake LP tokens function __curveGaugeV2Unstake(address _gauge, uint256 _amount) internal { ICurveLiquidityGaugeV2(_gauge).withdraw(_amount); } }
52,524
0
// USING Registry / Returned by .getRegistry()
interface IRegistry { function owner() external view returns (address _addr); function addressOf(bytes32 _name) external view returns (address _addr); }
interface IRegistry { function owner() external view returns (address _addr); function addressOf(bytes32 _name) external view returns (address _addr); }
1,153
22
// Deposit in wei the creator added when submitting their proposal. It is taken from the msg.value of a newProposal call.
uint proposalDeposit;
uint proposalDeposit;
9,306
18
// Returns the amount of tokens of token type `id` owned by `account`. Requirements: - `account` cannot be the zero address. /
function balanceOf(address account, uint256 id) external view returns (uint256);
function balanceOf(address account, uint256 id) external view returns (uint256);
9,062
54
// Burn the unsold tokens
IERC20(tokenAddress).transfer( DEAD, IERC20(tokenAddress).balanceOf(address(this)) ); emit TokensBurned(IERC20(tokenAddress).balanceOf(address(this)));
IERC20(tokenAddress).transfer( DEAD, IERC20(tokenAddress).balanceOf(address(this)) ); emit TokensBurned(IERC20(tokenAddress).balanceOf(address(this)));
25,769
55
// Execute a token flush from one of the forwarder addresses. This transfer needs only a single signature and can be done by any signerforwarderAddress the address of the forwarder address to flush the tokens from tokenContractAddress the address of the erc20 token contract /
function flushForwarderTokens( address payable forwarderAddress, address tokenContractAddress
function flushForwarderTokens( address payable forwarderAddress, address tokenContractAddress
1,439
45
// ----------------------------------internal--------------------------------------------------------
function statisticsTeam(address _ref,uint256 amount,bool _team) internal{ address up = _ref; for (uint256 i = 0; i < FLOOR; i++) { if (up == address(0)) { break; } if(_team){ umbrellas[up].headcount++; }else{ umbrellas[up].performance+=amount; } up = users[up].referer; } }
function statisticsTeam(address _ref,uint256 amount,bool _team) internal{ address up = _ref; for (uint256 i = 0; i < FLOOR; i++) { if (up == address(0)) { break; } if(_team){ umbrellas[up].headcount++; }else{ umbrellas[up].performance+=amount; } up = users[up].referer; } }
36,749
43
// ็‰นๅฎšใฎใ‚ขใƒ‰ใƒฌใ‚นใซๆŒ‡ๅฎšใ•ใ‚ŒใŸitemใฎ็พๅœจใฎๆ‰€ๆœ‰่€…ใงใ‚ใ‚‹ใ‹ใฉใ†ใ‹ใ‚’ใƒใ‚งใƒƒใ‚ฏใ—ใพใ™ใ€‚/_claimant /_tokenId
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return itemIndexToOwner[_tokenId] == _claimant; }
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return itemIndexToOwner[_tokenId] == _claimant; }
15,667
49
// set control variable adjustment_addition bool_increment uint_target uint_buffer uint /
function setAdjustment ( bool _addition, uint _increment, uint _target, uint _buffer
function setAdjustment ( bool _addition, uint _increment, uint _target, uint _buffer
17,574
52
// The highest ratio of the new price to the anchor price that will still trigger the price to be updated
uint public immutable upperBoundAnchorRatio;
uint public immutable upperBoundAnchorRatio;
4,512
185
// The ETHFUND TOKEN!
ETHFUND public ethfund;
ETHFUND public ethfund;
5,393
1
// return Whether the transfer was successful or not (hint: it is not :)
function transfer(address, uint256) public pure returns (bool) { return false; // there are no tokens so there can be no transfer }
function transfer(address, uint256) public pure returns (bool) { return false; // there are no tokens so there can be no transfer }
42,118
46
// Safe ants transfer function, just in case if rounding error causes pool to not have enough ANTSs.
function safeAntsTransfer(address _to, uint256 _amount) internal { uint256 antsBal = ants.balanceOf(address(this)); if (_amount > antsBal) { ants.transfer(_to, antsBal); } else { ants.transfer(_to, _amount); } }
function safeAntsTransfer(address _to, uint256 _amount) internal { uint256 antsBal = ants.balanceOf(address(this)); if (_amount > antsBal) { ants.transfer(_to, antsBal); } else { ants.transfer(_to, _amount); } }
42,035
6
// ERC20Interface function's implementation / ------------------------------------------------------------------------ Get the total supply of the `token` ------------------------------------------------------------------------
function totalSupply() public override view returns (uint256){ return _totalSupply; }
function totalSupply() public override view returns (uint256){ return _totalSupply; }
49,934
11
// So here we are creating a mask which consists of only ones from the firstOne bit to the lastOne bit
uint256 a = (1 << bitFrom) - 1; uint256 b = (1 << bitTo) - 1; uint256 mask = a ^ b; uint256 onlyNeededBits = (number & mask); return onlyNeededBits >> bitFrom;
uint256 a = (1 << bitFrom) - 1; uint256 b = (1 << bitTo) - 1; uint256 mask = a ^ b; uint256 onlyNeededBits = (number & mask); return onlyNeededBits >> bitFrom;
10,610
212
// A Loot-Derivative Project for the Travel Industry/jacmos3 - TripsCommunity/Text-based NFTs thought for the Travel Industry appannage. Hotels, restaurants, hospitality etc can use them both in the real or metaverse worlds
contract TravelerLoot is ERC721Enumerable, ReentrancyGuard, Ownable { uint256 private constant DISCOUNT_EXPIRATION = 1790553599; //Sun 27 Sep 2026 21:59:59 UTC string private constant WHITE = "white"; string private constant BLACK = "black"; string private constant GOLD = "gold"; string private constant PLATINUM = "#D5D6D8"; string private constant GUILD = "GUILD"; string private constant PATRON = "PATRON"; string private constant CONQUEROR = "CONQUEROR"; uint160 private constant INITIAL_PRICE_FOR_PATRONS = 1 ether; string private constant ERROR_TOKEN_ID_INVALID = "Token ID invalid"; string private constant ERROR_ADDRESS_NOT_VERIFIED = "Address not verified. Try another"; string private constant ERROR_NOT_THE_OWNER = "You do not own token(s) of the address"; string private constant ERROR_DOM_40TH_BIRTHDAY = "Only valid till Dom's 40th bday"; string private constant ERROR_LOW_VALUE = "Set a higher value"; string private constant ERROR_COMPETITION_ENDED = "Competition has ended. Check the Conqueror!"; string private constant ERROR_COMPETITION_ONGOING = "Conqueror not yet elected!"; string private constant ERROR_OWNER_NOT_ALLOWED = "Use claimByOwner() instead"; string private constant ERROR_ALREADY_ACTIVATED = "Already activated"; string private constant ERROR_COME_BACK_LATER = "Come back later"; string private constant ERROR_WITHDRAW_NEEDED = "Treasurer already changed. Perform a withdrawal before changing it"; string private constant ERROR_GUILD_ALREADY_WHITELISTED = "Guild already whitelisted!"; string private constant ERROR_CANNOT_ADD_THIS_CONTRACT = "Not possible"; string private constant ERROR_NOT_ENTITLED = "Check conditions before whitelisting"; address private constant INITIAL_TREASURER = 0xce73904422880604e78591fD6c758B0D5106dD50; //TripsCommunity address address private constant ADDRESS_OG_LOOT = 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7; address private constant PH_USERS = address(1); address private constant PH_PATRONS = address(2); address private constant PH_OG_LOOT = address(3); address private constant PH_CONQUERORS = address(4); address private constant PH_OWNER = address(0); uint16 public constant MAX_ID = 10000; uint16 public constant MAX_FOR_OWNER = 100; uint16 public constant MAX_FOR_GUILDS = 900; uint16 public constant LOCK_TIME = 5760 * 3; //it's three days struct Traveler { string familyType; string familyName; string color; uint256 counter; bool verified; } struct Conqueror { address addr; uint16 count; bool elected; } struct Treasurer { address old; address current; uint256 blockNumber; } struct Initial{ address addr; string symbol; } Conqueror public conqueror; Treasurer public treasurer; bool public canChangeTreasurer = true; mapping(address => Traveler) public detailsByAddress; mapping(uint256 => address) public addressList; uint8 public counterOwner = 0; uint16 public counterStandard = 0; uint16 public counterGuild = 0; uint16 public counterPatrons = 0; uint160 public priceForPatrons = INITIAL_PRICE_FOR_PATRONS; uint256 public blockActivation = 0; string[] private categories = ["ENVIRONMENT","TALENT","PLACE","CHARACTER","TRANSPORT","LANGUAGE","EXPERIENCE","OCCUPATION","ACCOMMODATION","BAG"]; address[] public whiteListedGuilds; mapping(string => string[]) elements; constructor() ERC721("TravelerLoot", "TRVLR") Ownable(){ uint256 blockNumber = block.number; treasurer.old = address(0); treasurer.current = INITIAL_TREASURER; treasurer.blockNumber = blockNumber; elements[categories[0]] = ["Beaches", "Mountains", "Urban", "Countrysides", "Lakes", "Rivers", "Farms", "Tropical areas", "Snowy places", "Forests", "Historical cities", "Islands", "Wilderness", "Deserts", "Natural parks", "Old towns", "Lakes", "Villages", "Forests", "Coral Reefs", "Wetlands", "Rainforests", "Grasslands", "Chaparral"]; elements[categories[1]] = ["Cooking", "Painting", "Basketball", "Tennis", "Football", "Soccer", "Climbing", "Surfing", "Photographer", "Fishing", "Painting", "Writing", "Dancing", "Architecture", "Singing", "Dancing", "Baking", "Running", "Sword-fighting", "Boxing", "Jumping", "Climbing", "Hiking", "Kitesurfing", "Sailing", "Comforting others", "Flipping NFTs", "Katana sword fighter", "Programming Solidity", "Creating Memes"]; elements[categories[2]] = ["Eiffel Tower", "Colosseum", "Taj Mahal", "Forbidden City", "Las Vegas", "Sagrada Familia", "Statue of Liberty", "Pompeii", "Tulum", "St. Peter's Basilica", "Bangkok", "Tower of London", "Alhambra", "San Marco Square", "Ciudad de las Artes y las Ciencias", "Moscow Kremlin", "Copacabana", "Great Wall of China", "Havana", "Arc de Triomphe", "Neuschwanstein Castle", "Machu Picchu", "Gili Islands", "Maya Bay", "Etherscan", "0x0000000000000000000000000000000000000000", "::1", "42.452483,-6.051345","Parcel 0, CityDAO", "Wyoming"]; elements[categories[3]] = ["Energetic", "Good-Natured", "Enthusiastic", "Challenging", "Charismatic", "Wise", "Modest", "Honest", "Protective", "Perceptive", "Providential", "Prudent", "Spontaneous", "Insightful", "Intelligent", "Intuitive", "Precise", "Sharing", "Simple", "Sociable", "Sophisticated", "Benevolent", "Admirable", "Brilliant", "Accessible", "Calm", "Capable", "Optimistic", "Respectful", "Responsible"]; elements[categories[4]] = ["Train", "Car", "Airplane", "Cruise", "4 wheel drive car", "Bus", "Convertible car", "Bicycle", "Motorbike", "Campervan", "Trailer", "Sailboat", "Electric car", "Sidecar", "Scooter", "Tram", "Cinquecento", "Hitch-hiking", "VW Beetle", "VW Bus", "Truck", "Off-road Vehicle", "Cab", "Lambo", "Ferrari", "Rocket", "DeLorean", "Kia Sedona", "Magic carpet", "Broomstick"]; elements[categories[5]] = ["English", "Mandarin Chinese", "Hindi", "Spanish", "Arabic", "French", "Russian", "Portuguese", "Indonesian", "German", "Japanese", "Turkish", "Korean", "Vietnamese", "Iranian Persian", "Swahili", "Javanese", "Italian", "Thai", "Filipino", "Burmese", "Polish", "Croatian", "Danish", "Serbian", "Slovenian", "Czech", "Slovakian", "Greek", "Hungarian"]; elements[categories[6]] = ["2", "3", "4", "5", "6", "7", "8", "9","10","100","0","1"]; elements[categories[7]] = ["Host", "Cook", "Writer", "DeeJay", "Employee", "Doctor", "Traveler", "Tour Guide", "Ship Pilot", "DAO Member", "Driver", "NFT flipper", "Meme creator", "Sales Manager", "Play 2 Earner", "NFT collector", "Hotel receptionist", "Hotel Manager", "Digital Nomad", "Crypto Trader", "Head of Growth", "PoS validator", "Lightning Network Developer", "Anonymous DeFi Protocol Lead", "Yacht owner (in bull markets)", "Web3 Engineer", "Blockchain Consultant", "Crypto VC", "Miner","Metaverse Realtor"]; elements[categories[8]] = ["Hotel", "Apartment", "Hostel", "Tent", "BnB", "Guest House", "Chalet", "Cottage", "Boat", "Caravan", "Motorhome", "5 stars Hotel", "Suite in 5 Stars Hotel", "Tipi", "Tree House", "Bungalow", "Ranch", "Co-living", "Gablefront cottage", "Longhouse", "Villa", "Yurt", "Housebarn", "Adobe House", "Castle", "Rammed earth", "Underground living", "Venetian palace", "Igloo", "Trullo"]; elements[categories[9]] = ["Pen", "eBook reader", "Water", "Cigarettes", "Swiss knife", "Mobile phone", "Notebook", "Laptop", "Digital Camera", "Lighter", "Earphones", "Beauty case", "Toothbrush", "Toothpaste", "Slippers", "Shirts", "Pants", "T-shirts", "Socks", "Underwear","Condoms"]; detailsByAddress[PH_USERS] = Traveler({color:BLACK,familyType:"",familyName:"",counter:0,verified:true}); detailsByAddress[PH_PATRONS] = Traveler({color:"#F87151",familyType:PATRON,familyName:"",counter:0,verified:true}); detailsByAddress[PH_OG_LOOT] = Traveler({color:GOLD,familyType:PATRON,familyName:"Loot (for Adventurers)",counter:0,verified:true}); detailsByAddress[PH_CONQUERORS] = Traveler({color:WHITE,familyType:CONQUEROR,familyName:"",counter:0,verified:true}); detailsByAddress[PH_OWNER] = Traveler({color:BLACK,familyType:" ",familyName:"",counter:0,verified:true}); whiteListedGuilds.push(ADDRESS_OG_LOOT); detailsByAddress[ADDRESS_OG_LOOT] = Traveler({color:BLACK,familyType:PLATINUM,familyName:"LOOT",counter:0,verified:true}); } modifier checkStart() { require(blockActivation > 0 && block.number >= blockActivation,ERROR_COME_BACK_LATER); _; } /// @notice Everyone can claim an available tokenId for free (+ gas) function claim() external nonReentrant checkStart { require(owner() != _msgSender(),ERROR_OWNER_NOT_ALLOWED); uint16 adjusted = 1 + counterStandard + MAX_FOR_GUILDS + MAX_FOR_OWNER; require(adjusted <= MAX_ID, ERROR_TOKEN_ID_INVALID); processing(adjusted,PH_USERS,1,false); _safeMint(_msgSender(), adjusted); counterStandard++; } /// @notice Guilds can use this function to mint a forged Traveler Loot. /// Forged TLs are recognizable by a colored line on the NFT. /// When all the forgeable TLs are minted, the guild who forged /// the most becomes Conqueror. Its members gain access to /// claimByConquerors() function /// @param tokenId derivative's tokenId owned by the user /// @param contractAddress derivative's address pretending to be guild function claimByGuilds(uint256 tokenId, address contractAddress) external nonReentrant checkStart{ require(!conqueror.elected, ERROR_COMPETITION_ENDED); Traveler storage details = detailsByAddress[contractAddress]; require(details.verified, ERROR_ADDRESS_NOT_VERIFIED); IERC721 looter = IERC721(contractAddress); require(tokenId > 0 && looter.ownerOf(tokenId) == _msgSender(), ERROR_NOT_THE_OWNER); if (details.counter == 0 && contractAddress != whiteListedGuilds[0]){ details.color = pickAColor(); } uint16 discretId = uint16(tokenId % MAX_FOR_GUILDS); if (counterGuild == MAX_FOR_GUILDS - 1 ){ (conqueror.addr, conqueror.count) = whoIsWinning(); conqueror.elected = true; detailsByAddress[PH_CONQUERORS].color = details.color; detailsByAddress[PH_CONQUERORS].familyName = details.familyName; } // after this mint, the price for patrons will be increased by 1% uint16 finalId = discretId == 0 ? MAX_FOR_GUILDS : discretId; processing(finalId, contractAddress, 1, true); _safeMint(_msgSender(), finalId); counterGuild++; } /// @notice Becoming a Patron. Requires payment function claimByPatrons() external payable nonReentrant checkStart{ require(msg.value >= priceForPatrons, ERROR_LOW_VALUE); if (priceForPatrons < INITIAL_PRICE_FOR_PATRONS){ priceForPatrons == INITIAL_PRICE_FOR_PATRONS; } // After this mint, the price for next patrons will be increased by 5% reservedMinting(PH_PATRONS, 5, true); counterPatrons++; } /// @notice - Loot (for Adventurers) holders can become Patrons for free if: /// . the Conqueror Guild is not yet elected, /// . or Dominik Hoffman (@ dhof on twitter) is still younger than 40 y/o. function claimByOGLooters() external nonReentrant checkStart{ require(IERC721(whiteListedGuilds[0]).balanceOf(_msgSender()) > 0, ERROR_NOT_THE_OWNER); require(!conqueror.elected, ERROR_COMPETITION_ENDED); require(block.timestamp <= DISCOUNT_EXPIRATION, ERROR_DOM_40TH_BIRTHDAY); // After this mint, the price for patrons will be decreased by 5% reservedMinting(PH_OG_LOOT, 5, false); counterPatrons++; } /// @notice Conquerors can mint a CONQUEROR Traveler Loot for free + gas /// only valid if they have not already minted a PATRON type before function claimByConquerors() external nonReentrant checkStart{ require(conqueror.elected, ERROR_COMPETITION_ONGOING); require(IERC721(conqueror.addr).balanceOf(_msgSender()) > 0, ERROR_NOT_THE_OWNER); // After this mint, the price for patrons is increased by 2% reservedMinting(PH_CONQUERORS, 2, true); counterPatrons++; } /// @notice Owner can claim its reserved tokenIds. function claimByOwner() external nonReentrant onlyOwner checkStart{ uint16 adjusted = 1 + counterOwner + MAX_FOR_GUILDS; require(adjusted <= MAX_FOR_GUILDS + MAX_FOR_OWNER, ERROR_TOKEN_ID_INVALID); //after this mint, the price for patrons will remain the same processing(adjusted,PH_OWNER,0,true); _safeMint(_msgSender(), adjusted); counterOwner++; } /// @notice Owner can call this function to activate the mintings. /// Note that the activation is delayed of LOCK_TIME blocks function activateClaims() external onlyOwner{ require (blockActivation == 0, ERROR_ALREADY_ACTIVATED); blockActivation = block.number + LOCK_TIME; } /// @notice Owner can order the withdraw all the funds coming from Patron mints /// to the Treasurer address previously set. function withdraw() external onlyOwner { require(block.number >= treasurer.blockNumber, ERROR_COME_BACK_LATER); canChangeTreasurer = true; //release treasurer payable(treasurer.current).transfer(address(this).balance); } /// @notice . Owner calls this function with lockTreasurer = true if the intent is /// to do a donation to a public-good project. Lock guarantees that nobody /// (not even the owner) can change treasurer till the donation is made. /// . Owner calls this function with lockTreasurer = false if the intent is /// to keep open the chance to change the treasurer even if no any /// withdrawal has been performed in the meanwhile. /// @param newAddress the new treasurer address /// @param lockTreasurer true if the the treasurer has to be locked till one withdraw is performed function setTreasurer(address newAddress, bool lockTreasurer) external onlyOwner{ require(canChangeTreasurer, ERROR_WITHDRAW_NEEDED); //this is a safety measure for when donating to public goods if (lockTreasurer){ canChangeTreasurer = false; } uint256 blockNumber = block.number + LOCK_TIME; treasurer.old = treasurer.current; treasurer.current = newAddress; treasurer.blockNumber = blockNumber; } /// @notice You can register new Guilds to the whitelist, if: /// - You own at least 50 Traveler Loots in your address /// - Or if you have mint a Patron version by using claimByPatrons() or /// claimByOGLooters() functions (no matter if you dont own them anymore) /// - Or if you are the owner of this Contract /// NOTE: no Guilds can be registered once the competition has ended /// @param addresses List of contract addresses to be whitelisted for the game. /// They'll be allowed to mint GUILD type Traveler Loot function addNewGuildToWhiteList(address[] calldata addresses) nonReentrant external { require(!conqueror.elected, ERROR_COMPETITION_ENDED); for (uint8 j = 0; j< addresses.length; j++){ address addr = addresses[j]; require(address(this) != addr, ERROR_CANNOT_ADD_THIS_CONTRACT); require(IERC721(address(this)).balanceOf(_msgSender()) > 50 || _exists(uint160(_msgSender())) || owner() == _msgSender() ,ERROR_NOT_ENTITLED); for (uint16 i = 0; i < whiteListedGuilds.length; i++){ require(whiteListedGuilds[i] != addr, ERROR_GUILD_ALREADY_WHITELISTED); } whiteListedGuilds.push(addr); detailsByAddress[addr] = Traveler({color:BLACK,familyType:GUILD,familyName:familyName(addr),counter:0,verified:true}); } } /// @notice Given a Guild address, returns the count for that addr /// @param addr Address of the Guild to be checked (the contract address) /// @return Number of the NFT minted from the members of the given Guild address function getCounterForAddress(address addr) external view returns (uint256){ Traveler memory details = detailsByAddress[addr]; require(details.verified, ERROR_ADDRESS_NOT_VERIFIED); return details.counter; } /// @notice Call this function if you want to know the list of the current Guilds /// return Array containing the addresses of all the whitelisted guilds function getWhiteListedGuilds() external view returns (address[] memory){ return whiteListedGuilds; } /// @notice Call this function to see the element for a given tokenId and categoryId /// @param tokenId The id of the Traveler Loot you want to check /// @param categoryId The category of the Traveler Loot you want to check /// @return The element of the given Token Id for the given categoryId function getElement(uint256 tokenId, uint8 categoryId) public view returns (string memory){ return pluck(tokenId, categories[categoryId], elements[categories[categoryId]]); } /// @notice Provides metadata and image of the PATRONS and CONQUEROR /// @param addr Address of the user who minted the PATRON or CONQUEROR you are checking /// @return The json containing the NFT info function addressURI(address addr) external view returns (string memory){ return tokenURI(uint160(addr)); } /// @notice Provides metadata and image of the Traveler Loot /// @param tokenId Token if of the Traveler Loot to process /// @return The json containing the NFT info function tokenURI(uint256 tokenId) override public view returns (string memory) { Traveler memory details = detailsByAddress[addressList[tokenId]]; string[4] memory parts; parts[0] = string(abi.encodePacked('<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.b { fill:white; font-family: serif; font-size: 14px; }</style> <rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="b">')); parts[1] = string(abi.encodePacked(getElement(tokenId,0),'</text><text x="10" y="40" class="b">',getElement(tokenId,1),'</text><text x="10" y="60" class="b">',getElement(tokenId,2),'</text><text x="10" y="80" class="b">',getElement(tokenId,3),'</text><text x="10" y="100" class="b">',getElement(tokenId,4),'</text><text x="10" y="120" class="b">',getElement(tokenId,5))); parts[2] = string(abi.encodePacked('</text><text x="10" y="140" class="b">',getElement(tokenId,6),'</text><text x="10" y="160" class="b">',getElement(tokenId,7),'</text><text x="10" y="180" class="b">',getElement(tokenId,8),'</text><text x="10" y="200" class="b">',getElement(tokenId,9),'</text>')); parts[3] = string(abi.encodePacked('<line x1="0" x2="350" y1="300" y2="300" stroke="',details.color,'" stroke-width="4"/>','<text x="340" y="294" text-anchor="end" class="b">',details.familyType,'</text></svg>')); string memory compact = string(abi.encodePacked(parts[0], parts[1], parts[2],parts[3])); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Traveler #', toString(tokenId), '", "description": "Traveler Loot is a Loot derivative for the Travel Industry, generated and stored on chain. Feel free to use the Traveler Loot in any way you want", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(compact)), '","attributes":[',metadata(tokenId,details),']}')))); return string(abi.encodePacked('data:application/json;base64,', json)); } /// @notice Call this method to check the Guild which is owning the most Forged Traveler Loot /// /// @return The address of the guild who has the most Forged Traveler Loot so far /// @return The amount of Forged Traveler Loot minted by the Winning Guild so far function whoIsWinning() public view returns (address, uint16){ if (conqueror.elected){ return (conqueror.addr,conqueror.count); } address winningLoot = whiteListedGuilds[0]; uint16 winningCount = uint16(detailsByAddress[winningLoot].counter); for (uint8 i = 1; i < whiteListedGuilds.length; i++){ address addr = whiteListedGuilds[i]; (winningLoot, winningCount) = checkWinning(winningLoot,winningCount, addr, uint16(detailsByAddress[addr].counter)); } return (winningLoot, winningCount); } /// @notice Call this function to get a random color using block difficulty, timestamp as seed /// @return A string containing the HEX number of a random color function pickAColor() internal view returns (string memory){ string[16] memory list = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]; string memory color = "#"; for (uint8 i=0; i<6;i++){ uint rand = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, i ))); color = string(abi.encodePacked(color,list[rand % list.length])); } return color; } /// @notice This function calls an external NFT contract and gets the symbol to be used into the metadata /// @param addr The address of the contract address to whitelist /// @return The symbol of the given external contract address function familyName(address addr) internal view returns (string memory){ return IERC721Metadata(addr).symbol(); } function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } /// @notice Update the PATRON price and the address counter /// @param id TokenId minted /// @param addr address Guild of the token to mint /// @param percentage percentage number of the PATRON'price variability /// @param isPositive true if the variability is positive, false if it's negative function processing(uint256 id, address addr, uint8 percentage, bool isPositive) internal{ if (percentage != 0){ uint160 x = priceForPatrons / (100 / percentage); priceForPatrons = isPositive ? priceForPatrons + x : priceForPatrons - x; } detailsByAddress[addr].counter++; addressList[id] = addr; } /// @notice It mints the Traveler Loot using the address as tokenId. /// Only particular cases can access to this: /// - Users who decide to become Patrons by paying the patronPrice /// - Conqueror Guild members, as the prize for have won the competition /// - OG Loot owners, as privilegiate users till @ dhof 40 bday or till Conqueror Guild election /// @param addr address Guild of the token to mint /// @param percentage percentage number of the PATRON'price variability /// @param isPositive true if the variability is positive, false if it's negative function reservedMinting(address addr,uint8 percentage, bool isPositive) internal{ uint160 castedAddress = uint160(_msgSender()); require(castedAddress > MAX_ID, ERROR_ADDRESS_NOT_VERIFIED); processing(castedAddress, addr, percentage, isPositive); _safeMint(_msgSender(), castedAddress); } /// @notice Call this function to get pick the element for a given Traveler Loot id and category /// @param tokenId TokenId /// @param keyPrefix Seed/nounce of the randomity /// @param sourceArray The list of all the elements /// @return The element extracted function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal view returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); uint8 toHoundred = uint8(rand % 100); uint8 delta = toHoundred > 95 ? 1 : toHoundred > 80 ? 2 : 3; uint8 len = uint8(sourceArray.length); uint8 x = len / 3; uint8 min = len - (delta * x); uint8 max = (len - 1) - ((delta - 1) * x); uint8 rand2 = uint8((random(string(abi.encodePacked(msg.sender, toHoundred, keyPrefix ))) % (max - min + 1)) + min); return sourceArray[rand2]; } /// @dev This function processes and build the metadata for the given tokenId /// @param tokenId TokenId /// @param details The details to be used for filling the metadata /// @return The json with the metadata to be appended to the full json function metadata(uint256 tokenId, Traveler memory details) internal view returns (string memory){ string memory toRet = ""; for (uint8 i = 0; i < 10; i++){ toRet = string(abi.encodePacked(toRet,'{"trait_type":"', categories[i], '","value":"',getElement(tokenId,i),'"},')); } if (keccak256(abi.encodePacked(details.color)) != keccak256(abi.encodePacked(BLACK))) { toRet = string(abi.encodePacked(toRet,'{"trait_type":"Type","value":"',details.familyType,'"}')); toRet = string(abi.encodePacked(toRet,',{"trait_type":"Flag Color","value":"',details.color,'"}')); toRet = string(abi.encodePacked(toRet,',{"trait_type":"',details.familyType,'","value":"',details.familyName,'"}')); } else{ toRet = string(abi.encodePacked(toRet,'{"trait_type":"Type","value":"EXPLORER"}')); } return toRet; } /// @dev This function compares two Guilds and check which has more Froged Guild already minted /// @param winningAddress The legacy winning address (so far) /// @param winningCount The amount for the legacy winning address (so far) /// @param newAddress The new address to compare with legacy /// @param newCount The new amount to compare with legacy /// @return The new winning address after comparison /// @return The new minted amount of winning address after comparison function checkWinning(address winningAddress, uint16 winningCount, address newAddress, uint16 newCount) internal pure returns(address,uint16){ return newCount > winningCount ? (newAddress, newCount) : (winningAddress, winningCount); } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
contract TravelerLoot is ERC721Enumerable, ReentrancyGuard, Ownable { uint256 private constant DISCOUNT_EXPIRATION = 1790553599; //Sun 27 Sep 2026 21:59:59 UTC string private constant WHITE = "white"; string private constant BLACK = "black"; string private constant GOLD = "gold"; string private constant PLATINUM = "#D5D6D8"; string private constant GUILD = "GUILD"; string private constant PATRON = "PATRON"; string private constant CONQUEROR = "CONQUEROR"; uint160 private constant INITIAL_PRICE_FOR_PATRONS = 1 ether; string private constant ERROR_TOKEN_ID_INVALID = "Token ID invalid"; string private constant ERROR_ADDRESS_NOT_VERIFIED = "Address not verified. Try another"; string private constant ERROR_NOT_THE_OWNER = "You do not own token(s) of the address"; string private constant ERROR_DOM_40TH_BIRTHDAY = "Only valid till Dom's 40th bday"; string private constant ERROR_LOW_VALUE = "Set a higher value"; string private constant ERROR_COMPETITION_ENDED = "Competition has ended. Check the Conqueror!"; string private constant ERROR_COMPETITION_ONGOING = "Conqueror not yet elected!"; string private constant ERROR_OWNER_NOT_ALLOWED = "Use claimByOwner() instead"; string private constant ERROR_ALREADY_ACTIVATED = "Already activated"; string private constant ERROR_COME_BACK_LATER = "Come back later"; string private constant ERROR_WITHDRAW_NEEDED = "Treasurer already changed. Perform a withdrawal before changing it"; string private constant ERROR_GUILD_ALREADY_WHITELISTED = "Guild already whitelisted!"; string private constant ERROR_CANNOT_ADD_THIS_CONTRACT = "Not possible"; string private constant ERROR_NOT_ENTITLED = "Check conditions before whitelisting"; address private constant INITIAL_TREASURER = 0xce73904422880604e78591fD6c758B0D5106dD50; //TripsCommunity address address private constant ADDRESS_OG_LOOT = 0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7; address private constant PH_USERS = address(1); address private constant PH_PATRONS = address(2); address private constant PH_OG_LOOT = address(3); address private constant PH_CONQUERORS = address(4); address private constant PH_OWNER = address(0); uint16 public constant MAX_ID = 10000; uint16 public constant MAX_FOR_OWNER = 100; uint16 public constant MAX_FOR_GUILDS = 900; uint16 public constant LOCK_TIME = 5760 * 3; //it's three days struct Traveler { string familyType; string familyName; string color; uint256 counter; bool verified; } struct Conqueror { address addr; uint16 count; bool elected; } struct Treasurer { address old; address current; uint256 blockNumber; } struct Initial{ address addr; string symbol; } Conqueror public conqueror; Treasurer public treasurer; bool public canChangeTreasurer = true; mapping(address => Traveler) public detailsByAddress; mapping(uint256 => address) public addressList; uint8 public counterOwner = 0; uint16 public counterStandard = 0; uint16 public counterGuild = 0; uint16 public counterPatrons = 0; uint160 public priceForPatrons = INITIAL_PRICE_FOR_PATRONS; uint256 public blockActivation = 0; string[] private categories = ["ENVIRONMENT","TALENT","PLACE","CHARACTER","TRANSPORT","LANGUAGE","EXPERIENCE","OCCUPATION","ACCOMMODATION","BAG"]; address[] public whiteListedGuilds; mapping(string => string[]) elements; constructor() ERC721("TravelerLoot", "TRVLR") Ownable(){ uint256 blockNumber = block.number; treasurer.old = address(0); treasurer.current = INITIAL_TREASURER; treasurer.blockNumber = blockNumber; elements[categories[0]] = ["Beaches", "Mountains", "Urban", "Countrysides", "Lakes", "Rivers", "Farms", "Tropical areas", "Snowy places", "Forests", "Historical cities", "Islands", "Wilderness", "Deserts", "Natural parks", "Old towns", "Lakes", "Villages", "Forests", "Coral Reefs", "Wetlands", "Rainforests", "Grasslands", "Chaparral"]; elements[categories[1]] = ["Cooking", "Painting", "Basketball", "Tennis", "Football", "Soccer", "Climbing", "Surfing", "Photographer", "Fishing", "Painting", "Writing", "Dancing", "Architecture", "Singing", "Dancing", "Baking", "Running", "Sword-fighting", "Boxing", "Jumping", "Climbing", "Hiking", "Kitesurfing", "Sailing", "Comforting others", "Flipping NFTs", "Katana sword fighter", "Programming Solidity", "Creating Memes"]; elements[categories[2]] = ["Eiffel Tower", "Colosseum", "Taj Mahal", "Forbidden City", "Las Vegas", "Sagrada Familia", "Statue of Liberty", "Pompeii", "Tulum", "St. Peter's Basilica", "Bangkok", "Tower of London", "Alhambra", "San Marco Square", "Ciudad de las Artes y las Ciencias", "Moscow Kremlin", "Copacabana", "Great Wall of China", "Havana", "Arc de Triomphe", "Neuschwanstein Castle", "Machu Picchu", "Gili Islands", "Maya Bay", "Etherscan", "0x0000000000000000000000000000000000000000", "::1", "42.452483,-6.051345","Parcel 0, CityDAO", "Wyoming"]; elements[categories[3]] = ["Energetic", "Good-Natured", "Enthusiastic", "Challenging", "Charismatic", "Wise", "Modest", "Honest", "Protective", "Perceptive", "Providential", "Prudent", "Spontaneous", "Insightful", "Intelligent", "Intuitive", "Precise", "Sharing", "Simple", "Sociable", "Sophisticated", "Benevolent", "Admirable", "Brilliant", "Accessible", "Calm", "Capable", "Optimistic", "Respectful", "Responsible"]; elements[categories[4]] = ["Train", "Car", "Airplane", "Cruise", "4 wheel drive car", "Bus", "Convertible car", "Bicycle", "Motorbike", "Campervan", "Trailer", "Sailboat", "Electric car", "Sidecar", "Scooter", "Tram", "Cinquecento", "Hitch-hiking", "VW Beetle", "VW Bus", "Truck", "Off-road Vehicle", "Cab", "Lambo", "Ferrari", "Rocket", "DeLorean", "Kia Sedona", "Magic carpet", "Broomstick"]; elements[categories[5]] = ["English", "Mandarin Chinese", "Hindi", "Spanish", "Arabic", "French", "Russian", "Portuguese", "Indonesian", "German", "Japanese", "Turkish", "Korean", "Vietnamese", "Iranian Persian", "Swahili", "Javanese", "Italian", "Thai", "Filipino", "Burmese", "Polish", "Croatian", "Danish", "Serbian", "Slovenian", "Czech", "Slovakian", "Greek", "Hungarian"]; elements[categories[6]] = ["2", "3", "4", "5", "6", "7", "8", "9","10","100","0","1"]; elements[categories[7]] = ["Host", "Cook", "Writer", "DeeJay", "Employee", "Doctor", "Traveler", "Tour Guide", "Ship Pilot", "DAO Member", "Driver", "NFT flipper", "Meme creator", "Sales Manager", "Play 2 Earner", "NFT collector", "Hotel receptionist", "Hotel Manager", "Digital Nomad", "Crypto Trader", "Head of Growth", "PoS validator", "Lightning Network Developer", "Anonymous DeFi Protocol Lead", "Yacht owner (in bull markets)", "Web3 Engineer", "Blockchain Consultant", "Crypto VC", "Miner","Metaverse Realtor"]; elements[categories[8]] = ["Hotel", "Apartment", "Hostel", "Tent", "BnB", "Guest House", "Chalet", "Cottage", "Boat", "Caravan", "Motorhome", "5 stars Hotel", "Suite in 5 Stars Hotel", "Tipi", "Tree House", "Bungalow", "Ranch", "Co-living", "Gablefront cottage", "Longhouse", "Villa", "Yurt", "Housebarn", "Adobe House", "Castle", "Rammed earth", "Underground living", "Venetian palace", "Igloo", "Trullo"]; elements[categories[9]] = ["Pen", "eBook reader", "Water", "Cigarettes", "Swiss knife", "Mobile phone", "Notebook", "Laptop", "Digital Camera", "Lighter", "Earphones", "Beauty case", "Toothbrush", "Toothpaste", "Slippers", "Shirts", "Pants", "T-shirts", "Socks", "Underwear","Condoms"]; detailsByAddress[PH_USERS] = Traveler({color:BLACK,familyType:"",familyName:"",counter:0,verified:true}); detailsByAddress[PH_PATRONS] = Traveler({color:"#F87151",familyType:PATRON,familyName:"",counter:0,verified:true}); detailsByAddress[PH_OG_LOOT] = Traveler({color:GOLD,familyType:PATRON,familyName:"Loot (for Adventurers)",counter:0,verified:true}); detailsByAddress[PH_CONQUERORS] = Traveler({color:WHITE,familyType:CONQUEROR,familyName:"",counter:0,verified:true}); detailsByAddress[PH_OWNER] = Traveler({color:BLACK,familyType:" ",familyName:"",counter:0,verified:true}); whiteListedGuilds.push(ADDRESS_OG_LOOT); detailsByAddress[ADDRESS_OG_LOOT] = Traveler({color:BLACK,familyType:PLATINUM,familyName:"LOOT",counter:0,verified:true}); } modifier checkStart() { require(blockActivation > 0 && block.number >= blockActivation,ERROR_COME_BACK_LATER); _; } /// @notice Everyone can claim an available tokenId for free (+ gas) function claim() external nonReentrant checkStart { require(owner() != _msgSender(),ERROR_OWNER_NOT_ALLOWED); uint16 adjusted = 1 + counterStandard + MAX_FOR_GUILDS + MAX_FOR_OWNER; require(adjusted <= MAX_ID, ERROR_TOKEN_ID_INVALID); processing(adjusted,PH_USERS,1,false); _safeMint(_msgSender(), adjusted); counterStandard++; } /// @notice Guilds can use this function to mint a forged Traveler Loot. /// Forged TLs are recognizable by a colored line on the NFT. /// When all the forgeable TLs are minted, the guild who forged /// the most becomes Conqueror. Its members gain access to /// claimByConquerors() function /// @param tokenId derivative's tokenId owned by the user /// @param contractAddress derivative's address pretending to be guild function claimByGuilds(uint256 tokenId, address contractAddress) external nonReentrant checkStart{ require(!conqueror.elected, ERROR_COMPETITION_ENDED); Traveler storage details = detailsByAddress[contractAddress]; require(details.verified, ERROR_ADDRESS_NOT_VERIFIED); IERC721 looter = IERC721(contractAddress); require(tokenId > 0 && looter.ownerOf(tokenId) == _msgSender(), ERROR_NOT_THE_OWNER); if (details.counter == 0 && contractAddress != whiteListedGuilds[0]){ details.color = pickAColor(); } uint16 discretId = uint16(tokenId % MAX_FOR_GUILDS); if (counterGuild == MAX_FOR_GUILDS - 1 ){ (conqueror.addr, conqueror.count) = whoIsWinning(); conqueror.elected = true; detailsByAddress[PH_CONQUERORS].color = details.color; detailsByAddress[PH_CONQUERORS].familyName = details.familyName; } // after this mint, the price for patrons will be increased by 1% uint16 finalId = discretId == 0 ? MAX_FOR_GUILDS : discretId; processing(finalId, contractAddress, 1, true); _safeMint(_msgSender(), finalId); counterGuild++; } /// @notice Becoming a Patron. Requires payment function claimByPatrons() external payable nonReentrant checkStart{ require(msg.value >= priceForPatrons, ERROR_LOW_VALUE); if (priceForPatrons < INITIAL_PRICE_FOR_PATRONS){ priceForPatrons == INITIAL_PRICE_FOR_PATRONS; } // After this mint, the price for next patrons will be increased by 5% reservedMinting(PH_PATRONS, 5, true); counterPatrons++; } /// @notice - Loot (for Adventurers) holders can become Patrons for free if: /// . the Conqueror Guild is not yet elected, /// . or Dominik Hoffman (@ dhof on twitter) is still younger than 40 y/o. function claimByOGLooters() external nonReentrant checkStart{ require(IERC721(whiteListedGuilds[0]).balanceOf(_msgSender()) > 0, ERROR_NOT_THE_OWNER); require(!conqueror.elected, ERROR_COMPETITION_ENDED); require(block.timestamp <= DISCOUNT_EXPIRATION, ERROR_DOM_40TH_BIRTHDAY); // After this mint, the price for patrons will be decreased by 5% reservedMinting(PH_OG_LOOT, 5, false); counterPatrons++; } /// @notice Conquerors can mint a CONQUEROR Traveler Loot for free + gas /// only valid if they have not already minted a PATRON type before function claimByConquerors() external nonReentrant checkStart{ require(conqueror.elected, ERROR_COMPETITION_ONGOING); require(IERC721(conqueror.addr).balanceOf(_msgSender()) > 0, ERROR_NOT_THE_OWNER); // After this mint, the price for patrons is increased by 2% reservedMinting(PH_CONQUERORS, 2, true); counterPatrons++; } /// @notice Owner can claim its reserved tokenIds. function claimByOwner() external nonReentrant onlyOwner checkStart{ uint16 adjusted = 1 + counterOwner + MAX_FOR_GUILDS; require(adjusted <= MAX_FOR_GUILDS + MAX_FOR_OWNER, ERROR_TOKEN_ID_INVALID); //after this mint, the price for patrons will remain the same processing(adjusted,PH_OWNER,0,true); _safeMint(_msgSender(), adjusted); counterOwner++; } /// @notice Owner can call this function to activate the mintings. /// Note that the activation is delayed of LOCK_TIME blocks function activateClaims() external onlyOwner{ require (blockActivation == 0, ERROR_ALREADY_ACTIVATED); blockActivation = block.number + LOCK_TIME; } /// @notice Owner can order the withdraw all the funds coming from Patron mints /// to the Treasurer address previously set. function withdraw() external onlyOwner { require(block.number >= treasurer.blockNumber, ERROR_COME_BACK_LATER); canChangeTreasurer = true; //release treasurer payable(treasurer.current).transfer(address(this).balance); } /// @notice . Owner calls this function with lockTreasurer = true if the intent is /// to do a donation to a public-good project. Lock guarantees that nobody /// (not even the owner) can change treasurer till the donation is made. /// . Owner calls this function with lockTreasurer = false if the intent is /// to keep open the chance to change the treasurer even if no any /// withdrawal has been performed in the meanwhile. /// @param newAddress the new treasurer address /// @param lockTreasurer true if the the treasurer has to be locked till one withdraw is performed function setTreasurer(address newAddress, bool lockTreasurer) external onlyOwner{ require(canChangeTreasurer, ERROR_WITHDRAW_NEEDED); //this is a safety measure for when donating to public goods if (lockTreasurer){ canChangeTreasurer = false; } uint256 blockNumber = block.number + LOCK_TIME; treasurer.old = treasurer.current; treasurer.current = newAddress; treasurer.blockNumber = blockNumber; } /// @notice You can register new Guilds to the whitelist, if: /// - You own at least 50 Traveler Loots in your address /// - Or if you have mint a Patron version by using claimByPatrons() or /// claimByOGLooters() functions (no matter if you dont own them anymore) /// - Or if you are the owner of this Contract /// NOTE: no Guilds can be registered once the competition has ended /// @param addresses List of contract addresses to be whitelisted for the game. /// They'll be allowed to mint GUILD type Traveler Loot function addNewGuildToWhiteList(address[] calldata addresses) nonReentrant external { require(!conqueror.elected, ERROR_COMPETITION_ENDED); for (uint8 j = 0; j< addresses.length; j++){ address addr = addresses[j]; require(address(this) != addr, ERROR_CANNOT_ADD_THIS_CONTRACT); require(IERC721(address(this)).balanceOf(_msgSender()) > 50 || _exists(uint160(_msgSender())) || owner() == _msgSender() ,ERROR_NOT_ENTITLED); for (uint16 i = 0; i < whiteListedGuilds.length; i++){ require(whiteListedGuilds[i] != addr, ERROR_GUILD_ALREADY_WHITELISTED); } whiteListedGuilds.push(addr); detailsByAddress[addr] = Traveler({color:BLACK,familyType:GUILD,familyName:familyName(addr),counter:0,verified:true}); } } /// @notice Given a Guild address, returns the count for that addr /// @param addr Address of the Guild to be checked (the contract address) /// @return Number of the NFT minted from the members of the given Guild address function getCounterForAddress(address addr) external view returns (uint256){ Traveler memory details = detailsByAddress[addr]; require(details.verified, ERROR_ADDRESS_NOT_VERIFIED); return details.counter; } /// @notice Call this function if you want to know the list of the current Guilds /// return Array containing the addresses of all the whitelisted guilds function getWhiteListedGuilds() external view returns (address[] memory){ return whiteListedGuilds; } /// @notice Call this function to see the element for a given tokenId and categoryId /// @param tokenId The id of the Traveler Loot you want to check /// @param categoryId The category of the Traveler Loot you want to check /// @return The element of the given Token Id for the given categoryId function getElement(uint256 tokenId, uint8 categoryId) public view returns (string memory){ return pluck(tokenId, categories[categoryId], elements[categories[categoryId]]); } /// @notice Provides metadata and image of the PATRONS and CONQUEROR /// @param addr Address of the user who minted the PATRON or CONQUEROR you are checking /// @return The json containing the NFT info function addressURI(address addr) external view returns (string memory){ return tokenURI(uint160(addr)); } /// @notice Provides metadata and image of the Traveler Loot /// @param tokenId Token if of the Traveler Loot to process /// @return The json containing the NFT info function tokenURI(uint256 tokenId) override public view returns (string memory) { Traveler memory details = detailsByAddress[addressList[tokenId]]; string[4] memory parts; parts[0] = string(abi.encodePacked('<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.b { fill:white; font-family: serif; font-size: 14px; }</style> <rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="b">')); parts[1] = string(abi.encodePacked(getElement(tokenId,0),'</text><text x="10" y="40" class="b">',getElement(tokenId,1),'</text><text x="10" y="60" class="b">',getElement(tokenId,2),'</text><text x="10" y="80" class="b">',getElement(tokenId,3),'</text><text x="10" y="100" class="b">',getElement(tokenId,4),'</text><text x="10" y="120" class="b">',getElement(tokenId,5))); parts[2] = string(abi.encodePacked('</text><text x="10" y="140" class="b">',getElement(tokenId,6),'</text><text x="10" y="160" class="b">',getElement(tokenId,7),'</text><text x="10" y="180" class="b">',getElement(tokenId,8),'</text><text x="10" y="200" class="b">',getElement(tokenId,9),'</text>')); parts[3] = string(abi.encodePacked('<line x1="0" x2="350" y1="300" y2="300" stroke="',details.color,'" stroke-width="4"/>','<text x="340" y="294" text-anchor="end" class="b">',details.familyType,'</text></svg>')); string memory compact = string(abi.encodePacked(parts[0], parts[1], parts[2],parts[3])); string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Traveler #', toString(tokenId), '", "description": "Traveler Loot is a Loot derivative for the Travel Industry, generated and stored on chain. Feel free to use the Traveler Loot in any way you want", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(compact)), '","attributes":[',metadata(tokenId,details),']}')))); return string(abi.encodePacked('data:application/json;base64,', json)); } /// @notice Call this method to check the Guild which is owning the most Forged Traveler Loot /// /// @return The address of the guild who has the most Forged Traveler Loot so far /// @return The amount of Forged Traveler Loot minted by the Winning Guild so far function whoIsWinning() public view returns (address, uint16){ if (conqueror.elected){ return (conqueror.addr,conqueror.count); } address winningLoot = whiteListedGuilds[0]; uint16 winningCount = uint16(detailsByAddress[winningLoot].counter); for (uint8 i = 1; i < whiteListedGuilds.length; i++){ address addr = whiteListedGuilds[i]; (winningLoot, winningCount) = checkWinning(winningLoot,winningCount, addr, uint16(detailsByAddress[addr].counter)); } return (winningLoot, winningCount); } /// @notice Call this function to get a random color using block difficulty, timestamp as seed /// @return A string containing the HEX number of a random color function pickAColor() internal view returns (string memory){ string[16] memory list = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]; string memory color = "#"; for (uint8 i=0; i<6;i++){ uint rand = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, i ))); color = string(abi.encodePacked(color,list[rand % list.length])); } return color; } /// @notice This function calls an external NFT contract and gets the symbol to be used into the metadata /// @param addr The address of the contract address to whitelist /// @return The symbol of the given external contract address function familyName(address addr) internal view returns (string memory){ return IERC721Metadata(addr).symbol(); } function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } /// @notice Update the PATRON price and the address counter /// @param id TokenId minted /// @param addr address Guild of the token to mint /// @param percentage percentage number of the PATRON'price variability /// @param isPositive true if the variability is positive, false if it's negative function processing(uint256 id, address addr, uint8 percentage, bool isPositive) internal{ if (percentage != 0){ uint160 x = priceForPatrons / (100 / percentage); priceForPatrons = isPositive ? priceForPatrons + x : priceForPatrons - x; } detailsByAddress[addr].counter++; addressList[id] = addr; } /// @notice It mints the Traveler Loot using the address as tokenId. /// Only particular cases can access to this: /// - Users who decide to become Patrons by paying the patronPrice /// - Conqueror Guild members, as the prize for have won the competition /// - OG Loot owners, as privilegiate users till @ dhof 40 bday or till Conqueror Guild election /// @param addr address Guild of the token to mint /// @param percentage percentage number of the PATRON'price variability /// @param isPositive true if the variability is positive, false if it's negative function reservedMinting(address addr,uint8 percentage, bool isPositive) internal{ uint160 castedAddress = uint160(_msgSender()); require(castedAddress > MAX_ID, ERROR_ADDRESS_NOT_VERIFIED); processing(castedAddress, addr, percentage, isPositive); _safeMint(_msgSender(), castedAddress); } /// @notice Call this function to get pick the element for a given Traveler Loot id and category /// @param tokenId TokenId /// @param keyPrefix Seed/nounce of the randomity /// @param sourceArray The list of all the elements /// @return The element extracted function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal view returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); uint8 toHoundred = uint8(rand % 100); uint8 delta = toHoundred > 95 ? 1 : toHoundred > 80 ? 2 : 3; uint8 len = uint8(sourceArray.length); uint8 x = len / 3; uint8 min = len - (delta * x); uint8 max = (len - 1) - ((delta - 1) * x); uint8 rand2 = uint8((random(string(abi.encodePacked(msg.sender, toHoundred, keyPrefix ))) % (max - min + 1)) + min); return sourceArray[rand2]; } /// @dev This function processes and build the metadata for the given tokenId /// @param tokenId TokenId /// @param details The details to be used for filling the metadata /// @return The json with the metadata to be appended to the full json function metadata(uint256 tokenId, Traveler memory details) internal view returns (string memory){ string memory toRet = ""; for (uint8 i = 0; i < 10; i++){ toRet = string(abi.encodePacked(toRet,'{"trait_type":"', categories[i], '","value":"',getElement(tokenId,i),'"},')); } if (keccak256(abi.encodePacked(details.color)) != keccak256(abi.encodePacked(BLACK))) { toRet = string(abi.encodePacked(toRet,'{"trait_type":"Type","value":"',details.familyType,'"}')); toRet = string(abi.encodePacked(toRet,',{"trait_type":"Flag Color","value":"',details.color,'"}')); toRet = string(abi.encodePacked(toRet,',{"trait_type":"',details.familyType,'","value":"',details.familyName,'"}')); } else{ toRet = string(abi.encodePacked(toRet,'{"trait_type":"Type","value":"EXPLORER"}')); } return toRet; } /// @dev This function compares two Guilds and check which has more Froged Guild already minted /// @param winningAddress The legacy winning address (so far) /// @param winningCount The amount for the legacy winning address (so far) /// @param newAddress The new address to compare with legacy /// @param newCount The new amount to compare with legacy /// @return The new winning address after comparison /// @return The new minted amount of winning address after comparison function checkWinning(address winningAddress, uint16 winningCount, address newAddress, uint16 newCount) internal pure returns(address,uint16){ return newCount > winningCount ? (newAddress, newCount) : (winningAddress, winningCount); } function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT license // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
10,817
63
// Returns whether the SetToken component default position real unit is greater than or equal to units passed in. /
function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); }
function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); }
14,980
82
// unwrap to get native tokens
wnative.withdraw(amounts[1]);
wnative.withdraw(amounts[1]);
7,254
404
// If this is the first lot, set this as the max multiplier of the account
if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; }
if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; }
32,595
0
// count number of bytes required to represent an unsigned integer
function count_bytes(uint256 n) pure internal returns (uint256 c) { uint i = 0; uint mask = 1; while (n >= mask) { i += 1; mask *= 256; } return i; }
function count_bytes(uint256 n) pure internal returns (uint256 c) { uint i = 0; uint mask = 1; while (n >= mask) { i += 1; mask *= 256; } return i; }
19,277
113
// data required to create a sequence
struct SequenceCreateData { uint16 sequenceNumber; string name; string description; string image; }
struct SequenceCreateData { uint16 sequenceNumber; string name; string description; string image; }
67,397
6
// Mixin to add support for `ownable()` `Mixins` are a design pattern seen in the 0x contracts.It simplyseparates logically groupings of code to ease readability. /
contract MixinConvenienceOwnable is MixinErrors, MixinLockCore { // used for `owner()`convenience helper address private _convenienceOwner; // events event OwnershipTransferred(address previousOwner, address newOwner); function _initializeMixinConvenienceOwnable(address _sender) internal { _convenienceOwner = _sender; } /** `owner()` is provided as an helper to mimick the `Ownable` contract ABI. * The `Ownable` logic is used by many 3rd party services to determine * contract ownership - e.g. who is allowed to edit metadata on Opensea. * * @notice This logic is NOT used internally by the Unlock Protocol and is made * available only as a convenience helper. */ function owner() public view returns (address) { return _convenienceOwner; } /** Setter for the `owner` convenience helper (see `owner()` docstring for more). * @notice This logic is NOT used internally by the Unlock Protocol ans is made * available only as a convenience helper. * @param account address returned by the `owner()` helper */ function setOwner(address account) public { _onlyLockManager(); if(account == address(0)) { revert OWNER_CANT_BE_ADDRESS_ZERO(); } address _previousOwner = _convenienceOwner; _convenienceOwner = account; emit OwnershipTransferred(_previousOwner, account); } function isOwner(address account) public view returns (bool) { return _convenienceOwner == account; } uint256[1000] private __safe_upgrade_gap; }
contract MixinConvenienceOwnable is MixinErrors, MixinLockCore { // used for `owner()`convenience helper address private _convenienceOwner; // events event OwnershipTransferred(address previousOwner, address newOwner); function _initializeMixinConvenienceOwnable(address _sender) internal { _convenienceOwner = _sender; } /** `owner()` is provided as an helper to mimick the `Ownable` contract ABI. * The `Ownable` logic is used by many 3rd party services to determine * contract ownership - e.g. who is allowed to edit metadata on Opensea. * * @notice This logic is NOT used internally by the Unlock Protocol and is made * available only as a convenience helper. */ function owner() public view returns (address) { return _convenienceOwner; } /** Setter for the `owner` convenience helper (see `owner()` docstring for more). * @notice This logic is NOT used internally by the Unlock Protocol ans is made * available only as a convenience helper. * @param account address returned by the `owner()` helper */ function setOwner(address account) public { _onlyLockManager(); if(account == address(0)) { revert OWNER_CANT_BE_ADDRESS_ZERO(); } address _previousOwner = _convenienceOwner; _convenienceOwner = account; emit OwnershipTransferred(_previousOwner, account); } function isOwner(address account) public view returns (bool) { return _convenienceOwner == account; } uint256[1000] private __safe_upgrade_gap; }
15,611
31
// ends ICO
function closeIco () onlyOwner inIco{ icoOpen = false; }
function closeIco () onlyOwner inIco{ icoOpen = false; }
1,828
223
// extend Aurora stream reward schedule. It can be only called by the default/ contract admin. It can accept extending the schedule if the new schedule is/ not overlapping with the current schedule. Also, it requires to pause the contract before calling it./scheduleTimes timestamp denoting the start of each scheduled interval. Last element is the end of the stream./scheduleRewards remaining rewards to be delivered at the beginning of each scheduled interval. Last element is always zero.
function extendAuroraStreamSchedule( uint256[] memory scheduleTimes, uint256[] memory scheduleRewards
function extendAuroraStreamSchedule( uint256[] memory scheduleTimes, uint256[] memory scheduleRewards
34,177
282
// Check reduceAmount โ‰ค reserves[n] (totalReserves)
if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); }
if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); }
17,408
6
// Returns the pricing premium in wei. /
function premium( string calldata name, uint256 expires, uint256 duration
function premium( string calldata name, uint256 expires, uint256 duration
21,158
80
// in case of change sslp /
function approveSslpToTopDog(IERC20 _sslpToken) public onlyManager { TransferHelper.safeApprove(address(_sslpToken), address(topDog), type(uint256).max); }
function approveSslpToTopDog(IERC20 _sslpToken) public onlyManager { TransferHelper.safeApprove(address(_sslpToken), address(topDog), type(uint256).max); }
29,452
15
// announcement of a new/bidder address of the bidder
event BidMade(address bidder);
event BidMade(address bidder);
31,862
4
// _key The key for the record
function getUint(bytes32 _key) external view returns (uint) { return uintStorage[_key]; }
function getUint(bytes32 _key) external view returns (uint) { return uintStorage[_key]; }
1,388
162
// return result Square root of the number /
function sqrt(uint256 x) private pure returns (uint256 result) { result = x; uint256 k = x.div(2).add(1); while (k < result) (result, k) = (k, x.div(k).add(k).div(2)); }
function sqrt(uint256 x) private pure returns (uint256 result) { result = x; uint256 k = x.div(2).add(1); while (k < result) (result, k) = (k, x.div(k).add(k).div(2)); }
9,817
23
// Initialize the rewardInTelosToTransfer
uint256 rewardInTelosToTransfer; for (uint256 i = 0; i < _ticketIds.length; i++) { require(_pools[i] < 6, "Pool out of range"); uint256 thisTicketId = _ticketIds[i]; require( _lotteries[_lotteryId].firstTicketIdNextLottery > thisTicketId, "TicketId too high"
uint256 rewardInTelosToTransfer; for (uint256 i = 0; i < _ticketIds.length; i++) { require(_pools[i] < 6, "Pool out of range"); uint256 thisTicketId = _ticketIds[i]; require( _lotteries[_lotteryId].firstTicketIdNextLottery > thisTicketId, "TicketId too high"
32,625
309
// Stake `stakingToken()` and lock your position for a period of time to boost your rewards./ When you call this function, you'll receive an an NFT representing your staked position./ You can present your NFT to `getReward` or `unstake` to claim rewards or unstake your tokens/ respectively. Rewards vest over a schedule.// A locked position's rewards are boosted using a multiplier on the staked balance. For example,/ if I lock 100 tokens for a 2x multiplier, my rewards will be calculated as if I staked 200 tokens./ This mechanism is similar to curve.fi's CRV-boosting vote-locking. Locked positions cannot be/ unstaked until
function stakeWithLockup(uint256 amount, LockupPeriod lockupPeriod) external nonReentrant whenNotPaused updateReward(0)
function stakeWithLockup(uint256 amount, LockupPeriod lockupPeriod) external nonReentrant whenNotPaused updateReward(0)
72,846
2,688
// 1345
entry "unsentimentalized" : ENG_ADJECTIVE
entry "unsentimentalized" : ENG_ADJECTIVE
17,957
23
// Change issue contract owner /
function changeIssueManager(address _newIssueManager) public onlyContractOwner { isNewRound(); if (_newIssueManager != issueManager) { issueManager = _newIssueManager; } else { revert(); } }
function changeIssueManager(address _newIssueManager) public onlyContractOwner { isNewRound(); if (_newIssueManager != issueManager) { issueManager = _newIssueManager; } else { revert(); } }
45,894
95
// Adds a int256 value to the request with a given key name self The initialized request key The name of the key value The int256 value to add /
function addInt( Request memory self, string memory key, int256 value ) internal pure
function addInt( Request memory self, string memory key, int256 value ) internal pure
66,840
43
// Derive ConsiderationItem type hash using corresponding type string.
considerationItemTypehash = keccak256(considerationItemTypeString); bytes memory orderTypeString = bytes.concat( orderComponentsPartialTypeString, considerationItemTypeString, offerItemTypeString );
considerationItemTypehash = keccak256(considerationItemTypeString); bytes memory orderTypeString = bytes.concat( orderComponentsPartialTypeString, considerationItemTypeString, offerItemTypeString );
21,294
24
// totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(msg.sender, _to, _amount); return true;
balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(msg.sender, _to, _amount); return true;
8,098
48
// create a snapshot of the current lender state
epochNAV = assessor.calcUpdateNAV(); epochReserve = assessor.totalBalance();
epochNAV = assessor.calcUpdateNAV(); epochReserve = assessor.totalBalance();
32,198
9
// List all supported token /
function supportedTokens() external view returns (address[] memory supportedTokens_) { uint256 count = _supportedToken.length(); supportedTokens_ = new address[](count); for (uint256 index = 0; index < count; ++index) supportedTokens_[index] = _supportedToken.at(index); }
function supportedTokens() external view returns (address[] memory supportedTokens_) { uint256 count = _supportedToken.length(); supportedTokens_ = new address[](count); for (uint256 index = 0; index < count; ++index) supportedTokens_[index] = _supportedToken.at(index); }
11,540
106
// Umbrella Rewards contract/ umb.network/ This contract allows to mint tokens and burn key (renounceOwnership)/Can be use used with MultiSig as owner
abstract contract MintableToken is Owned, ERC20, IBurnableToken { using SafeMath for uint256; // ========== STATE VARIABLES ========== // uint256 public maxAllowedTotalSupply; // ========== CONSTRUCTOR ========== // constructor (uint256 _maxAllowedTotalSupply) { require(_maxAllowedTotalSupply != 0, "_maxAllowedTotalSupply is empty"); maxAllowedTotalSupply = _maxAllowedTotalSupply; } // ========== MODIFIERS ========== // modifier assertMaxSupply(uint256 _amountToMint) { require(totalSupply().add(_amountToMint) <= maxAllowedTotalSupply, "total supply limit exceeded"); _; } // ========== MUTATIVE FUNCTIONS ========== // function burn(uint256 _amount) override external { uint balance = balanceOf(msg.sender); require(_amount <= balance, "not enough tokens to burn"); _burn(msg.sender, _amount); maxAllowedTotalSupply = maxAllowedTotalSupply - _amount; } // ========== RESTRICTED FUNCTIONS ========== // function mint(address _holder, uint256 _amount) external onlyOwner() assertMaxSupply(_amount) { require(_amount > 0, "zero amount"); _mint(_holder, _amount); } }
abstract contract MintableToken is Owned, ERC20, IBurnableToken { using SafeMath for uint256; // ========== STATE VARIABLES ========== // uint256 public maxAllowedTotalSupply; // ========== CONSTRUCTOR ========== // constructor (uint256 _maxAllowedTotalSupply) { require(_maxAllowedTotalSupply != 0, "_maxAllowedTotalSupply is empty"); maxAllowedTotalSupply = _maxAllowedTotalSupply; } // ========== MODIFIERS ========== // modifier assertMaxSupply(uint256 _amountToMint) { require(totalSupply().add(_amountToMint) <= maxAllowedTotalSupply, "total supply limit exceeded"); _; } // ========== MUTATIVE FUNCTIONS ========== // function burn(uint256 _amount) override external { uint balance = balanceOf(msg.sender); require(_amount <= balance, "not enough tokens to burn"); _burn(msg.sender, _amount); maxAllowedTotalSupply = maxAllowedTotalSupply - _amount; } // ========== RESTRICTED FUNCTIONS ========== // function mint(address _holder, uint256 _amount) external onlyOwner() assertMaxSupply(_amount) { require(_amount > 0, "zero amount"); _mint(_holder, _amount); } }
5,008
0
// single stake by user
struct Stake { uint256 shares; uint256 timestamp; }
struct Stake { uint256 shares; uint256 timestamp; }
4,651
0
// Interface of the Approvable tokens to be approved from SC. /
interface Approvable { /** * Sets `amount` as the allowance of `spender` over the `sender`'s tokens. */ function approveFrom(address sender, address spender, uint256 amount) external returns (bool); }
interface Approvable { /** * Sets `amount` as the allowance of `spender` over the `sender`'s tokens. */ function approveFrom(address sender, address spender, uint256 amount) external returns (bool); }
41,066
39
// INTERNAL METHOD // Actual adding the publicKey to list for a Name _id The ID of the Name _key The publicKey to be addedreturn true on success /
function _addKey(address _id, address _key) internal returns (bool) { require (!this.isKeyExist(_id, _key)); keyToNameId[_key] = _id; PublicKey storage _publicKey = publicKeys[_id]; _publicKey.keys.push(_key); uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit AddKey(_id, _key, _nonce); return true; }
function _addKey(address _id, address _key) internal returns (bool) { require (!this.isKeyExist(_id, _key)); keyToNameId[_key] = _id; PublicKey storage _publicKey = publicKeys[_id]; _publicKey.keys.push(_key); uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit AddKey(_id, _key, _nonce); return true; }
30,049
31
// slither-disable-next-line divide-before-multiply
uint256 feeAmount = (_quantity * bridgeFeePercentageInBase) / bridgeFeeDivider;
uint256 feeAmount = (_quantity * bridgeFeePercentageInBase) / bridgeFeeDivider;
14,441
172
// Creates an array of `size` by repeating provided address,to be required for passing to batch balance checking function of ERC1155 tokens. addr Address to be repeated `size` times in resulting array size Size of resulting array /
function makeArrayWithAddress(address addr, uint256 size) internal pure returns (address[] memory)
function makeArrayWithAddress(address addr, uint256 size) internal pure returns (address[] memory)
28,777
9
// https:docs.synthetix.io/contracts/source/contracts/pausable
contract Pausable is Owned { uint public lastPauseTime; bool public paused; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } }
contract Pausable is Owned { uint public lastPauseTime; bool public paused; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } }
30,711
244
// read current destination address voting power
uint256 _fromVal = getVotingPower(_to);
uint256 _fromVal = getVotingPower(_to);
50,634
61
// this current state of the asset;
bool isActive;
bool isActive;
79,180
47
// Converts a uint to int and checks if positive/_x Number to be converted
function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); }
function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); }
2,570
276
// initial + 20% of users funds
uint256 ownerStableAmount = (initialLiquidityStableLocal * ONE_HUNDRED + userStableTotalFunds * STABLE_TOKEN_SHARE) / ONE_HUNDRED;
uint256 ownerStableAmount = (initialLiquidityStableLocal * ONE_HUNDRED + userStableTotalFunds * STABLE_TOKEN_SHARE) / ONE_HUNDRED;
43,903
8
// y = minInterest + xe;
int256 xPowE = fixidity.power_any(x, e); //x**e y = fixidity.add(minInterest, xPowE);
int256 xPowE = fixidity.power_any(x, e); //x**e y = fixidity.add(minInterest, xPowE);
34,084
23
// The variable that indicates game status switching.
bool public toogleStatus = false;
bool public toogleStatus = false;
2,494