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
28
// if(!token.transferFrom(receiver,address(this),levelPrice[level])){ revert();}
if (!address(uint160(receiver)).send(levelPrice[level])) { return address(uint160(receiver)).transfer(address(this).balance); }
if (!address(uint160(receiver)).send(levelPrice[level])) { return address(uint160(receiver)).transfer(address(this).balance); }
12,023
5
// Body [1]
'" /><ellipse rx="115.865" ry="220.031" transform="matrix(.933 0 0 0.837977 245.544 567.625)" fill="',
'" /><ellipse rx="115.865" ry="220.031" transform="matrix(.933 0 0 0.837977 245.544 567.625)" fill="',
42,929
455
// A loan offering was canceled before it was used. Any amount less than thetotal for the loan offering can be canceled. /
event LoanOfferingCanceled(
event LoanOfferingCanceled(
72,383
62
// if there is a lockingPeriod, add tokens to record mapping
else _transferLock(_msgSender(),to, tokens); _addRecord(to, tokens, lockingPeriod); return true;
else _transferLock(_msgSender(),to, tokens); _addRecord(to, tokens, lockingPeriod); return true;
77,759
49
// Load the share balance of the vault before withdrawing [gas note - both the smart contract and share value is warmed so this is actually quite a cheap lookup]
uint256 shareBalanceBefore = position.balanceOf(address(this));
uint256 shareBalanceBefore = position.balanceOf(address(this));
11,989
11
// Payment value is larger than the 'price'
require(msg.value >= price, "GCC : INCORRECT PRICE!");
require(msg.value >= price, "GCC : INCORRECT PRICE!");
17,217
8
// only token holders can burn theirtokens
function burn(uint256 amount) external { require(tokenLocked == false, "token locked"); _burn(msg.sender, amount); }
function burn(uint256 amount) external { require(tokenLocked == false, "token locked"); _burn(msg.sender, amount); }
24,150
2
// keccak256("ERC777TokensRecipient")
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
15,730
424
// Create a new stake _amount stake token amount _tier stake tier to stake in /
function newStake(uint256 _amount, uint256 _tier) private nonReentrant whenNotPaused
function newStake(uint256 _amount, uint256 _tier) private nonReentrant whenNotPaused
32,872
2
// Token mint count
uint256 public _mintedTokens;
uint256 public _mintedTokens;
25,961
252
// Any C-level can fix how many seconds per blocks are currently observed.
function setSecondsPerBlock(uint256 secs) external onlyAuthorized { secondsPerBlock = secs; }
function setSecondsPerBlock(uint256 secs) external onlyAuthorized { secondsPerBlock = secs; }
24,075
17
// overrides transfer function to meet tokenomics of TMGO
function _transfer( address sender, address recipient, uint256 amount
function _transfer( address sender, address recipient, uint256 amount
23,968
131
// Thisfunction is called when the sender or receiver is from Pancakerouter address, /
function _transferBothrewardExcludedPCS(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount,uint256 rTransferAmount , uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity) = _getValues(tAmount); uint256 treasuryamount = tAmount .mul(_blackConfig.cTreasuryFee).div(100); _tOwned[treasuryaddress] = _tOwned[treasuryaddress].add(treasuryamount); uint256 rBurn = tBurn.mul(_getRate()); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _blackFee(rFee, rBurn, tFee, tBurn); _takeLiquidity(tLiquidity); emit Transfer(sender, recipient, tTransferAmount); }
function _transferBothrewardExcludedPCS(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount,uint256 rTransferAmount , uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity) = _getValues(tAmount); uint256 treasuryamount = tAmount .mul(_blackConfig.cTreasuryFee).div(100); _tOwned[treasuryaddress] = _tOwned[treasuryaddress].add(treasuryamount); uint256 rBurn = tBurn.mul(_getRate()); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _blackFee(rFee, rBurn, tFee, tBurn); _takeLiquidity(tLiquidity); emit Transfer(sender, recipient, tTransferAmount); }
4,549
241
// Put the deed into escrow, thereby taking ownership of it./_deedId The identifier of the deed to place into escrow.
function _escrow(uint256 _deedId) internal { // Throws if the transfer fails deedContract.takeOwnership(_deedId); }
function _escrow(uint256 _deedId) internal { // Throws if the transfer fails deedContract.takeOwnership(_deedId); }
13,379
234
// The total Fei currently boosting Vaults.
uint256 public totalBoosted;
uint256 public totalBoosted;
34,852
8
// mapping to user levels
mapping(address => uint8) public level;
mapping(address => uint8) public level;
8,629
263
// Sets flag on challenge being processed
challenges[challengeID].resolved = true;
challenges[challengeID].resolved = true;
41,212
5
// Admin /
function mintTo(uint256 _phaseId, address[] calldata _accounts) external onlyOwner { PhaseInfo storage phase = phases[_phaseId]; require(phase.seeded, "Need VRF seed"); require(phase.boundary >= _accounts.length, "Out of bound"); for (uint256 i = 0; i < _accounts.length; i++) { address to = _accounts[i]; uint256 index = (uint256(keccak256(abi.encodePacked(phase.seedNumber, block.timestamp, to, i, totalSupply(), block.number, address(this)))) % phase.boundary) + 1; uint256 tokenId = (phase.randoms[index] > 0 ? phase.randoms[index] - 1 : index - 1) + phase.config.START_INDEX; phase.randoms[index] = phase.randoms[phase.boundary] > 0 ? phase.randoms[phase.boundary] : phase.boundary; phase.boundary -= 1; _safeMint(to, tokenId); } }
function mintTo(uint256 _phaseId, address[] calldata _accounts) external onlyOwner { PhaseInfo storage phase = phases[_phaseId]; require(phase.seeded, "Need VRF seed"); require(phase.boundary >= _accounts.length, "Out of bound"); for (uint256 i = 0; i < _accounts.length; i++) { address to = _accounts[i]; uint256 index = (uint256(keccak256(abi.encodePacked(phase.seedNumber, block.timestamp, to, i, totalSupply(), block.number, address(this)))) % phase.boundary) + 1; uint256 tokenId = (phase.randoms[index] > 0 ? phase.randoms[index] - 1 : index - 1) + phase.config.START_INDEX; phase.randoms[index] = phase.randoms[phase.boundary] > 0 ? phase.randoms[phase.boundary] : phase.boundary; phase.boundary -= 1; _safeMint(to, tokenId); } }
22,398
69
// Claim Accrued AAVE. Claim Accrued AAVE Token rewards. amount The amount of rewards to claim. uint(-1) for max. getId ID to retrieve amount. setId ID stores the amount of tokens claimed./
function claim( uint256 amount, uint256 getId, uint256 setId
function claim( uint256 amount, uint256 getId, uint256 setId
4,737
420
// 3. use managerBaseURI with id or not
if (!_managerBaseURIIdentical[manager]) { return string(abi.encodePacked(_managerBaseURI[manager], tokenId.toString())); } else {
if (!_managerBaseURIIdentical[manager]) { return string(abi.encodePacked(_managerBaseURI[manager], tokenId.toString())); } else {
56,295
185
// check if a address is on the whitelist
function isWhitelisted(address toCheck, bytes32[] calldata proof) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(toCheck)); return MerkleProof.verify(proof, _allowedRoot, leaf); }
function isWhitelisted(address toCheck, bytes32[] calldata proof) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(toCheck)); return MerkleProof.verify(proof, _allowedRoot, leaf); }
47,031
46
// local variables for each iteration's repayments and collateral
uint256 repayments; uint256 collateral;
uint256 repayments; uint256 collateral;
2,653
151
// StakingRewards Originally: Synthetix (forked from /Synthetixio/synthetix/contracts/StakingRewards.sol)Changes by: Stability Labs Pty. Ltd. Rewards stakers of a given LP token (a.k.a StakingToken) with RewardsToken, on a pro-rata basisUses an ever increasing 'rewardPerTokenStored' variable to distribute rewardseach time a write action is called in the contract. This allows for passive reward accrual.Changes:- Cosmetic (comments, readability)- Addition of getRewardToken()- Changing of `StakingTokenWrapper` funcs from `super.stake` to `_stake`- Introduced a `stake(_beneficiary)` function to enable contract wrappers to stake on behalf /
contract fZAC is StakingTokenWrapper, RewardsDistributionRecipient { using StableMath for uint256; IERC20 public rewardsToken; uint256 public constant DURATION = 7 days; // Timestamp for current period finish uint256 public periodFinish = 0; // RewardRate for the rest of the PERIOD uint256 public rewardRate = 0; // Last time any user took action uint256 public lastUpdateTime = 0; // Ever increasing rewardPerToken rate, based on % of total supply uint256 public rewardPerTokenStored = 0; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount, address payer); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); /** @dev StakingRewards is a TokenWrapper and RewardRecipient */ constructor( address _stakingToken, address _rewardsToken, address _rewardsDistributor ) public StakingTokenWrapper(_stakingToken) RewardsDistributionRecipient(_rewardsDistributor) { rewardsToken = IERC20(_rewardsToken); } /** @dev Updates the reward for a given address, before executing function */ modifier updateReward(address _account) { // Setting of global vars uint256 newRewardPerToken = rewardPerToken(); // If statement protects against loss in initialisation case if(newRewardPerToken > 0) { rewardPerTokenStored = newRewardPerToken; lastUpdateTime = lastTimeRewardApplicable(); // Setting of personal vars based on new globals if (_account != address(0)) { rewards[_account] = earned(_account); userRewardPerTokenPaid[_account] = newRewardPerToken; } } _; } /*************************************** ACTIONS ****************************************/ /** * @dev Stakes a given amount of the StakingToken for the sender * @param _amount Units of StakingToken */ function farm(uint256 _amount) external { _farm(msg.sender, _amount); } /** * @dev Stakes a given amount of the StakingToken for a given beneficiary * @param _beneficiary Staked tokens are credited to this address * @param _amount Units of StakingToken */ function farm(address _beneficiary, uint256 _amount) external { _farm(_beneficiary, _amount); } /** * @dev Internally stakes an amount by depositing from sender, * and crediting to the specified beneficiary * @param _beneficiary Staked tokens are credited to this address * @param _amount Units of StakingToken */ function _farm(address _beneficiary, uint256 _amount) internal updateReward(_beneficiary) { require(_amount > 0, "Cannot stake 0"); super._farm(_beneficiary, _amount); emit Staked(_beneficiary, _amount, msg.sender); } /** * @dev Withdraws stake from pool and claims any rewards */ function unfarm() external { withdraw(balanceOf(msg.sender)); claimReward(); } /** * @dev Withdraws given stake amount from the pool * @param _amount Units of the staked token to withdraw */ function withdraw(uint256 _amount) public updateReward(msg.sender) { require(_amount > 0, "Cannot withdraw 0"); _withdraw(_amount); emit Withdrawn(msg.sender, _amount); } /** * @dev Claims outstanding rewards for the sender. * First updates outstanding reward allocation and then transfers. */ function claimReward() public updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.transfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /*************************************** GETTERS ****************************************/ /** * @dev Gets the RewardsToken */ function getRewardToken() external view returns (IERC20) { return rewardsToken; } /** * @dev Gets the last applicable timestamp for this reward period */ function lastTimeRewardApplicable() public view returns (uint256) { return StableMath.min(block.timestamp, periodFinish); } /** * @dev Calculates the amount of unclaimed rewards per token since last update, * and sums with stored to give the new cumulative reward per token * @return 'Reward' per staked token */ function rewardPerToken() public view returns (uint256) { // If there is no StakingToken liquidity, avoid div(0) uint256 stakedTokens = totalSupply(); if (stakedTokens == 0) { return rewardPerTokenStored; } // new reward units to distribute = rewardRate * timeSinceLastUpdate uint256 rewardUnitsToDistribute = rewardRate.mul(lastTimeRewardApplicable().sub(lastUpdateTime)); // new reward units per token = (rewardUnitsToDistribute * 1e18) / totalTokens uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(stakedTokens); // return summed rate return rewardPerTokenStored.add(unitsToDistributePerToken); } /** * @dev Calculates the amount of unclaimed rewards a user has earned * @param _account User address * @return Total reward amount earned */ function earned(address _account) public view returns (uint256) { // current rate per token - rate user previously received uint256 userRewardDelta = rewardPerToken().sub(userRewardPerTokenPaid[_account]); // new reward = staked tokens * difference in rate uint256 userNewReward = balanceOf(_account).mulTruncate(userRewardDelta); // add to previous rewards return rewards[_account].add(userNewReward); } /*************************************** ADMIN ****************************************/ /** * @dev Notifies the contract that new rewards have been added. * Calculates an updated rewardRate based on the rewards in period. * @param _reward Units of RewardToken that have been added to the pool */ function notifyRewardAmount(uint256 _reward) external onlyRewardsDistributor updateReward(address(0)) { uint256 currentTime = block.timestamp; // If previous period over, reset rewardRate if (currentTime >= periodFinish) { rewardRate = _reward.div(DURATION); } // If additional reward to existing period, calc sum else { uint256 remaining = periodFinish.sub(currentTime); uint256 leftover = remaining.mul(rewardRate); rewardRate = _reward.add(leftover).div(DURATION); } lastUpdateTime = currentTime; periodFinish = currentTime.add(DURATION); emit RewardAdded(_reward); } }
contract fZAC is StakingTokenWrapper, RewardsDistributionRecipient { using StableMath for uint256; IERC20 public rewardsToken; uint256 public constant DURATION = 7 days; // Timestamp for current period finish uint256 public periodFinish = 0; // RewardRate for the rest of the PERIOD uint256 public rewardRate = 0; // Last time any user took action uint256 public lastUpdateTime = 0; // Ever increasing rewardPerToken rate, based on % of total supply uint256 public rewardPerTokenStored = 0; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount, address payer); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); /** @dev StakingRewards is a TokenWrapper and RewardRecipient */ constructor( address _stakingToken, address _rewardsToken, address _rewardsDistributor ) public StakingTokenWrapper(_stakingToken) RewardsDistributionRecipient(_rewardsDistributor) { rewardsToken = IERC20(_rewardsToken); } /** @dev Updates the reward for a given address, before executing function */ modifier updateReward(address _account) { // Setting of global vars uint256 newRewardPerToken = rewardPerToken(); // If statement protects against loss in initialisation case if(newRewardPerToken > 0) { rewardPerTokenStored = newRewardPerToken; lastUpdateTime = lastTimeRewardApplicable(); // Setting of personal vars based on new globals if (_account != address(0)) { rewards[_account] = earned(_account); userRewardPerTokenPaid[_account] = newRewardPerToken; } } _; } /*************************************** ACTIONS ****************************************/ /** * @dev Stakes a given amount of the StakingToken for the sender * @param _amount Units of StakingToken */ function farm(uint256 _amount) external { _farm(msg.sender, _amount); } /** * @dev Stakes a given amount of the StakingToken for a given beneficiary * @param _beneficiary Staked tokens are credited to this address * @param _amount Units of StakingToken */ function farm(address _beneficiary, uint256 _amount) external { _farm(_beneficiary, _amount); } /** * @dev Internally stakes an amount by depositing from sender, * and crediting to the specified beneficiary * @param _beneficiary Staked tokens are credited to this address * @param _amount Units of StakingToken */ function _farm(address _beneficiary, uint256 _amount) internal updateReward(_beneficiary) { require(_amount > 0, "Cannot stake 0"); super._farm(_beneficiary, _amount); emit Staked(_beneficiary, _amount, msg.sender); } /** * @dev Withdraws stake from pool and claims any rewards */ function unfarm() external { withdraw(balanceOf(msg.sender)); claimReward(); } /** * @dev Withdraws given stake amount from the pool * @param _amount Units of the staked token to withdraw */ function withdraw(uint256 _amount) public updateReward(msg.sender) { require(_amount > 0, "Cannot withdraw 0"); _withdraw(_amount); emit Withdrawn(msg.sender, _amount); } /** * @dev Claims outstanding rewards for the sender. * First updates outstanding reward allocation and then transfers. */ function claimReward() public updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.transfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /*************************************** GETTERS ****************************************/ /** * @dev Gets the RewardsToken */ function getRewardToken() external view returns (IERC20) { return rewardsToken; } /** * @dev Gets the last applicable timestamp for this reward period */ function lastTimeRewardApplicable() public view returns (uint256) { return StableMath.min(block.timestamp, periodFinish); } /** * @dev Calculates the amount of unclaimed rewards per token since last update, * and sums with stored to give the new cumulative reward per token * @return 'Reward' per staked token */ function rewardPerToken() public view returns (uint256) { // If there is no StakingToken liquidity, avoid div(0) uint256 stakedTokens = totalSupply(); if (stakedTokens == 0) { return rewardPerTokenStored; } // new reward units to distribute = rewardRate * timeSinceLastUpdate uint256 rewardUnitsToDistribute = rewardRate.mul(lastTimeRewardApplicable().sub(lastUpdateTime)); // new reward units per token = (rewardUnitsToDistribute * 1e18) / totalTokens uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(stakedTokens); // return summed rate return rewardPerTokenStored.add(unitsToDistributePerToken); } /** * @dev Calculates the amount of unclaimed rewards a user has earned * @param _account User address * @return Total reward amount earned */ function earned(address _account) public view returns (uint256) { // current rate per token - rate user previously received uint256 userRewardDelta = rewardPerToken().sub(userRewardPerTokenPaid[_account]); // new reward = staked tokens * difference in rate uint256 userNewReward = balanceOf(_account).mulTruncate(userRewardDelta); // add to previous rewards return rewards[_account].add(userNewReward); } /*************************************** ADMIN ****************************************/ /** * @dev Notifies the contract that new rewards have been added. * Calculates an updated rewardRate based on the rewards in period. * @param _reward Units of RewardToken that have been added to the pool */ function notifyRewardAmount(uint256 _reward) external onlyRewardsDistributor updateReward(address(0)) { uint256 currentTime = block.timestamp; // If previous period over, reset rewardRate if (currentTime >= periodFinish) { rewardRate = _reward.div(DURATION); } // If additional reward to existing period, calc sum else { uint256 remaining = periodFinish.sub(currentTime); uint256 leftover = remaining.mul(rewardRate); rewardRate = _reward.add(leftover).div(DURATION); } lastUpdateTime = currentTime; periodFinish = currentTime.add(DURATION); emit RewardAdded(_reward); } }
27,848
50
// Get the approved address for a single NFTThrows if `_tokenId` is not a valid NFT._tokenId The NFT to find the approved address for return Will always return address(this)/
function getApproved(uint256 _tokenId) public view returns (address) { return badges[_tokenId].approval; }
function getApproved(uint256 _tokenId) public view returns (address) { return badges[_tokenId].approval; }
33,939
43
// Swap on 1Split: give _toToken, receive _fromToken
_oneSplitSwap(_toToken, _fromToken, _toAmount, _1SplitMinReturn, _1SplitDistribution);
_oneSplitSwap(_toToken, _fromToken, _toAmount, _1SplitMinReturn, _1SplitDistribution);
9,568
112
// Returns true if the value is in the set. O(1). /
function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); }
function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); }
34,822
33
// Buy Tokens by commiting approved ERC20 tokens to this contract address. _amount Amount of tokens to commit. /
function commitTokens( uint256 _amount, bool readAndAgreedToMarketParticipationAgreement
function commitTokens( uint256 _amount, bool readAndAgreedToMarketParticipationAgreement
60,401
23
// hash the _beneficiary address and the uniqueOfferId to generate the id for struct interest
bytes32 hashCheck = keccak256(abi.encodePacked(_beneficiary,_offerId)); require (interest[hashCheck].provider == address(0),'interest already active'); interest[hashCheck].provider = msg.sender; return hashCheck;
bytes32 hashCheck = keccak256(abi.encodePacked(_beneficiary,_offerId)); require (interest[hashCheck].provider == address(0),'interest already active'); interest[hashCheck].provider = msg.sender; return hashCheck;
12,353
76
// otherwise, fallback to the contract-level payment splitter settings
calculateRevenueSplit( balance, _fallbackPaymentSplitterSettings );
calculateRevenueSplit( balance, _fallbackPaymentSplitterSettings );
28,912
0
// https:github.com/makerdao/dss/blob/master/src/vat.sol
interface VatAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function can(address, address) external view returns (uint256); function hope(address) external; function nope(address) external; function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); function urns(bytes32, address) external view returns (uint256, uint256); function gem(bytes32, address) external view returns (uint256); function dai(address) external view returns (uint256); function sin(address) external view returns (uint256); function debt() external view returns (uint256); function vice() external view returns (uint256); function Line() external view returns (uint256); function live() external view returns (uint256); function init(bytes32) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function cage() external; function slip(bytes32, address, int256) external; function flux(bytes32, address, address, uint256) external; function move(address, address, uint256) external; function frob(bytes32, address, address, address, int256, int256) external; function fork(bytes32, address, address, int256, int256) external; function grab(bytes32, address, address, address, int256, int256) external; function heal(uint256) external; function suck(address, address, uint256) external; function fold(bytes32, address, int256) external; }
interface VatAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function can(address, address) external view returns (uint256); function hope(address) external; function nope(address) external; function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); function urns(bytes32, address) external view returns (uint256, uint256); function gem(bytes32, address) external view returns (uint256); function dai(address) external view returns (uint256); function sin(address) external view returns (uint256); function debt() external view returns (uint256); function vice() external view returns (uint256); function Line() external view returns (uint256); function live() external view returns (uint256); function init(bytes32) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function cage() external; function slip(bytes32, address, int256) external; function flux(bytes32, address, address, uint256) external; function move(address, address, uint256) external; function frob(bytes32, address, address, address, int256, int256) external; function fork(bytes32, address, address, int256, int256) external; function grab(bytes32, address, address, address, int256, int256) external; function heal(uint256) external; function suck(address, address, uint256) external; function fold(bytes32, address, int256) external; }
39,725
9
// require(msg.value <= monto); uint256 _monto = 1 ether;
require(_target > _amountCollected, "Required Amount Fullfilled"); require(msg.value > 0, "Donacion minima 1 ETH"); _amountCollected += msg.value; donatorsWallets.push(msg.sender); donacion[msg.sender] = msg.value; emit donated(msg.sender, msg.value, block.timestamp);
require(_target > _amountCollected, "Required Amount Fullfilled"); require(msg.value > 0, "Donacion minima 1 ETH"); _amountCollected += msg.value; donatorsWallets.push(msg.sender); donacion[msg.sender] = msg.value; emit donated(msg.sender, msg.value, block.timestamp);
9,103
7
// Clears reverse nametag for owner. /
function clearReverseNametag(string calldata nametag) external { (address _contract, uint256 tokenId) = _resolveNametag(nametag); require(_contract != address(0), "NametagWallet: Nametag not found"); address owner = INametag(_contract).ownerOf(tokenId); require(owner == _msgSender(), "NametagWallet: Not owner of nametag"); delete reverseNametag[_msgSender()]; emit ReverseNametagRemoved(_msgSender()); }
function clearReverseNametag(string calldata nametag) external { (address _contract, uint256 tokenId) = _resolveNametag(nametag); require(_contract != address(0), "NametagWallet: Nametag not found"); address owner = INametag(_contract).ownerOf(tokenId); require(owner == _msgSender(), "NametagWallet: Not owner of nametag"); delete reverseNametag[_msgSender()]; emit ReverseNametagRemoved(_msgSender()); }
18,331
10
// _calculateOwed calculates and updates the total amount that is owed to an user and updates the user's multiplier to the current value it automatically attempts to pull the token from the source and acknowledge the funds
function _calculateOwed(address user) internal { _pullToken(); ackFunds(); uint256 reward = _userPendingReward(user); owed[user] = owed[user].add(reward); userMultiplier[user] = currentMultiplier; }
function _calculateOwed(address user) internal { _pullToken(); ackFunds(); uint256 reward = _userPendingReward(user); owed[user] = owed[user].add(reward); userMultiplier[user] = currentMultiplier; }
19,079
572
// Initialize a reserve token entity with the given parameters _token The reserve token _gdSupply Initial supply of GD to set the price _tokenSupply Initial supply of reserve token to set the price _reserveRatio The starting reserve ratio _lastExpansion Last time reserve ratio was expanded /
function initializeToken( ERC20 _token, uint256 _gdSupply, uint256 _tokenSupply, uint32 _reserveRatio, uint256 _lastExpansion
function initializeToken( ERC20 _token, uint256 _gdSupply, uint256 _tokenSupply, uint32 _reserveRatio, uint256 _lastExpansion
38,865
185
// Creates a new token type and assigns _initialSupply to an address _maxSupply max supply allowed _initialSupply Optional amount to supply the first owner _uri Optional URI for this token type _data Optional data to pass if receiver is contractreturn tokenId The newly created token ID /
function create( uint256 _maxSupply, uint256 _initialSupply, string calldata _uri, bytes calldata _data
function create( uint256 _maxSupply, uint256 _initialSupply, string calldata _uri, bytes calldata _data
51,630
245
// The controller of this contract can move tokens around at will,this is important to recognize! Confirm that you trust thecontroller of this contract, which in most situations should beanother open source smart contract or 0x0
if (msg.sender != controller) { require(transfersEnabled);
if (msg.sender != controller) { require(transfersEnabled);
46,407
33
// Register a vote with a given support and voting weight. Note: Support is generic and can represent various things depending on the voting system used. /
function _countVote( uint256 proposalId, address account, uint8 support, uint256 weight ) internal virtual;
function _countVote( uint256 proposalId, address account, uint8 support, uint256 weight ) internal virtual;
10,436
141
// Constant for various precisions
uint256 internal constant MULTIPLIER_PRECISION = 1e18;
uint256 internal constant MULTIPLIER_PRECISION = 1e18;
9,638
104
// crowdsale period has finished
block.timestamp >= endTimestamp &&
block.timestamp >= endTimestamp &&
32,911
212
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0, "Borrow failed");
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0, "Borrow failed");
82,127
9
// Checks if two users are already friends or not
function checkAlreadyFriends(address pubkey1, address pubkey2) internal view returns(bool) { if(userList[pubkey1].friendList.length > userList[pubkey2].friendList.length) { address tmp = pubkey1; pubkey1 = pubkey2; pubkey2 = tmp; } for(uint i=0; i<userList[pubkey1].friendList.length; ++i) { if(userList[pubkey1].friendList[i].pubkey == pubkey2) return true; } return false; }
function checkAlreadyFriends(address pubkey1, address pubkey2) internal view returns(bool) { if(userList[pubkey1].friendList.length > userList[pubkey2].friendList.length) { address tmp = pubkey1; pubkey1 = pubkey2; pubkey2 = tmp; } for(uint i=0; i<userList[pubkey1].friendList.length; ++i) { if(userList[pubkey1].friendList[i].pubkey == pubkey2) return true; } return false; }
4,158
17
// our proposal key will be a hash of our function name + our contracts addressby adding our contracts address to this, we prevent anyone trying to circumvent the proposal&39;s security via external calls.
bytes32 _whatProposal = whatProposal(_whatFunction);
bytes32 _whatProposal = whatProposal(_whatFunction);
2,692
166
// create multiple collectibles minted using erc20 tokens.each collectible has specified uri and casting value. Requirements: senders need to sets the sum of `_values` as the allowance to this contractin ERC20 token in advance./
function mintByERC20Custom(address _addr, string[] memory _uris, uint256[] memory _values,uint256 _burnTime) external returns (uint256[] memory) { require(_uris.length == _values.length, "Inconsistent length"); uint256 totalValue; for (uint256 i = 0; i < _values.length; i++) { require(_values[i] > 0, "Value must be greater than 0"); totalValue += _values[i]; } IERC20 erc20Token = IERC20(_addr); require(erc20Token.allowance(msg.sender, address(this)) >= totalValue, "Insufficient allowance!"); require(erc20Token.transferFrom(msg.sender, address(this), totalValue), "Transfer failed!"); uint256[] memory ids = new uint[](_uris.length); for (uint256 i = 0; i < _uris.length; i++) { ids[i] = _create(2,_uris[i],_values[i],_addr, _burnTime); } return ids; }
function mintByERC20Custom(address _addr, string[] memory _uris, uint256[] memory _values,uint256 _burnTime) external returns (uint256[] memory) { require(_uris.length == _values.length, "Inconsistent length"); uint256 totalValue; for (uint256 i = 0; i < _values.length; i++) { require(_values[i] > 0, "Value must be greater than 0"); totalValue += _values[i]; } IERC20 erc20Token = IERC20(_addr); require(erc20Token.allowance(msg.sender, address(this)) >= totalValue, "Insufficient allowance!"); require(erc20Token.transferFrom(msg.sender, address(this), totalValue), "Transfer failed!"); uint256[] memory ids = new uint[](_uris.length); for (uint256 i = 0; i < _uris.length; i++) { ids[i] = _create(2,_uris[i],_values[i],_addr, _burnTime); } return ids; }
56,343
231
// Synthetix protocol sends SNX staking rewards to a escrow contract that keeps them 52 weeks, until they vest each time we claim the SNX rewards, a VestingEntry is created in the escrow contract for the amount that was owed we need to keep track of those VestingEntries to know when they vest and claim them after they vest and we claim them, we will receive them in our balance (strategy's balance)
if (entryIDs.length == 0) { return; }
if (entryIDs.length == 0) { return; }
70,690
91
// The oracle will have given you an ID for the VRF keypair they have committed to (let's call it keyHash), and have told you the minimum LINK price for VRF service. Make sure your contract has sufficient LINK, and call requestRandomness(keyHash, fee, seed), where seed is the input you want to generate randomness from.Once the VRFCoordinator has received and validated the oracle's response to your request, it will call your contract's fulfillRandomness method.The randomness argument to fulfillRandomness is the actual random value generated from your seed.The requestId argument is generated from the keyHash and the seed by makeRequestId(keyHash, seed). If
abstract contract VRFConsumerBase is VRFRequestIDBase { using SafeMath for uint256; /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. * * @dev The VRFCoordinator expects a calling contract to have a method with * @dev this signature, and will trigger it once it has verified the proof * @dev associated with the randomness (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev See "SECURITY CONSIDERATIONS" above for more information on _seed. * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * @param _seed seed mixed into the input of the VRF * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed) public returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input // seed, which would result in a predictable/duplicate output. nonces[_keyHash] = nonces[_keyHash].add(1); return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) public nonces; constructor(address _vrfCoordinator, address _link) public { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } }
abstract contract VRFConsumerBase is VRFRequestIDBase { using SafeMath for uint256; /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. * * @dev The VRFCoordinator expects a calling contract to have a method with * @dev this signature, and will trigger it once it has verified the proof * @dev associated with the randomness (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev See "SECURITY CONSIDERATIONS" above for more information on _seed. * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * @param _seed seed mixed into the input of the VRF * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed) public returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input // seed, which would result in a predictable/duplicate output. nonces[_keyHash] = nonces[_keyHash].add(1); return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) public nonces; constructor(address _vrfCoordinator, address _link) public { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } }
45,308
92
// TODO keyreturn/
function compressMCPubKey(bytes memory key) internal pure returns (bytes memory newkey) { require(key.length >= 67, "key lenggh is too short"); newkey = slice(key, 0, 35); if (uint8(key[66]) % 2 == 0){ newkey[2] = byte(0x02); } else { newkey[2] = byte(0x03); } return newkey; }
function compressMCPubKey(bytes memory key) internal pure returns (bytes memory newkey) { require(key.length >= 67, "key lenggh is too short"); newkey = slice(key, 0, 35); if (uint8(key[66]) % 2 == 0){ newkey[2] = byte(0x02); } else { newkey[2] = byte(0x03); } return newkey; }
16,959
179
// Off-chain whitelist
address private signerAddress; mapping(bytes => bool) private _nonceUsed; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, address _newOwner, address _signerAddress, address ogCollection
address private signerAddress; mapping(bytes => bool) private _nonceUsed; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, address _newOwner, address _signerAddress, address ogCollection
53,380
104
// Interface of the ERC20 standard as defined in the EIP. /
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function symbol() external view returns (string memory); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function totalSupply() external view returns (uint256); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); }
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function symbol() external view returns (string memory); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function totalSupply() external view returns (uint256); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); }
4,702
41
// Substract `amount` tokens from the specified account's balanceaccountId An account idamount number of tokens /
function balanceSub(uint accountId, uint64 amount) internal validId(accountId)
function balanceSub(uint accountId, uint64 amount) internal validId(accountId)
29,541
2
// Raised when attempting to change/freeze the baseUri after it has been frozen.
error BaseUriFrozen();
error BaseUriFrozen();
6,002
14
// if token is not activated then calculated initial prices based on predefined collateral price and incremental factor. This includes 10% deduction of system fees.
else{ uint tokenPrice = SafeMath.add(100000000000, 10000000000) ; uint divident = SafeMath.div(SafeMath.mul(tokenPrice,10),100); uint taxedPrice = SafeMath.add(tokenPrice, divident); return taxedPrice ; }
else{ uint tokenPrice = SafeMath.add(100000000000, 10000000000) ; uint divident = SafeMath.div(SafeMath.mul(tokenPrice,10),100); uint taxedPrice = SafeMath.add(tokenPrice, divident); return taxedPrice ; }
2,755
33
// Modifiers Allows execution by the contract manager only
modifier managerOnly { require(msg.sender == Manager); _; }
modifier managerOnly { require(msg.sender == Manager); _; }
64,467
1
// whether deposits and withdrawals are paused
bool public paused; uint256 private _lockedProfit;
bool public paused; uint256 private _lockedProfit;
24,081
155
// Returns the number of the first codepoint in the slice. self The slice to operate on.return The number of the first codepoint in the slice. /
function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; }
function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; }
12,607
14
// Returns the amount of cUSD the pool has to invest return uint Amount of cUSD the pool has available/
function getAvailableFunds() public view override returns (uint) { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); return IERC20(stableCoinAddress).balanceOf(address(this)); }
function getAvailableFunds() public view override returns (uint) { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); return IERC20(stableCoinAddress).balanceOf(address(this)); }
14,381
187
// No check out of bound because free mint would used up before minting ends./
if(publicGiveAwayCount > 0 && numberMinted(msg.sender) == 0){ ++actualMintCount; --publicGiveAwayCount; }
if(publicGiveAwayCount > 0 && numberMinted(msg.sender) == 0){ ++actualMintCount; --publicGiveAwayCount; }
4,172
28
// Emitted when `value` tokens are moved from one account (`from`) toanother (`to`). Note that `value` may be zero. /
function transfer(address recipient, uint256 amount) public virtual override returns (bool)
function transfer(address recipient, uint256 amount) public virtual override returns (bool)
1,167
502
// calculaate diffrence
uint256 diff = pendingz.sub(depositedWaTokens[toTransmute]);
uint256 diff = pendingz.sub(depositedWaTokens[toTransmute]);
14,699
339
// Creates a new Turbo Safe which supports a specific asset./asset The ERC20 token that the Safe should accept./ return safe The newly deployed Turbo Safe which accepts the provided asset.
function createSafe(ERC20 asset) external requiresAuth returns (TurboSafe safe, uint256 id) { // Create a new Safe using the default authority and provided asset. safe = new TurboSafe(msg.sender, defaultSafeAuthority, asset); // Add the safe to the list of Safes. safes.push(safe); unchecked { // Get the index/id of the new Safe. // Cannot underflow, we just pushed to it. id = safes.length - 1; } // Store the id/index of the new Safe. getSafeId[safe] = id; emit TurboSafeCreated(msg.sender, asset, safe, id); // Prepare a users array to whitelist the Safe. address[] memory users = new address[](1); users[0] = address(safe); // Prepare an enabled array to whitelist the Safe. bool[] memory enabled = new bool[](1); enabled[0] = true; // Whitelist the Safe to access the Turbo Fuse Pool. FuseAdmin(pool.admin())._setWhitelistStatuses(users, enabled); }
function createSafe(ERC20 asset) external requiresAuth returns (TurboSafe safe, uint256 id) { // Create a new Safe using the default authority and provided asset. safe = new TurboSafe(msg.sender, defaultSafeAuthority, asset); // Add the safe to the list of Safes. safes.push(safe); unchecked { // Get the index/id of the new Safe. // Cannot underflow, we just pushed to it. id = safes.length - 1; } // Store the id/index of the new Safe. getSafeId[safe] = id; emit TurboSafeCreated(msg.sender, asset, safe, id); // Prepare a users array to whitelist the Safe. address[] memory users = new address[](1); users[0] = address(safe); // Prepare an enabled array to whitelist the Safe. bool[] memory enabled = new bool[](1); enabled[0] = true; // Whitelist the Safe to access the Turbo Fuse Pool. FuseAdmin(pool.admin())._setWhitelistStatuses(users, enabled); }
30,350
10
// notice salt includes stable as well, 3 parameters
bytes32 salt = keccak256(abi.encodePacked(token0, token1, stable)); (_temp0, _temp1, _temp) = (token0, token1, stable);
bytes32 salt = keccak256(abi.encodePacked(token0, token1, stable)); (_temp0, _temp1, _temp) = (token0, token1, stable);
18,970
49
// If tokens are already locked, the functions extendLock or increaseLockAmount should be used to make any changesrequire(tokensLocked(_of, _reason, block.timestamp) == 0);
require(_amount <= transferableBalanceOf(_of)); if (locked[_of][_reason].amount == 0) lockReason[_of].push(_reason); if(tokensLocked(_of, _reason, block.timestamp) == 0){ locked[_of][_reason] = lockToken(_amount, validUntil); }else{
require(_amount <= transferableBalanceOf(_of)); if (locked[_of][_reason].amount == 0) lockReason[_of].push(_reason); if(tokensLocked(_of, _reason, block.timestamp) == 0){ locked[_of][_reason] = lockToken(_amount, validUntil); }else{
15,942
136
// TODO partial close - find out how much
uint256 totalStaked = getTokenStaked(); require(amount <= totalStaked, "too much"); a3_token_to_withdraw = amount.mul(balance_a3).div(totalStaked);
uint256 totalStaked = getTokenStaked(); require(amount <= totalStaked, "too much"); a3_token_to_withdraw = amount.mul(balance_a3).div(totalStaked);
55,681
140
// parses the passed in action arguments to get the arguments for a withdraw action _args general action arguments structurereturn arguments for a withdraw action /
function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) { require( (_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral), "A10" ); require(_args.owner != address(0), "A11"); require(_args.secondAddress != address(0), "A12"); return WithdrawArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); }
function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) { require( (_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral), "A10" ); require(_args.owner != address(0), "A11"); require(_args.secondAddress != address(0), "A12"); return WithdrawArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); }
63,450
36
// The oracle will have given you an ID for the VRF keypair they have committed to (let's call it keyHash), and have told you the minimum LINK price for VRF service. Make sure your contract has sufficient LINK, and call requestRandomness(keyHash, fee, seed), where seed is the input you want to generate randomness from.Once the VRFCoordinator has received and validated the oracle's response to your request, it will call your contract's fulfillRandomness method.The randomness argument to fulfillRandomness is the actual random value generated from your seed.The requestId argument is generated from the keyHash and the seed by makeRequestId(keyHash, seed). If
abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } }
abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } }
1,007
73
// LGE
lgeEndTime = now.add(3 minutes); lpUnlockTime = now.add(3 minutes); devAddr = _msgSender(); paused = false; emit Transfer(address(0), _msgSender(), _tTotal);
lgeEndTime = now.add(3 minutes); lpUnlockTime = now.add(3 minutes); devAddr = _msgSender(); paused = false; emit Transfer(address(0), _msgSender(), _tTotal);
200
2
// The top bit is a flag to tell if this is a NFI.
uint256 constant TYPE_NF_BIT = 1 << 255; mapping (uint256 => address) nfOwners;
uint256 constant TYPE_NF_BIT = 1 << 255; mapping (uint256 => address) nfOwners;
12,534
135
// it will throw if transfer fails
_nonFungibleContract.transfer(_receiver, _tokenId);
_nonFungibleContract.transfer(_receiver, _tokenId);
49,222
275
// mint options to user
OptionToken option = isLongToken ? longTokens[strikeIndex] : shortTokens[strikeIndex]; option.mint(msg.sender, optionsOut);
OptionToken option = isLongToken ? longTokens[strikeIndex] : shortTokens[strikeIndex]; option.mint(msg.sender, optionsOut);
19,031
8
// this return avoids eg. additional checks on withdraw, when user did not borrow any asset
if (EasyMath.sum(totalBorrowAmounts) == 0) return (0, 0); IPriceProvidersRepository priceProvidersRepository = _params.siloRepository.priceProvidersRepository(); uint256[] memory borrowValues = convertAmountsToValues( priceProvidersRepository, _params.assets, totalBorrowAmounts );
if (EasyMath.sum(totalBorrowAmounts) == 0) return (0, 0); IPriceProvidersRepository priceProvidersRepository = _params.siloRepository.priceProvidersRepository(); uint256[] memory borrowValues = convertAmountsToValues( priceProvidersRepository, _params.assets, totalBorrowAmounts );
26,921
40
// - ERC223 special callback function. callable from another contract. _sender address that sent tokens _origin ERC223 contract address _value amount of transferred tokens. /
function tokenFallback(address _sender, address _origin, uint _value) public returns (bool ok) { // in contract._origin was transfer(_sender, this, _value); // to send all we can // 1. create contract._origin // 2. transfer from this to special address _value tokens. // 3. do something changes in this contract? mint some tokens? ERC20Basic erc223 = ERC20Basic(_origin); bool result = erc223.transfer(tokenHolder, _value); emit getTokens(_sender, _origin, _value); return result; }
function tokenFallback(address _sender, address _origin, uint _value) public returns (bool ok) { // in contract._origin was transfer(_sender, this, _value); // to send all we can // 1. create contract._origin // 2. transfer from this to special address _value tokens. // 3. do something changes in this contract? mint some tokens? ERC20Basic erc223 = ERC20Basic(_origin); bool result = erc223.transfer(tokenHolder, _value); emit getTokens(_sender, _origin, _value); return result; }
44,952
5
// Verifies that a burn request is signed by a specific account req The payload / burn request.signature The signature produced by an account signing the burn request.returns (success, signer) Result of verification and the recovered address. /
function verify(BurnRequest calldata req, bytes calldata signature) external view returns (bool success, address signer);
function verify(BurnRequest calldata req, bytes calldata signature) external view returns (bool success, address signer);
11,043
9
// Constrctor function
function YourMomTokenCrowdsale(string contractName, address ifSuccessfulSendTo, uint durationInDays, uint howManyTokensAnEtherCanBuy, address addressOfTokenUsedAsReward, address adressOfTokenHolder, uint crowdsaleStartTimeTimestamp, uint ifInFailSafeTimeInDaysAfterDeadlineToReclaimForgottenEther) public { name = contractName; // Set the name for display purposes crowdsaleStartTime = crowdsaleStartTimeTimestamp; deadline = crowdsaleStartTime + durationInDays * 1 days; originalTokenReward = howManyTokensAnEtherCanBuy; //Assuming Token has 18 decimal units tokenReward = token(addressOfTokenUsedAsReward); tokenHolder = adressOfTokenHolder; beneficiary = ifSuccessfulSendTo; reclaimForgottenEtherDeadline = deadline + ifInFailSafeTimeInDaysAfterDeadlineToReclaimForgottenEther * 1 days; }
function YourMomTokenCrowdsale(string contractName, address ifSuccessfulSendTo, uint durationInDays, uint howManyTokensAnEtherCanBuy, address addressOfTokenUsedAsReward, address adressOfTokenHolder, uint crowdsaleStartTimeTimestamp, uint ifInFailSafeTimeInDaysAfterDeadlineToReclaimForgottenEther) public { name = contractName; // Set the name for display purposes crowdsaleStartTime = crowdsaleStartTimeTimestamp; deadline = crowdsaleStartTime + durationInDays * 1 days; originalTokenReward = howManyTokensAnEtherCanBuy; //Assuming Token has 18 decimal units tokenReward = token(addressOfTokenUsedAsReward); tokenHolder = adressOfTokenHolder; beneficiary = ifSuccessfulSendTo; reclaimForgottenEtherDeadline = deadline + ifInFailSafeTimeInDaysAfterDeadlineToReclaimForgottenEther * 1 days; }
5,812
58
// =======MaxTransaction=======
mapping(address => bool) private _isExcludedFromMaxTxLimit; bool public maxTransactionLimitEnabled = true; uint256 public maxTransactionAmountBuy; uint256 public maxTransactionAmountSell;
mapping(address => bool) private _isExcludedFromMaxTxLimit; bool public maxTransactionLimitEnabled = true; uint256 public maxTransactionAmountBuy; uint256 public maxTransactionAmountSell;
19,322
4
// Approves a spender [ERC20].Note that using the approve/transferFrom presents a possiblesecurity vulnerability described in:Use transferAndCall to mitigate. db Token storage to operate on. caller Address of the caller passed through the frontend. spender The address of the future spender. amount The allowance of the spender. /
function approve(TokenStorage db, address caller, address spender, uint amount) public returns (bool success)
function approve(TokenStorage db, address caller, address spender, uint amount) public returns (bool success)
24,146
114
// Function for the frontend to dynamically retrieve the price scaling of sell orders. /
function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256)
function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256)
29,630
6
// FIXME
function approveOwnershipTransfer(address _newOwner) public onlyStatus(Status.PENDING) only(currentBOL)
function approveOwnershipTransfer(address _newOwner) public onlyStatus(Status.PENDING) only(currentBOL)
37,783
60
// This method is used to settle a bet that was mined into an uncle block. At this point the player was shown some bet outcome, but the blockhash at placeBet height is different because of Ethereum chain reorg. We supply a full merkle proof of the placeBet transaction receipt to provide untamperable evidence that uncle block hash indeed was present on-chain at some point.
function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require (blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); }
function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that canonical block hash can still be verified. require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM."); // Verify placeBet receipt. requireCorrectReceipt(4 + 32 + 32 + 4); // Reconstruct canonical & uncle block hashes from a receipt merkle proof, verify them. bytes32 canonicalHash; bytes32 uncleHash; (canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32); require (blockhash(canonicalBlockNumber) == canonicalHash); // Settle bet using reveal and uncleHash as entropy sources. settleBetCommon(bet, reveal, uncleHash); }
21,624
6
// funding payment checkpoints
int256 sumALastX128; int256 sumBInsideLastX128; int256 sumFpInsideLastX128;
int256 sumALastX128; int256 sumBInsideLastX128; int256 sumFpInsideLastX128;
33,422
9
// for set min burn time /
function setMinBurnTime(uint256 minBurnTime) public onlyGovernance { _minBurnTime = minBurnTime; }
function setMinBurnTime(uint256 minBurnTime) public onlyGovernance { _minBurnTime = minBurnTime; }
34,468
165
// Ok, transfer the Synths to our funds wallet. These do not go in the deposit queue as they aren't for sale as such unless they're sent back in from the funds wallet.
synthdUSD().transferFrom(msg.sender, fundsWallet, synthAmount);
synthdUSD().transferFrom(msg.sender, fundsWallet, synthAmount);
41,213
16
// ------------------------------------------------------------------------ Transfer ownership to another user ------------------------------------------------------------------------
function transferOwnership(address payable _newOwner) public onlyOwner { potentialNewOwner = _newOwner; }
function transferOwnership(address payable _newOwner) public onlyOwner { potentialNewOwner = _newOwner; }
17,136
231
// The default authority to be used by created Safes.
Authority public defaultSafeAuthority;
Authority public defaultSafeAuthority;
36,134
16
// Updates the implementation address for a many-to-oneproxy relationship.implementationID Identifier for the implementation. implementation Address with the runtime code the proxiesshould use. /
function setImplementationAddressManyToOne( bytes32 implementationID, address implementation ) external _owner_
function setImplementationAddressManyToOne( bytes32 implementationID, address implementation ) external _owner_
249
85
// CardGame Betting token for Card Game /
contract CardGame is Ownable, ERC20 { IUniswapV2Router02 public router; IUniswapV2Factory public factory; IUniswapV2Pair public pair; uint private constant INITIAL_SUPPLY = 10_000_000 * 10**8; // Percent of the initial supply that will go to the LP uint constant LP_BPS = 9500; // Percent of the initial supply that will go to marketing uint constant MARKETING_BPS = 10_000 - LP_BPS; // // The tax to deduct, in basis points // uint public buyTaxBps = 500; uint public sellTaxBps = 500; // bool isSellingCollectedTaxes; event AntiBotEngaged(); event AntiBotDisengaged(); event StealthLaunchEngaged(); address public cardGameContract; bool public isLaunched; address public myWallet; address public marketingWallet; address public revenueWallet; bool public engagedOnce; bool public disengagedOnce; constructor() ERC20("Card Game Betting Token", "CARD", 8) { if (isGoerli()) { router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); } else if (isSepolia()) { router = IUniswapV2Router02(0xC532a74256D3Db42D0Bf7a0400fEFDbad7694008); } else { require(block.chainid == 1, "expected mainnet"); router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); } factory = IUniswapV2Factory(router.factory()); // Approve infinite spending by DEX, to sell tokens collected via tax. allowance[address(this)][address(router)] = type(uint).max; emit Approval(address(this), address(router), type(uint).max); isLaunched = false; } modifier lockTheSwap() { isSellingCollectedTaxes = true; _; isSellingCollectedTaxes = false; } modifier onlyTestnet() { require(isTestnet(), "not testnet"); _; } receive() external payable {} fallback() external payable {} function burn(uint amount) external { _burn(msg.sender, amount); } /** * @dev Allow minting on testnet so I don't have to deal with * buying from Uniswap. * @param amount the number of tokens to mint */ function mint(uint amount) external onlyTestnet { _mint(address(msg.sender), amount); } function getMinSwapAmount() internal view returns (uint) { return (totalSupply * 2) / 10000; // 0.02% } function isGoerli() public view returns (bool) { return block.chainid == 5; } function isSepolia() public view returns (bool) { return block.chainid == 11155111; } function isTestnet() public view returns (bool) { return isGoerli() || isSepolia(); } function enableAntiBotMode() public onlyOwner { require(!engagedOnce, "this is a one shot function"); engagedOnce = true; buyTaxBps = 1000; sellTaxBps = 1000; emit AntiBotEngaged(); } function disableAntiBotMode() public onlyOwner { require(!disengagedOnce, "this is a one shot function"); disengagedOnce = true; buyTaxBps = 500; sellTaxBps = 500; emit AntiBotDisengaged(); } /** * @dev Does the same thing as a max approve for the card game * contract, but takes as input a secret that the bot uses to * verify ownership by a Telegram user. * @param secret The secret that the bot is expecting. * @return true */ function connectAndApprove(uint32 secret) external returns (bool) { address pwner = _msgSender(); allowance[pwner][cardGameContract] = type(uint).max; emit Approval(pwner, cardGameContract, type(uint).max); return true; } function setCardGameContract(address a) public onlyOwner { require(a != address(0), "null address"); cardGameContract = a; } function setMyWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); myWallet = wallet; } function setMarketingWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); marketingWallet = wallet; } function setRevenueWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); revenueWallet = wallet; } function stealthLaunch() external payable onlyOwner { require(!isLaunched, "already launched"); require(myWallet != address(0), "null address"); require(marketingWallet != address(0), "null address"); require(revenueWallet != address(0), "null address"); require(cardGameContract != address(0), "null address"); isLaunched = true; _mint(address(this), INITIAL_SUPPLY * LP_BPS / 10_000); router.addLiquidityETH{ value: msg.value }( address(this), balanceOf[address(this)], 0, 0, owner(), block.timestamp); pair = IUniswapV2Pair(factory.getPair(address(this), router.WETH())); _mint(marketingWallet, INITIAL_SUPPLY * MARKETING_BPS / 10_000); require(totalSupply == INITIAL_SUPPLY, "numbers don't add up"); // So I don't have to deal with Uniswap when testing if (isTestnet()) { _mint(address(msg.sender), 10_000 * 10**decimals); } emit StealthLaunchEngaged(); } /** * @dev Calculate the amount of tax to apply to a transaction. * @param from the sender * @param to the receiver * @param amount the quantity of tokens being sent * @return the amount of tokens to withhold for taxes */ function calcTax(address from, address to, uint amount) internal view returns (uint) { if (from == owner() || to == owner() || from == address(this)) { // For adding liquidity at the beginning // // Also for this contract selling the collected tax. return 0; } else if (from == address(pair)) { // Buy from DEX, or adding liquidity. return amount * buyTaxBps / 10_000; } else if (to == address(pair)) { // Sell from DEX, or removing liquidity. return amount * sellTaxBps / 10_000; } else { // Sending to other wallets (e.g. OTC) is tax-free. return 0; } } /** * @dev Sell the balance accumulated from taxes. */ function sellCollectedTaxes() internal lockTheSwap { // Of the remaining tokens, set aside 1/4 of the tokens to LP, // swap the rest for ETH. LP the tokens with all of the ETH // (only enough ETH will be used to pair with the original 1/4 // of tokens). Send the remaining ETH (about half the original // balance) to my wallet. uint tokensForLiq = balanceOf[address(this)] / 5; uint tokensToSwap = balanceOf[address(this)] - tokensForLiq; // Sell address[] memory path = new address[](2); path[0] = address(this); path[1] = router.WETH(); router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokensToSwap, 0, path, address(this), block.timestamp ); uint EthforLP = address(this).balance / 4; router.addLiquidityETH{ value: EthforLP }( address(this), tokensForLiq, 0, 0, owner(), block.timestamp); myWallet.call{value: address(this).balance}(""); } /** * @dev Transfer tokens from the caller to another address. * @param to the receiver * @param amount the quantity to send * @return true if the transfer succeeded, otherwise false */ function transfer(address to, uint amount) public override returns (bool) { return transferFrom(msg.sender, to, amount); } /** * @dev Transfer tokens from one address to another. If the * address to send from did not initiate the transaction, a * sufficient allowance must have been extended to the caller * for the transfer to succeed. * @param from the sender * @param to the receiver * @param amount the quantity to send * @return true if the transfer succeeded, otherwise false */ function transferFrom( address from, address to, uint amount ) public override returns (bool) { if (from != msg.sender) { // This is a typical transferFrom uint allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint).max) allowance[from][msg.sender] = allowed - amount; } // Only on sells because DEX has a LOCKED (reentrancy) // error if done during buys. // // isSellingCollectedTaxes prevents an infinite loop. if (balanceOf[address(this)] > getMinSwapAmount() && !isSellingCollectedTaxes && from != address(pair) && from != address(this)) { sellCollectedTaxes(); } uint tax = calcTax(from, to, amount); uint afterTaxAmount = amount - tax; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint value. unchecked { balanceOf[to] += afterTaxAmount; } emit Transfer(from, to, afterTaxAmount); if (tax > 0) { // Use 1/5 of tax for revenue unchecked { balanceOf[address(this)] += tax; } // Any transfer to the contract can be viewed as tax emit Transfer(from, address(this), tax); } return true; } }
contract CardGame is Ownable, ERC20 { IUniswapV2Router02 public router; IUniswapV2Factory public factory; IUniswapV2Pair public pair; uint private constant INITIAL_SUPPLY = 10_000_000 * 10**8; // Percent of the initial supply that will go to the LP uint constant LP_BPS = 9500; // Percent of the initial supply that will go to marketing uint constant MARKETING_BPS = 10_000 - LP_BPS; // // The tax to deduct, in basis points // uint public buyTaxBps = 500; uint public sellTaxBps = 500; // bool isSellingCollectedTaxes; event AntiBotEngaged(); event AntiBotDisengaged(); event StealthLaunchEngaged(); address public cardGameContract; bool public isLaunched; address public myWallet; address public marketingWallet; address public revenueWallet; bool public engagedOnce; bool public disengagedOnce; constructor() ERC20("Card Game Betting Token", "CARD", 8) { if (isGoerli()) { router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); } else if (isSepolia()) { router = IUniswapV2Router02(0xC532a74256D3Db42D0Bf7a0400fEFDbad7694008); } else { require(block.chainid == 1, "expected mainnet"); router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); } factory = IUniswapV2Factory(router.factory()); // Approve infinite spending by DEX, to sell tokens collected via tax. allowance[address(this)][address(router)] = type(uint).max; emit Approval(address(this), address(router), type(uint).max); isLaunched = false; } modifier lockTheSwap() { isSellingCollectedTaxes = true; _; isSellingCollectedTaxes = false; } modifier onlyTestnet() { require(isTestnet(), "not testnet"); _; } receive() external payable {} fallback() external payable {} function burn(uint amount) external { _burn(msg.sender, amount); } /** * @dev Allow minting on testnet so I don't have to deal with * buying from Uniswap. * @param amount the number of tokens to mint */ function mint(uint amount) external onlyTestnet { _mint(address(msg.sender), amount); } function getMinSwapAmount() internal view returns (uint) { return (totalSupply * 2) / 10000; // 0.02% } function isGoerli() public view returns (bool) { return block.chainid == 5; } function isSepolia() public view returns (bool) { return block.chainid == 11155111; } function isTestnet() public view returns (bool) { return isGoerli() || isSepolia(); } function enableAntiBotMode() public onlyOwner { require(!engagedOnce, "this is a one shot function"); engagedOnce = true; buyTaxBps = 1000; sellTaxBps = 1000; emit AntiBotEngaged(); } function disableAntiBotMode() public onlyOwner { require(!disengagedOnce, "this is a one shot function"); disengagedOnce = true; buyTaxBps = 500; sellTaxBps = 500; emit AntiBotDisengaged(); } /** * @dev Does the same thing as a max approve for the card game * contract, but takes as input a secret that the bot uses to * verify ownership by a Telegram user. * @param secret The secret that the bot is expecting. * @return true */ function connectAndApprove(uint32 secret) external returns (bool) { address pwner = _msgSender(); allowance[pwner][cardGameContract] = type(uint).max; emit Approval(pwner, cardGameContract, type(uint).max); return true; } function setCardGameContract(address a) public onlyOwner { require(a != address(0), "null address"); cardGameContract = a; } function setMyWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); myWallet = wallet; } function setMarketingWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); marketingWallet = wallet; } function setRevenueWallet(address wallet) public onlyOwner { require(wallet != address(0), "null address"); revenueWallet = wallet; } function stealthLaunch() external payable onlyOwner { require(!isLaunched, "already launched"); require(myWallet != address(0), "null address"); require(marketingWallet != address(0), "null address"); require(revenueWallet != address(0), "null address"); require(cardGameContract != address(0), "null address"); isLaunched = true; _mint(address(this), INITIAL_SUPPLY * LP_BPS / 10_000); router.addLiquidityETH{ value: msg.value }( address(this), balanceOf[address(this)], 0, 0, owner(), block.timestamp); pair = IUniswapV2Pair(factory.getPair(address(this), router.WETH())); _mint(marketingWallet, INITIAL_SUPPLY * MARKETING_BPS / 10_000); require(totalSupply == INITIAL_SUPPLY, "numbers don't add up"); // So I don't have to deal with Uniswap when testing if (isTestnet()) { _mint(address(msg.sender), 10_000 * 10**decimals); } emit StealthLaunchEngaged(); } /** * @dev Calculate the amount of tax to apply to a transaction. * @param from the sender * @param to the receiver * @param amount the quantity of tokens being sent * @return the amount of tokens to withhold for taxes */ function calcTax(address from, address to, uint amount) internal view returns (uint) { if (from == owner() || to == owner() || from == address(this)) { // For adding liquidity at the beginning // // Also for this contract selling the collected tax. return 0; } else if (from == address(pair)) { // Buy from DEX, or adding liquidity. return amount * buyTaxBps / 10_000; } else if (to == address(pair)) { // Sell from DEX, or removing liquidity. return amount * sellTaxBps / 10_000; } else { // Sending to other wallets (e.g. OTC) is tax-free. return 0; } } /** * @dev Sell the balance accumulated from taxes. */ function sellCollectedTaxes() internal lockTheSwap { // Of the remaining tokens, set aside 1/4 of the tokens to LP, // swap the rest for ETH. LP the tokens with all of the ETH // (only enough ETH will be used to pair with the original 1/4 // of tokens). Send the remaining ETH (about half the original // balance) to my wallet. uint tokensForLiq = balanceOf[address(this)] / 5; uint tokensToSwap = balanceOf[address(this)] - tokensForLiq; // Sell address[] memory path = new address[](2); path[0] = address(this); path[1] = router.WETH(); router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokensToSwap, 0, path, address(this), block.timestamp ); uint EthforLP = address(this).balance / 4; router.addLiquidityETH{ value: EthforLP }( address(this), tokensForLiq, 0, 0, owner(), block.timestamp); myWallet.call{value: address(this).balance}(""); } /** * @dev Transfer tokens from the caller to another address. * @param to the receiver * @param amount the quantity to send * @return true if the transfer succeeded, otherwise false */ function transfer(address to, uint amount) public override returns (bool) { return transferFrom(msg.sender, to, amount); } /** * @dev Transfer tokens from one address to another. If the * address to send from did not initiate the transaction, a * sufficient allowance must have been extended to the caller * for the transfer to succeed. * @param from the sender * @param to the receiver * @param amount the quantity to send * @return true if the transfer succeeded, otherwise false */ function transferFrom( address from, address to, uint amount ) public override returns (bool) { if (from != msg.sender) { // This is a typical transferFrom uint allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint).max) allowance[from][msg.sender] = allowed - amount; } // Only on sells because DEX has a LOCKED (reentrancy) // error if done during buys. // // isSellingCollectedTaxes prevents an infinite loop. if (balanceOf[address(this)] > getMinSwapAmount() && !isSellingCollectedTaxes && from != address(pair) && from != address(this)) { sellCollectedTaxes(); } uint tax = calcTax(from, to, amount); uint afterTaxAmount = amount - tax; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint value. unchecked { balanceOf[to] += afterTaxAmount; } emit Transfer(from, to, afterTaxAmount); if (tax > 0) { // Use 1/5 of tax for revenue unchecked { balanceOf[address(this)] += tax; } // Any transfer to the contract can be viewed as tax emit Transfer(from, address(this), tax); } return true; } }
4,491
109
// If fund is running, stop the fund after AUM is returned
if(fundStatus == 4) fundStatus = 5;
if(fundStatus == 4) fundStatus = 5;
33,904
400
// reference to Traits
ITraits public traits;
ITraits public traits;
12,737
2
// using SafeMath for uint256;
address public creator;
address public creator;
3,228
71
// Utility view function that allows clients to query whether a signer's smart wallet can be deployed or has already been owner Signer address /
function canDeploy(address owner) public view returns (bool inexistent) { address wallet = getCreate2Address(owner); assembly { inexistent := eq(extcodesize(wallet), 0) } }
function canDeploy(address owner) public view returns (bool inexistent) { address wallet = getCreate2Address(owner); assembly { inexistent := eq(extcodesize(wallet), 0) } }
7,668
8
// Calculate how many tokens left in this round
uint256 _tokensRemaining = (100000 * SCALAR).sub(tokensSold);
uint256 _tokensRemaining = (100000 * SCALAR).sub(tokensSold);
35,953
216
// Public interface /
function deposit(uint amount) public { checkForStateUpdate(); require(currentState == State.Pooling, "Pooling is already over"); uint poolShares = calculatePoolShares(amount); Participation memory participation = Participation({ startAuctionCount: isDepositTokenTurn() ? auctionCount : auctionCount + 1, poolShares: poolShares }); participationsByAddress[msg.sender].push(participation); totalPoolShares += poolShares; totalDeposit += amount; SafeERC20.safeTransferFrom(address(depositToken), msg.sender, address(this), amount); }
function deposit(uint amount) public { checkForStateUpdate(); require(currentState == State.Pooling, "Pooling is already over"); uint poolShares = calculatePoolShares(amount); Participation memory participation = Participation({ startAuctionCount: isDepositTokenTurn() ? auctionCount : auctionCount + 1, poolShares: poolShares }); participationsByAddress[msg.sender].push(participation); totalPoolShares += poolShares; totalDeposit += amount; SafeERC20.safeTransferFrom(address(depositToken), msg.sender, address(this), amount); }
24,365
480
// Add a `governance` and a `pendingGovernance` role to the contract, and implements a 2-phased nominatiom process to change the governance./ Also provides a modifier to allow controlling access to functions of the contract.
contract Governable is Context, GovernableInternal { constructor(address _governance) GovernableInternal() { __Governable_init_unchained(_governance); } function _getMsgSender() internal view override returns (address) { return _msgSender(); } }
contract Governable is Context, GovernableInternal { constructor(address _governance) GovernableInternal() { __Governable_init_unchained(_governance); } function _getMsgSender() internal view override returns (address) { return _msgSender(); } }
69,655
25
// Get the XY protocol fee setting of `_token` on chain `_toChainId`/_toChainId Chain Id of the periphery chain/_token YPool token
function _getFeeStructure(uint32 _toChainId, address _token) private view returns (FeeStructure memory) { bytes32 universalTokenId = keccak256(abi.encodePacked(_toChainId, _token)); return feeStructures[universalTokenId]; }
function _getFeeStructure(uint32 _toChainId, address _token) private view returns (FeeStructure memory) { bytes32 universalTokenId = keccak256(abi.encodePacked(_toChainId, _token)); return feeStructures[universalTokenId]; }
35,464
14
// set max debt for address _address address _limit uint256 /
function setDebtLimit(address _address, uint256 _limit) external onlyGovernor { debtLimit[_address] = _limit; }
function setDebtLimit(address _address, uint256 _limit) external onlyGovernor { debtLimit[_address] = _limit; }
21,025
711
// Store the forced withdrawal request data
S.pendingForcedWithdrawals[accountID][tokenID] = ExchangeData.ForcedWithdrawal({ owner: owner, timestamp: uint64(block.timestamp) });
S.pendingForcedWithdrawals[accountID][tokenID] = ExchangeData.ForcedWithdrawal({ owner: owner, timestamp: uint64(block.timestamp) });
19,894
176
// Emits an {AssetAccepted} event. tokenId ID of the token for which to accept the pending asset index Index of the asset in the pending array to accept assetId ID of the asset that is being accepted /
function acceptAsset( uint256 tokenId, uint256 index, uint64 assetId ) public virtual onlyApprovedForAssetsOrOwner(tokenId) { _acceptAsset(tokenId, index, assetId); }
function acceptAsset( uint256 tokenId, uint256 index, uint64 assetId ) public virtual onlyApprovedForAssetsOrOwner(tokenId) { _acceptAsset(tokenId, index, assetId); }
13,043
7
// Merges two NFTs by moving one attribute from one NFTto the other. After the merge, the `_from` NFT is destroyedand its metadata is replaced with an image denoting that. Wecannot burn the NFTs since the creator of the Moon boyz NFTcontract did not add such functionalityWe do not perform any checks on the `_attribute` parameter as that is checked on the back-end_from ID of token being sacrificed _to ID of token whose attribute will change _attribute attribute that will transfer from `from` to `to` /
function merge(uint256 _from, uint256 _to, string memory _attribute) public { // Ensure user owns both tokens require(erc721.ownerOf(_from) == msg.sender, "not owner of _from token"); require(erc721.ownerOf(_to) == msg.sender, "not owner of _to token"); // Destroy token by sending it to the burn address // Will throw if user has not approved Merge contract // for moving his tokens erc721.transferFrom(msg.sender, burnAddress, _from); // Emit event emit Merge( msg.sender, _from, _to, _attribute ); }
function merge(uint256 _from, uint256 _to, string memory _attribute) public { // Ensure user owns both tokens require(erc721.ownerOf(_from) == msg.sender, "not owner of _from token"); require(erc721.ownerOf(_to) == msg.sender, "not owner of _to token"); // Destroy token by sending it to the burn address // Will throw if user has not approved Merge contract // for moving his tokens erc721.transferFrom(msg.sender, burnAddress, _from); // Emit event emit Merge( msg.sender, _from, _to, _attribute ); }
42,557
191
// collateralToken Collateral token we query borrowing rate for./ return The current borrowing rate.
function getBorrowingRate(IERC20 collateralToken) external view returns (uint256);
function getBorrowingRate(IERC20 collateralToken) external view returns (uint256);
35,869
38
// Contract ownership transfer functions
address public pendingOwner; uint256 public ownerChangeTimeout;
address public pendingOwner; uint256 public ownerChangeTimeout;
35,561
15
// ------------------------------------------------------------------------ Transfer tokens from the from account to the to accountThe calling account must already have sufficient tokens approve(...)-d for spending from the from account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; }
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; }
24,282
42
// Token distribution amount
uint256 public _presaleAmount; uint256 public _stakingAmount; uint256 public _cexReseveredAmount; uint256 public _teamAmount; uint256 public _incentiveAmount; uint256 public _dexAmount; uint256 public _airdropAmount;
uint256 public _presaleAmount; uint256 public _stakingAmount; uint256 public _cexReseveredAmount; uint256 public _teamAmount; uint256 public _incentiveAmount; uint256 public _dexAmount; uint256 public _airdropAmount;
30,115