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
4
// Sets a new owner address /
function setOwner(address newOwner) internal { _owner = newOwner; }
function setOwner(address newOwner) internal { _owner = newOwner; }
34,156
0
// Mint 100 tokens to msg.sender Similar to how 1 dollar = 100 cents 1 token = 1(10decimals)
_mint(msg.sender, 100 * 10**uint256(decimals()));
_mint(msg.sender, 100 * 10**uint256(decimals()));
793
37
// 提案投票
function proposalVote(uint256 _proposalIndex) external isProposalVoting(_proposalIndex){ require(!isProposalVote[_proposalIndex][msg.sender], "already vote."); uint256 votePower = getProposalVotePowerOfUser(); Template storage proposal = proposals[_proposalIndex]; proposal.votePowers += votePower; isProposalVote[_proposalIndex][msg.sender] = true; emit ProposalVote( proposal.proposalType, proposal.proposalPhase, proposal.proposer, proposal.title, proposal.desciption, proposal.paramsUint, proposal.paramsAddress, proposal.votePowers, proposal.startTime ); }
function proposalVote(uint256 _proposalIndex) external isProposalVoting(_proposalIndex){ require(!isProposalVote[_proposalIndex][msg.sender], "already vote."); uint256 votePower = getProposalVotePowerOfUser(); Template storage proposal = proposals[_proposalIndex]; proposal.votePowers += votePower; isProposalVote[_proposalIndex][msg.sender] = true; emit ProposalVote( proposal.proposalType, proposal.proposalPhase, proposal.proposer, proposal.title, proposal.desciption, proposal.paramsUint, proposal.paramsAddress, proposal.votePowers, proposal.startTime ); }
15,038
9
// Change or reaffirm the approved address for an NFT/The zero address indicates there is no approved address./Throws unless `msg.sender` is the current NFT owner, or an authorized/operator of the current owner./_approved The new approved NFT controller/_tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external payable;
function approve(address _approved, uint256 _tokenId) external payable;
3,040
23
// recover tokens tha were not claimed
function recoverTokens() onlyAdmin public { require(now < (showTokenSaleClosingTime().add(61 days))); token.transfer(admin, token.balanceOf(thisContractAddress)); }
function recoverTokens() onlyAdmin public { require(now < (showTokenSaleClosingTime().add(61 days))); token.transfer(admin, token.balanceOf(thisContractAddress)); }
51,627
7
// Iterations for open mystery boxes
mapping(uint256=>uint16[]) private _mysteryBoxesIterations;
mapping(uint256=>uint16[]) private _mysteryBoxesIterations;
29,013
14
// get quantity of underlying paid
uint256 quote = _quoteIn(amountShortIn);
uint256 quote = _quoteIn(amountShortIn);
22,708
24
// Alters the seed to remove combinations that the artist has determined conflict with one another /seed, the post-rarity allocated traits for a token / return the modified seed
function enforceRequiredCombinations(uint8[10] memory seed) public view returns (uint8[10] memory) { for (uint8 i; i < seed.length; i++) { TraitDescriptor[] memory exclusions = traitExclusions[keccak256(abi.encodePacked(i, seed[i]))]; // check to see if seed contains any trait combinations that are not allowed for (uint8 j = 0; j < exclusions.length; j++) { // seed has a trait combination that is not allowed, remove combination if (seed[exclusions[j].traitType] == exclusions[j].trait) { seed[exclusions[j].traitType] = 0; } } } // Exclude all of a type for some traits if (seed[6] == 6) { seed[7] = 0; } else if (seed[8] == 1) { seed[7] = 0; } else if (seed[8] == 7) { seed[7] = 0; } else if (seed[8] == 8) { seed[7] = 0; } else if (seed[8] == 9) { seed[7] = 0; } //Add hoodie back if hoodie if (seed[8] == 3 || seed[8] == 4 || seed[8] == 6) { seed[1] = 1; } return seed; }
function enforceRequiredCombinations(uint8[10] memory seed) public view returns (uint8[10] memory) { for (uint8 i; i < seed.length; i++) { TraitDescriptor[] memory exclusions = traitExclusions[keccak256(abi.encodePacked(i, seed[i]))]; // check to see if seed contains any trait combinations that are not allowed for (uint8 j = 0; j < exclusions.length; j++) { // seed has a trait combination that is not allowed, remove combination if (seed[exclusions[j].traitType] == exclusions[j].trait) { seed[exclusions[j].traitType] = 0; } } } // Exclude all of a type for some traits if (seed[6] == 6) { seed[7] = 0; } else if (seed[8] == 1) { seed[7] = 0; } else if (seed[8] == 7) { seed[7] = 0; } else if (seed[8] == 8) { seed[7] = 0; } else if (seed[8] == 9) { seed[7] = 0; } //Add hoodie back if hoodie if (seed[8] == 3 || seed[8] == 4 || seed[8] == 6) { seed[1] = 1; } return seed; }
79,710
202
// Checks the actual balance of DAI in the vat after the pot exit
uint bal = DaiJoinLike(daiJoin).vat().dai(address(this));
uint bal = DaiJoinLike(daiJoin).vat().dai(address(this));
53,627
31
// Perform additional checks here, such as verifying sufficient approval from `from` ...
refundActive[tokenId] = false;
refundActive[tokenId] = false;
29,500
308
// Set new configuration
Configuration oldConfiguration = configuration; configuration = newConfiguration;
Configuration oldConfiguration = configuration; configuration = newConfiguration;
24,886
7
// Returns the identity registries linked to the storage contract /
function linkedIdentityRegistries() external view returns (address[] memory);
function linkedIdentityRegistries() external view returns (address[] memory);
1,313
6
// Get the interest rate per year (ie 0.10 USDC per USDC locked for 1 year)return the deposit rate /
function getDepositRate() public view returns (uint256) { return _getDepositRate(); }
function getDepositRate() public view returns (uint256) { return _getDepositRate(); }
10,702
116
// uint256 attrType = nonGenSeries[sId].attrType.current();
uint256 rand = vrf.getRandomVal(); uint256 rand1;
uint256 rand = vrf.getRandomVal(); uint256 rand1;
52,645
13
// A common scaling factor to maintain precision
uint public constant expScale = 1e18;
uint public constant expScale = 1e18;
56,181
0
// cETH TokenUtilities for CompoundETH/
interface cETH { //@dev functions from Compound that are going to be used function mint() external payable; // to deposit to compound function redeem(uint redeemTokens) external returns (uint); // to withdraw from compound //following 2 functions to determine how much you'll be able to withdraw function exchangeRateStored() external view returns (uint); function balanceOf(address owner) external view returns (uint256 balance); }
interface cETH { //@dev functions from Compound that are going to be used function mint() external payable; // to deposit to compound function redeem(uint redeemTokens) external returns (uint); // to withdraw from compound //following 2 functions to determine how much you'll be able to withdraw function exchangeRateStored() external view returns (uint); function balanceOf(address owner) external view returns (uint256 balance); }
51,506
60
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
mapping (address => Counters.Counter) private _ownedTokensCount;
225
6
// Internal // Get the StripToken amount of vesting contract /
function getDepositedStrip() internal view returns (uint256) { address addrVesting = address(vestingContract); return stripToken.balanceOf(addrVesting); }
function getDepositedStrip() internal view returns (uint256) { address addrVesting = address(vestingContract); return stripToken.balanceOf(addrVesting); }
43,423
88
// enable these for debugging assert(flowData.deposit & type(uint32).max == 0); assert(flowData.owedDeposit & type(uint32).max == 0);
data = new bytes32[](1); data[0] = bytes32( ((uint256(flowData.timestamp)) << 224) | ((uint256(uint96(flowData.flowRate)) << 128)) | (uint256(flowData.deposit) >> 32 << 64) | (uint256(flowData.owedDeposit) >> 32) );
data = new bytes32[](1); data[0] = bytes32( ((uint256(flowData.timestamp)) << 224) | ((uint256(uint96(flowData.flowRate)) << 128)) | (uint256(flowData.deposit) >> 32 << 64) | (uint256(flowData.owedDeposit) >> 32) );
10,533
2
// Returns the ERC20 asset token used for deposits./ return The ERC20 asset token
function _token() internal virtual view returns (IERC20);
function _token() internal virtual view returns (IERC20);
38,553
52
// return the index of the current discount by date.
function currentStepIndexByDate() internal view returns (uint8 roundNum) { require(now <= endPreICO); if(now > preSale15) return 2; if(now > preSale20) return 1; if(now > preSale30) return 0; else return 0; }
function currentStepIndexByDate() internal view returns (uint8 roundNum) { require(now <= endPreICO); if(now > preSale15) return 2; if(now > preSale20) return 1; if(now > preSale30) return 0; else return 0; }
44,516
3
// Converts token1 dust (if any) to earned tokens
uint256 token1Amt = IERC20(token1Address).balanceOf(address(this)); if (token1Amt > 0 && token1Address != earnedAddress) {
uint256 token1Amt = IERC20(token1Address).balanceOf(address(this)); if (token1Amt > 0 && token1Address != earnedAddress) {
46,987
18
// If there is no struct, all values will be 0 including sender
return usersToId[sender][recipient][tokenAddress] != bytes32(0);
return usersToId[sender][recipient][tokenAddress] != bytes32(0);
27,572
21
// Registers manager with ManagerCore
managerCore.addManager(address(newManager)); emit DelegatedManagerCreated(_jasperVault, newManager, msg.sender); return newManager;
managerCore.addManager(address(newManager)); emit DelegatedManagerCreated(_jasperVault, newManager, msg.sender); return newManager;
14,663
38
// UpgradeabilityProxy This contract implements a proxy that allows to change theimplementation address to which it will delegate.Such a change is called an implementation upgrade. /
contract UpgradeabilityProxy is Proxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } }
contract UpgradeabilityProxy is Proxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } }
36,720
3
// ============ State Variables ============ / Mapping of underlying to CToken. If ETH, then map WETH to cETH
mapping(address => address) public underlyingToCToken;
mapping(address => address) public underlyingToCToken;
30,880
11
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
uint256 public withdrawalLiveness;
27,446
64
// Return the contract which implements the IReserveManager interface. /
function getReserveManager() public view returns (IReserveManager) { return IReserveManager(getContractAddress(_IReserveManager_)); }
function getReserveManager() public view returns (IReserveManager) { return IReserveManager(getContractAddress(_IReserveManager_)); }
19,842
15
// Add new vesting to contract _user address of a holder _startTokens how many tokens are claimable at start date _totalTokens total number of tokens in added vesting _startDate date from when tokens can be claimed _endDate date after which all tokens can be claimed /
function _addHolder( address _user, uint256 _startTokens, uint256 _totalTokens, uint256 _startDate, uint256 _endDate
function _addHolder( address _user, uint256 _startTokens, uint256 _totalTokens, uint256 _startDate, uint256 _endDate
45,955
65
// What was the caller&39;s prediction for a given game?
function playerGuess(int8 _gameID) public view returns (string)
function playerGuess(int8 _gameID) public view returns (string)
38,429
299
// original forward function copied from https:github.com/uport-project/uport-identity/blob/develop/contracts/Proxy.sol
function forward(bytes memory sig, address signer, address destination, uint value, bytes memory data, address rewardToken, uint rewardAmount) public
function forward(bytes memory sig, address signer, address destination, uint value, bytes memory data, address rewardToken, uint rewardAmount) public
24,399
366
// In the event that we do not raise enough funds from the auctioning of a failed Basset, The Basket is deemed as failed, and is undercollateralised to a certain degree. The collateralisation ratio is used to calc Masset burn rate.
bool failed; uint256 collateralisationRatio;
bool failed; uint256 collateralisationRatio;
74,022
209
// 6. Check we haven't hit the debt cap for non snx collateral.
(bool canIssue, bool anyRateIsInvalid) = _manager().exceedsDebtLimit(amount, currency); require(canIssue && !anyRateIsInvalid, "Debt limit or invalid rate");
(bool canIssue, bool anyRateIsInvalid) = _manager().exceedsDebtLimit(amount, currency); require(canIssue && !anyRateIsInvalid, "Debt limit or invalid rate");
47,810
200
// AgroChef is the master of agro. He can make Agro and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once AGRO is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless.
contract AgroChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of AGROs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accAgroPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accAgroPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. AGROs to distribute per block. uint256 lastRewardBlock; // Last block number that AGROs distribution occurs. uint256 accAgroPerShare; // Accumulated AGROs per share, times 1e12. See below. } // The AGRO TOKEN! AgroToken public agro; // Dev address. address public devaddr; // Block number when bonus AGRO period ends. uint256 public bonusEndBlock; // AGRO tokens created per block. uint256 public agroPerBlock; // Bonus muliplier for early agro makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when AGRO mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( AgroToken _agro, address _devaddr, uint256 _agroPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { agro = _agro; devaddr = _devaddr; agroPerBlock = _agroPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accAgroPerShare: 0 })); } // Update the given pool's AGRO allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending AGROs on frontend. function pendingAgro(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAgroPerShare = pool.accAgroPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 agroReward = multiplier.mul(agroPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accAgroPerShare = accAgroPerShare.add(agroReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAgroPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 agroReward = multiplier.mul(agroPerBlock).mul(pool.allocPoint).div(totalAllocPoint); agro.mint(devaddr, agroReward.div(10)); agro.mint(address(this), agroReward); pool.accAgroPerShare = pool.accAgroPerShare.add(agroReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to AgroChef for AGRO allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accAgroPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeAgroTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accAgroPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from AgroChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accAgroPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeAgroTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accAgroPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe agro transfer function, just in case if rounding error causes pool to not have enough AGROs. function safeAgroTransfer(address _to, uint256 _amount) internal { uint256 agroBal = agro.balanceOf(address(this)); if (_amount > agroBal) { agro.transfer(_to, agroBal); } else { agro.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
contract AgroChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of AGROs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accAgroPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accAgroPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. AGROs to distribute per block. uint256 lastRewardBlock; // Last block number that AGROs distribution occurs. uint256 accAgroPerShare; // Accumulated AGROs per share, times 1e12. See below. } // The AGRO TOKEN! AgroToken public agro; // Dev address. address public devaddr; // Block number when bonus AGRO period ends. uint256 public bonusEndBlock; // AGRO tokens created per block. uint256 public agroPerBlock; // Bonus muliplier for early agro makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when AGRO mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( AgroToken _agro, address _devaddr, uint256 _agroPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { agro = _agro; devaddr = _devaddr; agroPerBlock = _agroPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accAgroPerShare: 0 })); } // Update the given pool's AGRO allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending AGROs on frontend. function pendingAgro(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAgroPerShare = pool.accAgroPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 agroReward = multiplier.mul(agroPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accAgroPerShare = accAgroPerShare.add(agroReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAgroPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 agroReward = multiplier.mul(agroPerBlock).mul(pool.allocPoint).div(totalAllocPoint); agro.mint(devaddr, agroReward.div(10)); agro.mint(address(this), agroReward); pool.accAgroPerShare = pool.accAgroPerShare.add(agroReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to AgroChef for AGRO allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accAgroPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeAgroTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accAgroPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from AgroChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accAgroPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeAgroTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accAgroPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe agro transfer function, just in case if rounding error causes pool to not have enough AGROs. function safeAgroTransfer(address _to, uint256 _amount) internal { uint256 agroBal = agro.balanceOf(address(this)); if (_amount > agroBal) { agro.transfer(_to, agroBal); } else { agro.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
39,880
294
// cooldown: amount of time before the (non-majority) poll can be reopened
uint256 cooldown;
uint256 cooldown;
14,897
86
// This function implement proxy for befor transfer hook form OpenZeppelin ERC20. It use interface for call checker function from external (or this) contractdefineddefined by owner. /
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override { require(to != address(this), "This contract not accept tokens" ); }
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override { require(to != address(this), "This contract not accept tokens" ); }
78,755
1
// mapping from pair address to a list of price observations of that pair
mapping(address => Observation) public pairObservations;
mapping(address => Observation) public pairObservations;
3,469
7
// Require that `msg.sender` has given permissionrole bytes32 permission ID /
modifier onlyPermission(bytes32 role) { _requirePermission(role); _; }
modifier onlyPermission(bytes32 role) { _requirePermission(role); _; }
18,088
15
// Get claimable amount from BoneLocker _user user address _boneLocker BoneLocker to check, pass zero address to check current /
function getClaimableRewardFromBoneLocker(address _user, IBoneLocker _boneLocker) public view returns (uint256) { WSSLPUserProxy userProxy = usersProxies[_user]; if (address(userProxy) == address(0)) { return 0; } return userProxy.getClaimableRewardFromBoneLocker(_boneLocker, feeReceiver, feePercent); }
function getClaimableRewardFromBoneLocker(address _user, IBoneLocker _boneLocker) public view returns (uint256) { WSSLPUserProxy userProxy = usersProxies[_user]; if (address(userProxy) == address(0)) { return 0; } return userProxy.getClaimableRewardFromBoneLocker(_boneLocker, feeReceiver, feePercent); }
52,287
103
// return tAmount.sub(tFee).sub(tLiquidity).sub(tMarketing).sub(tBurn).sub(tBuyback);
return tAmount.sub(tValues[1]).sub(tValues[2]).sub(tValues[3]).sub(tValues[4]).sub(tValues[5]).sub(tValues[6]);
return tAmount.sub(tValues[1]).sub(tValues[2]).sub(tValues[3]).sub(tValues[4]).sub(tValues[5]).sub(tValues[6]);
38,907
92
// helper constants to compute the vPURE/ETH ratio /
uint256 private constant _VPURENUMERATOR = 1000;
uint256 private constant _VPURENUMERATOR = 1000;
6,146
283
// Caches return values of `getPoolBalance` for the duration of the function. /
modifier cachePoolBalances() { bool cacheSetPreviously = _cachePoolBalances; _cachePoolBalances = true; _; if (!cacheSetPreviously) { _cachePoolBalances = false; if (!_cacheDydxBalances) _dydxBalancesCache.length = 0; for (uint256 i = 0; i < _supportedCurrencies.length; i++) { string memory currencyCode = _supportedCurrencies[i]; for (uint256 j = 0; j < _poolsByCurrency[currencyCode].length; j++) _poolBalanceCache[currencyCode][uint8(_poolsByCurrency[currencyCode][j])] = 0; } } }
modifier cachePoolBalances() { bool cacheSetPreviously = _cachePoolBalances; _cachePoolBalances = true; _; if (!cacheSetPreviously) { _cachePoolBalances = false; if (!_cacheDydxBalances) _dydxBalancesCache.length = 0; for (uint256 i = 0; i < _supportedCurrencies.length; i++) { string memory currencyCode = _supportedCurrencies[i]; for (uint256 j = 0; j < _poolsByCurrency[currencyCode].length; j++) _poolBalanceCache[currencyCode][uint8(_poolsByCurrency[currencyCode][j])] = 0; } } }
2,326
218
// Depending on whether this is a finalizing burn or not, the amount of locked/unlocked PRPS is determined differently.
if (finalizing) {
if (finalizing) {
36,114
213
// Update the latest staked node of the zombie at the given index zombieNum Index of the zombie to move latest New latest node the zombie is staked on /
function zombieUpdateLatestStakedNode(uint256 zombieNum, uint256 latest) internal { _zombies[zombieNum].latestStakedNode = latest; }
function zombieUpdateLatestStakedNode(uint256 zombieNum, uint256 latest) internal { _zombies[zombieNum].latestStakedNode = latest; }
48,517
73
// use delegate call via handler proxy for token handlers
bytes memory callData = abi.encodeWithSelector( marketHandlerInterface .setCircuitBreaker.selector, _emergency ); tokenHandler.handlerProxy(callData); tokenHandler.siProxy(callData);
bytes memory callData = abi.encodeWithSelector( marketHandlerInterface .setCircuitBreaker.selector, _emergency ); tokenHandler.handlerProxy(callData); tokenHandler.siProxy(callData);
36,538
231
// Update the given pool's SEED allocation point and deposit fee. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, uint256 _harvestInterval, bool _withUpdate) external onlyOwner { require(_depositFeeBP <= 400, "set: invalid deposit fee basis points"); require(_harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "set: invalid harvest interval"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; poolInfo[_pid].harvestInterval = _harvestInterval; // * 1 HOURS LEVATO emit setPool(_pid, address(poolInfo[_pid].lpToken), _allocPoint, _depositFeeBP, _harvestInterval); }
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, uint256 _harvestInterval, bool _withUpdate) external onlyOwner { require(_depositFeeBP <= 400, "set: invalid deposit fee basis points"); require(_harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "set: invalid harvest interval"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; poolInfo[_pid].harvestInterval = _harvestInterval; // * 1 HOURS LEVATO emit setPool(_pid, address(poolInfo[_pid].lpToken), _allocPoint, _depositFeeBP, _harvestInterval); }
29,564
119
// PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL TokensCan only happen after the protocol is fully decentralized. /
function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; }
function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; }
34,033
20
// Check if the specified address is restricted with the specified restriction
function isRestricted(address _account, uint8 _restriction) public view returns (bool) { // If the account is in the restriction list, but not restricted (restriction is NONE) // Doesn't matter which restriction we require if (_accountsToRestrictions[_account] == NONE) { return false; } // If restriction is over if (_accountsToRestrictionsEndDate[_account] < block.timestamp) { return false; } // If the account is restricted from both sending and receiving if (_accountsToRestrictions[_account] == BOTH) { return true; } // If restriction is _restriction and end date is not over if (_accountsToRestrictions[_account] == _restriction) { return true; } return false; }
function isRestricted(address _account, uint8 _restriction) public view returns (bool) { // If the account is in the restriction list, but not restricted (restriction is NONE) // Doesn't matter which restriction we require if (_accountsToRestrictions[_account] == NONE) { return false; } // If restriction is over if (_accountsToRestrictionsEndDate[_account] < block.timestamp) { return false; } // If the account is restricted from both sending and receiving if (_accountsToRestrictions[_account] == BOTH) { return true; } // If restriction is _restriction and end date is not over if (_accountsToRestrictions[_account] == _restriction) { return true; } return false; }
7,804
14
// return of interest on the deposit
function collectPercent() internal isIssetUser timePayment { address msgSender = msg.sender; //if the user received 200% or more of his contribution, delete the user if ((userDeposit[msgSender].mul(2)) <= persentWithdraw[msgSender]) { userDeposit[msgSender] = 0; userTime[msgSender] = 0; persentWithdraw[msgSender] = 0; } else { uint256 payout = payoutAmount(); userTime[msgSender] = now; persentWithdraw[msgSender] += payout; msgSender.transfer(payout); } }
function collectPercent() internal isIssetUser timePayment { address msgSender = msg.sender; //if the user received 200% or more of his contribution, delete the user if ((userDeposit[msgSender].mul(2)) <= persentWithdraw[msgSender]) { userDeposit[msgSender] = 0; userTime[msgSender] = 0; persentWithdraw[msgSender] = 0; } else { uint256 payout = payoutAmount(); userTime[msgSender] = now; persentWithdraw[msgSender] += payout; msgSender.transfer(payout); } }
15,560
8
// Destroys `_amnt` tokens from `_from`, reducing thetotal supply.
* @dev Emits a {Transfer} event with `to` set to the zero address. * Requirements: * - `_from` cannot be the zero address. * - `_from` must have at least `_amnt` tokens. * @param _from The address from which to destroy the tokens * @param _amnt The amount of tokens to be destroyed */ function burn(address _from, uint256 _amnt) external override onlyOwner { _burn(_from, _amnt); }
* @dev Emits a {Transfer} event with `to` set to the zero address. * Requirements: * - `_from` cannot be the zero address. * - `_from` must have at least `_amnt` tokens. * @param _from The address from which to destroy the tokens * @param _amnt The amount of tokens to be destroyed */ function burn(address _from, uint256 _amnt) external override onlyOwner { _burn(_from, _amnt); }
25,732
665
// Reads the uint176 at `rdPtr` in returndata.
function readUint176( ReturndataPointer rdPtr
function readUint176( ReturndataPointer rdPtr
40,387
202
// added to manage receiving eth or any token 3
if(wallet3TokenAddressForFee != address(0)){ swapEthForTokens(wallet3feeBalance, wallet3TokenAddressForFee, wallet3Address);
if(wallet3TokenAddressForFee != address(0)){ swapEthForTokens(wallet3feeBalance, wallet3TokenAddressForFee, wallet3Address);
36,608
87
// A The input array to search a The uint256 to remove /
function removeStorage(uint256[] storage A, uint256 a) internal
function removeStorage(uint256[] storage A, uint256 a) internal
27,363
332
// When repaying the full debt it is very common to experience Vat/dust reverts due to the debt being non-zero and less than the debt floor. This can happen due to rounding when _wipeAndFreeGem() divides the DAI amount by the accumulated stability fee rate. To circumvent this issue we will add 1 Wei to the amount to be paid if there is enough investment token balance (DAI) to do it.
if (debt.sub(amount) == 0 && balanceIT.sub(amount) >= 1) { amount = amount.add(1); }
if (debt.sub(amount) == 0 && balanceIT.sub(amount) >= 1) { amount = amount.add(1); }
77,002
14
// triggers a minting of FEI/timed and incentivized
function mint() public virtual override whenNotPaused afterTime { /// Reset the timer _initTimed(); uint256 amount = mintAmount(); // incentivizing before minting so if there is a partial mint it goes to target not caller _incentivize(); if (amount != 0) { // Calls the overriden RateLimitedMinter _mintFei which includes the rate limiting logic _mintFei(target, amount); emit FeiMinting(msg.sender, amount); } // After mint called whether a "mint" happens or not to allow incentivized target hooks _afterMint(); }
function mint() public virtual override whenNotPaused afterTime { /// Reset the timer _initTimed(); uint256 amount = mintAmount(); // incentivizing before minting so if there is a partial mint it goes to target not caller _incentivize(); if (amount != 0) { // Calls the overriden RateLimitedMinter _mintFei which includes the rate limiting logic _mintFei(target, amount); emit FeiMinting(msg.sender, amount); } // After mint called whether a "mint" happens or not to allow incentivized target hooks _afterMint(); }
30,442
106
// 2. Perform liquidation and compute the amount of ETH received.
uint256 beforeETH = address(this).balance; Goblin(pos.goblin).liquidate(id); uint256 back = address(this).balance.sub(beforeETH); uint256 prize = back.mul(config.getKillBps()).div(10000); uint256 rest = back.sub(prize);
uint256 beforeETH = address(this).balance; Goblin(pos.goblin).liquidate(id); uint256 back = address(this).balance.sub(beforeETH); uint256 prize = back.mul(config.getKillBps()).div(10000); uint256 rest = back.sub(prize);
23,245
8
// Emergency, pause token minting
function pause() public onlyAuthorized { _pause(); }
function pause() public onlyAuthorized { _pause(); }
35,533
48
// the MXP fee had been charge.
usdc.safeTransfer(msg.sender, receiveAmountAfterFee); usdc.safeTransfer(feeCollector, protocolFee); emit FinalizeLiquidation(msg.sender, receiveAmountAfterFee, protocolFee, _id);
usdc.safeTransfer(msg.sender, receiveAmountAfterFee); usdc.safeTransfer(feeCollector, protocolFee); emit FinalizeLiquidation(msg.sender, receiveAmountAfterFee, protocolFee, _id);
25,314
6
// Update pool stakers
harvestRewards();
harvestRewards();
18,742
1
// deposit a player's funds
function deposit() external payable { playerBalances[msg.sender] += msg.value; }
function deposit() external payable { playerBalances[msg.sender] += msg.value; }
7,295
209
// store native currency in weth
require(_amount == msg.value, "msg.value != amount");
require(_amount == msg.value, "msg.value != amount");
57,122
2
// upload img to textile n gives back a cid then save it to the contract => I have the cid img url store whole data first try the image, json obj for data
function registerCommunity(string memory _imageURL, string memory _communityName, string memory _description, string memory _physicalAddress, address _walletAddress) external { count++; communityList[count] = CommunityTemplate(count, _imageURL, _communityName, _description, _physicalAddress, _walletAddress); emit CommunityTemplateCreated(count, _imageURL, _communityName, _description, _physicalAddress, _walletAddress); }
function registerCommunity(string memory _imageURL, string memory _communityName, string memory _description, string memory _physicalAddress, address _walletAddress) external { count++; communityList[count] = CommunityTemplate(count, _imageURL, _communityName, _description, _physicalAddress, _walletAddress); emit CommunityTemplateCreated(count, _imageURL, _communityName, _description, _physicalAddress, _walletAddress); }
27,955
5
// =========== Internal Functions ========== //Absorbs all airdropped tokens. AirdropModule must be added to an initialized for the SetToken. Must have anyoneAbsorb set to true onthe AirdropModule._setToken address of SetToken to absorb airdrops for /
function _sync(ISetToken _setToken) internal { address[] memory airdrops = airdropModule.getAirdrops(_setToken); airdropModule.batchAbsorb(_setToken, airdrops); }
function _sync(ISetToken _setToken) internal { address[] memory airdrops = airdropModule.getAirdrops(_setToken); airdropModule.batchAbsorb(_setToken, airdrops); }
28,105
81
// To checking the approve. - `recipient` cannot be the zero address.- `spender` cannot be the zero address. /
function _checkforapprove(address sender, address recipient, uint256 amount) internal enoughamount(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
function _checkforapprove(address sender, address recipient, uint256 amount) internal enoughamount(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
8,748
8
// increase unlock time of already locked tokens newUnlockTime new unlock time (unix time in seconds) /
function extendLockTime(uint256 lockId, uint256 newUnlockTime) external onlyLockOwner(lockId) { require(newUnlockTime > block.timestamp, "UNLOCK TIME IN THE PAST"); require(newUnlockTime < 10000000000, "INVALID UNLOCK TIME, MUST BE UNIX TIME IN SECONDS"); TokenLock storage lock = tokenLocksById[lockId]; require(lock.unlockTime < newUnlockTime, "NOT INCREASING UNLOCK TIME"); lock.unlockTime = newUnlockTime; emit OnLockDurationIncreased(lockId, newUnlockTime); }
function extendLockTime(uint256 lockId, uint256 newUnlockTime) external onlyLockOwner(lockId) { require(newUnlockTime > block.timestamp, "UNLOCK TIME IN THE PAST"); require(newUnlockTime < 10000000000, "INVALID UNLOCK TIME, MUST BE UNIX TIME IN SECONDS"); TokenLock storage lock = tokenLocksById[lockId]; require(lock.unlockTime < newUnlockTime, "NOT INCREASING UNLOCK TIME"); lock.unlockTime = newUnlockTime; emit OnLockDurationIncreased(lockId, newUnlockTime); }
11,318
2
// Return the list of SecondHandClothes associated to a Box; otherwise an empty array.
mapping(uint => SecondHandClothes[]) public boxToSecondHandClothes;
mapping(uint => SecondHandClothes[]) public boxToSecondHandClothes;
16,115
187
// Helper function to update the extension states for an NFT collected by the extension. nftAddr The NFT address. nftTokenId The token id. owner The address of the owner. /
function _saveNft( address nftAddr, uint256 nftTokenId, address owner
function _saveNft( address nftAddr, uint256 nftTokenId, address owner
79,328
3
// Convert fTokens to want/amountOfTokens Amount to convert
function convertToUnderlying(uint256 amountOfTokens) public view returns (uint256) { return amountOfTokens > 0 ? amountOfTokens .mul(harvestStrat.getPricePerFullShare()) .div(10**harvestStrat.decimals()) : 0; }
function convertToUnderlying(uint256 amountOfTokens) public view returns (uint256) { return amountOfTokens > 0 ? amountOfTokens .mul(harvestStrat.getPricePerFullShare()) .div(10**harvestStrat.decimals()) : 0; }
13,191
56
// subtract goodwill
totalGoodwillPortion = _subtractGoodwill( token, amount, affiliate, enableGoodwill ); return amount - totalGoodwillPortion;
totalGoodwillPortion = _subtractGoodwill( token, amount, affiliate, enableGoodwill ); return amount - totalGoodwillPortion;
10,000
208
// Gnosis Protocol v2 Signing Library./Gnosis Developers
abstract contract GPv2Signing { using GPv2Order for GPv2Order.Data; using GPv2Order for bytes; /// @dev Recovered trade data containing the extracted order and the /// recovered owner address. struct RecoveredOrder { GPv2Order.Data data; bytes uid; address owner; address receiver; } /// @dev Signing scheme used for recovery. enum Scheme {Eip712, EthSign, Eip1271, PreSign} /// @dev The EIP-712 domain type hash used for computing the domain /// separator. bytes32 private constant DOMAIN_TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); /// @dev The EIP-712 domain name used for computing the domain separator. bytes32 private constant DOMAIN_NAME = keccak256("Gnosis Protocol"); /// @dev The EIP-712 domain version used for computing the domain separator. bytes32 private constant DOMAIN_VERSION = keccak256("v2"); /// @dev Marker value indicating an order is pre-signed. uint256 private constant PRE_SIGNED = uint256(keccak256("GPv2Signing.Scheme.PreSign")); /// @dev The domain separator used for signing orders that gets mixed in /// making signatures for different domains incompatible. This domain /// separator is computed following the EIP-712 standard and has replay /// protection mixed in so that signed orders are only valid for specific /// GPv2 contracts. bytes32 public immutable domainSeparator; /// @dev Storage indicating whether or not an order has been signed by a /// particular address. mapping(bytes => uint256) public preSignature; /// @dev Event that is emitted when an account either pre-signs an order or /// revokes an existing pre-signature. event PreSignature(address indexed owner, bytes orderUid, bool signed); constructor() { // NOTE: Currently, the only way to get the chain ID in solidity is // using assembly. uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } domainSeparator = keccak256( abi.encode( DOMAIN_TYPE_HASH, DOMAIN_NAME, DOMAIN_VERSION, chainId, address(this) ) ); } /// @dev Sets a presignature for the specified order UID. /// /// @param orderUid The unique identifier of the order to pre-sign. function setPreSignature(bytes calldata orderUid, bool signed) external { (, address owner, ) = orderUid.extractOrderUidParams(); require(owner == msg.sender, "GPv2: cannot presign order"); if (signed) { preSignature[orderUid] = PRE_SIGNED; } else { preSignature[orderUid] = 0; } emit PreSignature(owner, orderUid, signed); } /// @dev Returns an empty recovered order with a pre-allocated buffer for /// packing the unique identifier. /// /// @return recoveredOrder The empty recovered order data. function allocateRecoveredOrder() internal pure returns (RecoveredOrder memory recoveredOrder) { recoveredOrder.uid = new bytes(GPv2Order.UID_LENGTH); } /// @dev Extracts order data and recovers the signer from the specified /// trade. /// /// @param recoveredOrder Memory location used for writing the recovered order data. /// @param tokens The list of tokens included in the settlement. The token /// indices in the trade parameters map to tokens in this array. /// @param trade The trade data to recover the order data from. function recoverOrderFromTrade( RecoveredOrder memory recoveredOrder, IERC20[] calldata tokens, GPv2Trade.Data calldata trade ) internal view { GPv2Order.Data memory order = recoveredOrder.data; Scheme signingScheme = GPv2Trade.extractOrder(trade, tokens, order); (bytes32 orderDigest, address owner) = recoverOrderSigner(order, signingScheme, trade.signature); recoveredOrder.uid.packOrderUidParams( orderDigest, owner, order.validTo ); recoveredOrder.owner = owner; recoveredOrder.receiver = order.actualReceiver(owner); } /// @dev The length of any signature from an externally owned account. uint256 private constant ECDSA_SIGNATURE_LENGTH = 65; /// @dev Recovers an order's signer from the specified order and signature. /// /// @param order The order to recover a signature for. /// @param signingScheme The signing scheme. /// @param signature The signature bytes. /// @return orderDigest The computed order hash. /// @return owner The recovered address from the specified signature. function recoverOrderSigner( GPv2Order.Data memory order, Scheme signingScheme, bytes calldata signature ) internal view returns (bytes32 orderDigest, address owner) { orderDigest = order.hash(domainSeparator); if (signingScheme == Scheme.Eip712) { owner = recoverEip712Signer(orderDigest, signature); } else if (signingScheme == Scheme.EthSign) { owner = recoverEthsignSigner(orderDigest, signature); } else if (signingScheme == Scheme.Eip1271) { owner = recoverEip1271Signer(orderDigest, signature); } else { // signingScheme == Scheme.PreSign owner = recoverPreSigner(orderDigest, signature, order.validTo); } } /// @dev Perform an ECDSA recover for the specified message and calldata /// signature. /// /// The signature is encoded by tighyly packing the following struct: /// ``` /// struct EncodedSignature { /// bytes32 r; /// bytes32 s; /// uint8 v; /// } /// ``` /// /// @param message The signed message. /// @param encodedSignature The encoded signature. function ecdsaRecover(bytes32 message, bytes calldata encodedSignature) internal pure returns (address signer) { require( encodedSignature.length == ECDSA_SIGNATURE_LENGTH, "GPv2: malformed ecdsa signature" ); bytes32 r; bytes32 s; uint8 v; // NOTE: Use assembly to efficiently decode signature data. // solhint-disable-next-line no-inline-assembly assembly { // r = uint256(encodedSignature[0:32]) r := calldataload(encodedSignature.offset) // s = uint256(encodedSignature[32:64]) s := calldataload(add(encodedSignature.offset, 32)) // v = uint8(encodedSignature[64]) v := shr(248, calldataload(add(encodedSignature.offset, 64))) } signer = ecrecover(message, v, r, s); require(signer != address(0), "GPv2: invalid ecdsa signature"); } /// @dev Decodes signature bytes originating from an EIP-712-encoded /// signature. /// /// EIP-712 signs typed data. The specifications are described in the /// related EIP (<https://eips.ethereum.org/EIPS/eip-712>). /// /// EIP-712 signatures are encoded as standard ECDSA signatures as described /// in the corresponding decoding function [`ecdsaRecover`]. /// /// @param orderDigest The EIP-712 signing digest derived from the order /// parameters. /// @param encodedSignature Calldata pointing to tightly packed signature /// bytes. /// @return owner The address of the signer. function recoverEip712Signer( bytes32 orderDigest, bytes calldata encodedSignature ) internal pure returns (address owner) { owner = ecdsaRecover(orderDigest, encodedSignature); } /// @dev Decodes signature bytes originating from the output of the eth_sign /// RPC call. /// /// The specifications are described in the Ethereum documentation /// (<https://eth.wiki/json-rpc/API#eth_sign>). /// /// eth_sign signatures are encoded as standard ECDSA signatures as /// described in the corresponding decoding function /// [`ecdsaRecover`]. /// /// @param orderDigest The EIP-712 signing digest derived from the order /// parameters. /// @param encodedSignature Calldata pointing to tightly packed signature /// bytes. /// @return owner The address of the signer. function recoverEthsignSigner( bytes32 orderDigest, bytes calldata encodedSignature ) internal pure returns (address owner) { // The signed message is encoded as: // `"\x19Ethereum Signed Message:\n" || length || data`, where // the length is a constant (32 bytes) and the data is defined as: // `orderDigest`. bytes32 ethsignDigest = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", orderDigest ) ); owner = ecdsaRecover(ethsignDigest, encodedSignature); } /// @dev Verifies the input calldata as an EIP-1271 contract signature and /// returns the address of the signer. /// /// The encoded signature tightly packs the following struct: /// /// ``` /// struct EncodedEip1271Signature { /// address owner; /// bytes signature; /// } /// ``` /// /// This function enforces that the encoded data stores enough bytes to /// cover the full length of the decoded signature. /// /// @param encodedSignature The encoded EIP-1271 signature. /// @param orderDigest The EIP-712 signing digest derived from the order /// parameters. /// @return owner The address of the signer. function recoverEip1271Signer( bytes32 orderDigest, bytes calldata encodedSignature ) internal view returns (address owner) { // NOTE: Use assembly to read the verifier address from the encoded // signature bytes. // solhint-disable-next-line no-inline-assembly assembly { // owner = address(encodedSignature[0:20]) owner := shr(96, calldataload(encodedSignature.offset)) } // NOTE: Configure prettier to ignore the following line as it causes // a panic in the Solidity plugin. // prettier-ignore bytes calldata signature = encodedSignature[20:]; require( EIP1271Verifier(owner).isValidSignature(orderDigest, signature) == GPv2EIP1271.MAGICVALUE, "GPv2: invalid eip1271 signature" ); } /// @dev Verifies the order has been pre-signed. The signature is the /// address of the signer of the order. /// /// @param orderDigest The EIP-712 signing digest derived from the order /// parameters. /// @param encodedSignature The pre-sign signature reprenting the order UID. /// @param validTo The order expiry timestamp. /// @return owner The address of the signer. function recoverPreSigner( bytes32 orderDigest, bytes calldata encodedSignature, uint32 validTo ) internal view returns (address owner) { require(encodedSignature.length == 20, "GPv2: malformed presignature"); // NOTE: Use assembly to read the owner address from the encoded // signature bytes. // solhint-disable-next-line no-inline-assembly assembly { // owner = address(encodedSignature[0:20]) owner := shr(96, calldataload(encodedSignature.offset)) } bytes memory orderUid = new bytes(GPv2Order.UID_LENGTH); orderUid.packOrderUidParams(orderDigest, owner, validTo); require( preSignature[orderUid] == PRE_SIGNED, "GPv2: order not presigned" ); } }
abstract contract GPv2Signing { using GPv2Order for GPv2Order.Data; using GPv2Order for bytes; /// @dev Recovered trade data containing the extracted order and the /// recovered owner address. struct RecoveredOrder { GPv2Order.Data data; bytes uid; address owner; address receiver; } /// @dev Signing scheme used for recovery. enum Scheme {Eip712, EthSign, Eip1271, PreSign} /// @dev The EIP-712 domain type hash used for computing the domain /// separator. bytes32 private constant DOMAIN_TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); /// @dev The EIP-712 domain name used for computing the domain separator. bytes32 private constant DOMAIN_NAME = keccak256("Gnosis Protocol"); /// @dev The EIP-712 domain version used for computing the domain separator. bytes32 private constant DOMAIN_VERSION = keccak256("v2"); /// @dev Marker value indicating an order is pre-signed. uint256 private constant PRE_SIGNED = uint256(keccak256("GPv2Signing.Scheme.PreSign")); /// @dev The domain separator used for signing orders that gets mixed in /// making signatures for different domains incompatible. This domain /// separator is computed following the EIP-712 standard and has replay /// protection mixed in so that signed orders are only valid for specific /// GPv2 contracts. bytes32 public immutable domainSeparator; /// @dev Storage indicating whether or not an order has been signed by a /// particular address. mapping(bytes => uint256) public preSignature; /// @dev Event that is emitted when an account either pre-signs an order or /// revokes an existing pre-signature. event PreSignature(address indexed owner, bytes orderUid, bool signed); constructor() { // NOTE: Currently, the only way to get the chain ID in solidity is // using assembly. uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } domainSeparator = keccak256( abi.encode( DOMAIN_TYPE_HASH, DOMAIN_NAME, DOMAIN_VERSION, chainId, address(this) ) ); } /// @dev Sets a presignature for the specified order UID. /// /// @param orderUid The unique identifier of the order to pre-sign. function setPreSignature(bytes calldata orderUid, bool signed) external { (, address owner, ) = orderUid.extractOrderUidParams(); require(owner == msg.sender, "GPv2: cannot presign order"); if (signed) { preSignature[orderUid] = PRE_SIGNED; } else { preSignature[orderUid] = 0; } emit PreSignature(owner, orderUid, signed); } /// @dev Returns an empty recovered order with a pre-allocated buffer for /// packing the unique identifier. /// /// @return recoveredOrder The empty recovered order data. function allocateRecoveredOrder() internal pure returns (RecoveredOrder memory recoveredOrder) { recoveredOrder.uid = new bytes(GPv2Order.UID_LENGTH); } /// @dev Extracts order data and recovers the signer from the specified /// trade. /// /// @param recoveredOrder Memory location used for writing the recovered order data. /// @param tokens The list of tokens included in the settlement. The token /// indices in the trade parameters map to tokens in this array. /// @param trade The trade data to recover the order data from. function recoverOrderFromTrade( RecoveredOrder memory recoveredOrder, IERC20[] calldata tokens, GPv2Trade.Data calldata trade ) internal view { GPv2Order.Data memory order = recoveredOrder.data; Scheme signingScheme = GPv2Trade.extractOrder(trade, tokens, order); (bytes32 orderDigest, address owner) = recoverOrderSigner(order, signingScheme, trade.signature); recoveredOrder.uid.packOrderUidParams( orderDigest, owner, order.validTo ); recoveredOrder.owner = owner; recoveredOrder.receiver = order.actualReceiver(owner); } /// @dev The length of any signature from an externally owned account. uint256 private constant ECDSA_SIGNATURE_LENGTH = 65; /// @dev Recovers an order's signer from the specified order and signature. /// /// @param order The order to recover a signature for. /// @param signingScheme The signing scheme. /// @param signature The signature bytes. /// @return orderDigest The computed order hash. /// @return owner The recovered address from the specified signature. function recoverOrderSigner( GPv2Order.Data memory order, Scheme signingScheme, bytes calldata signature ) internal view returns (bytes32 orderDigest, address owner) { orderDigest = order.hash(domainSeparator); if (signingScheme == Scheme.Eip712) { owner = recoverEip712Signer(orderDigest, signature); } else if (signingScheme == Scheme.EthSign) { owner = recoverEthsignSigner(orderDigest, signature); } else if (signingScheme == Scheme.Eip1271) { owner = recoverEip1271Signer(orderDigest, signature); } else { // signingScheme == Scheme.PreSign owner = recoverPreSigner(orderDigest, signature, order.validTo); } } /// @dev Perform an ECDSA recover for the specified message and calldata /// signature. /// /// The signature is encoded by tighyly packing the following struct: /// ``` /// struct EncodedSignature { /// bytes32 r; /// bytes32 s; /// uint8 v; /// } /// ``` /// /// @param message The signed message. /// @param encodedSignature The encoded signature. function ecdsaRecover(bytes32 message, bytes calldata encodedSignature) internal pure returns (address signer) { require( encodedSignature.length == ECDSA_SIGNATURE_LENGTH, "GPv2: malformed ecdsa signature" ); bytes32 r; bytes32 s; uint8 v; // NOTE: Use assembly to efficiently decode signature data. // solhint-disable-next-line no-inline-assembly assembly { // r = uint256(encodedSignature[0:32]) r := calldataload(encodedSignature.offset) // s = uint256(encodedSignature[32:64]) s := calldataload(add(encodedSignature.offset, 32)) // v = uint8(encodedSignature[64]) v := shr(248, calldataload(add(encodedSignature.offset, 64))) } signer = ecrecover(message, v, r, s); require(signer != address(0), "GPv2: invalid ecdsa signature"); } /// @dev Decodes signature bytes originating from an EIP-712-encoded /// signature. /// /// EIP-712 signs typed data. The specifications are described in the /// related EIP (<https://eips.ethereum.org/EIPS/eip-712>). /// /// EIP-712 signatures are encoded as standard ECDSA signatures as described /// in the corresponding decoding function [`ecdsaRecover`]. /// /// @param orderDigest The EIP-712 signing digest derived from the order /// parameters. /// @param encodedSignature Calldata pointing to tightly packed signature /// bytes. /// @return owner The address of the signer. function recoverEip712Signer( bytes32 orderDigest, bytes calldata encodedSignature ) internal pure returns (address owner) { owner = ecdsaRecover(orderDigest, encodedSignature); } /// @dev Decodes signature bytes originating from the output of the eth_sign /// RPC call. /// /// The specifications are described in the Ethereum documentation /// (<https://eth.wiki/json-rpc/API#eth_sign>). /// /// eth_sign signatures are encoded as standard ECDSA signatures as /// described in the corresponding decoding function /// [`ecdsaRecover`]. /// /// @param orderDigest The EIP-712 signing digest derived from the order /// parameters. /// @param encodedSignature Calldata pointing to tightly packed signature /// bytes. /// @return owner The address of the signer. function recoverEthsignSigner( bytes32 orderDigest, bytes calldata encodedSignature ) internal pure returns (address owner) { // The signed message is encoded as: // `"\x19Ethereum Signed Message:\n" || length || data`, where // the length is a constant (32 bytes) and the data is defined as: // `orderDigest`. bytes32 ethsignDigest = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", orderDigest ) ); owner = ecdsaRecover(ethsignDigest, encodedSignature); } /// @dev Verifies the input calldata as an EIP-1271 contract signature and /// returns the address of the signer. /// /// The encoded signature tightly packs the following struct: /// /// ``` /// struct EncodedEip1271Signature { /// address owner; /// bytes signature; /// } /// ``` /// /// This function enforces that the encoded data stores enough bytes to /// cover the full length of the decoded signature. /// /// @param encodedSignature The encoded EIP-1271 signature. /// @param orderDigest The EIP-712 signing digest derived from the order /// parameters. /// @return owner The address of the signer. function recoverEip1271Signer( bytes32 orderDigest, bytes calldata encodedSignature ) internal view returns (address owner) { // NOTE: Use assembly to read the verifier address from the encoded // signature bytes. // solhint-disable-next-line no-inline-assembly assembly { // owner = address(encodedSignature[0:20]) owner := shr(96, calldataload(encodedSignature.offset)) } // NOTE: Configure prettier to ignore the following line as it causes // a panic in the Solidity plugin. // prettier-ignore bytes calldata signature = encodedSignature[20:]; require( EIP1271Verifier(owner).isValidSignature(orderDigest, signature) == GPv2EIP1271.MAGICVALUE, "GPv2: invalid eip1271 signature" ); } /// @dev Verifies the order has been pre-signed. The signature is the /// address of the signer of the order. /// /// @param orderDigest The EIP-712 signing digest derived from the order /// parameters. /// @param encodedSignature The pre-sign signature reprenting the order UID. /// @param validTo The order expiry timestamp. /// @return owner The address of the signer. function recoverPreSigner( bytes32 orderDigest, bytes calldata encodedSignature, uint32 validTo ) internal view returns (address owner) { require(encodedSignature.length == 20, "GPv2: malformed presignature"); // NOTE: Use assembly to read the owner address from the encoded // signature bytes. // solhint-disable-next-line no-inline-assembly assembly { // owner = address(encodedSignature[0:20]) owner := shr(96, calldataload(encodedSignature.offset)) } bytes memory orderUid = new bytes(GPv2Order.UID_LENGTH); orderUid.packOrderUidParams(orderDigest, owner, validTo); require( preSignature[orderUid] == PRE_SIGNED, "GPv2: order not presigned" ); } }
54,760
147
// VaultFactory/Instantiates proxy vault contracts
contract VaultFactory is Guarded { event VaultCreated(address indexed instance, address indexed creator, bytes params); function createVault(address impl, bytes calldata params) external checkCaller returns (address) { address instance = Clones.clone(impl); // append msg.sender to set the root IVaultInitializable(instance).initialize(abi.encodePacked(params, abi.encode(msg.sender))); emit VaultCreated(instance, msg.sender, params); return instance; } }
contract VaultFactory is Guarded { event VaultCreated(address indexed instance, address indexed creator, bytes params); function createVault(address impl, bytes calldata params) external checkCaller returns (address) { address instance = Clones.clone(impl); // append msg.sender to set the root IVaultInitializable(instance).initialize(abi.encodePacked(params, abi.encode(msg.sender))); emit VaultCreated(instance, msg.sender, params); return instance; } }
61,240
350
// returns the pool token of the pool /
function poolToken(Token pool) external view returns (IPoolToken);
function poolToken(Token pool) external view returns (IPoolToken);
65,032
143
// from now
block.timestamp,
block.timestamp,
49,719
5
// check the given tokenId is in the tokenList and its owner is not null.
modifier tokenExist(uint256 _id) { require(_id >= 1 && _id <= WarriorList.length); require(tokenIndexToOwner[_id] != address(0)); _; }
modifier tokenExist(uint256 _id) { require(_id >= 1 && _id <= WarriorList.length); require(tokenIndexToOwner[_id] != address(0)); _; }
38,079
35
// transfers the input amount from the caller farming contract to the extension.amount amount of erc20 to transfer back or burn. /
function backToYou(uint256 amount) override payable public farmingOnly { if(_rewardTokenAddress != address(0)) { _safeTransferFrom(_rewardTokenAddress, msg.sender, address(this), amount); _safeApprove(_rewardTokenAddress, _getFunctionalityAddress(), amount); IMVDProxy(IDoubleProxy(_doubleProxy).proxy()).submit(FUNCTIONALITY_NAME, abi.encode(address(0), 0, false, _rewardTokenAddress, msg.sender, amount, _byMint)); } else { IMVDProxy(IDoubleProxy(_doubleProxy).proxy()).submit{value : amount}(FUNCTIONALITY_NAME, abi.encode(address(0), 0, false, _rewardTokenAddress, msg.sender, amount, _byMint)); } }
function backToYou(uint256 amount) override payable public farmingOnly { if(_rewardTokenAddress != address(0)) { _safeTransferFrom(_rewardTokenAddress, msg.sender, address(this), amount); _safeApprove(_rewardTokenAddress, _getFunctionalityAddress(), amount); IMVDProxy(IDoubleProxy(_doubleProxy).proxy()).submit(FUNCTIONALITY_NAME, abi.encode(address(0), 0, false, _rewardTokenAddress, msg.sender, amount, _byMint)); } else { IMVDProxy(IDoubleProxy(_doubleProxy).proxy()).submit{value : amount}(FUNCTIONALITY_NAME, abi.encode(address(0), 0, false, _rewardTokenAddress, msg.sender, amount, _byMint)); } }
16,167
31
// Records data of all the tokens Locked /
event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity );
event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity );
4,261
134
// Exit the gems from mkr Anyone is allowed to call this function /
function gemExit() external { for(uint i = 0; i < ilks.length; i++) { uint wad = VatLike(vat).gem(ilks[i], address(this)); GemJoinLike(gemJoins[i]).exit(address(this), wad); } if(_isWithdrawOpen()) gemExitCalled = true; }
function gemExit() external { for(uint i = 0; i < ilks.length; i++) { uint wad = VatLike(vat).gem(ilks[i], address(this)); GemJoinLike(gemJoins[i]).exit(address(this), wad); } if(_isWithdrawOpen()) gemExitCalled = true; }
20,206
346
// Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. * * _Available since v4.2._ */ abstract contract ERC20Votes is ERC20Permit, IERC5805 { struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; /** * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting). */ function clock() public view virtual override returns (uint48) { return SafeCast.toUint48(block.number); } /** * @dev Description of the clock */ // solhint-disable-next-line func-name-mixedcase function CLOCK_MODE() public view virtual override returns (string memory) { // Check that the clock was not modified require(clock() == block.number, "ERC20Votes: broken clock mode"); return "mode=blocknumber&from=default"; } /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual override returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view virtual override returns (uint256) { uint256 pos = _checkpoints[account].length; unchecked { return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } } /** * @dev Retrieve the number of votes for `account` at the end of `timepoint`. * * Requirements: * * - `timepoint` must be in the past */ function getPastVotes(address account, uint256 timepoint) public view virtual override returns (uint256) { require(timepoint < clock(), "ERC20Votes: future lookup"); return _checkpointsLookup(_checkpoints[account], timepoint); } /** * @dev Retrieve the `totalSupply` at the end of `timepoint`. Note, this value is the sum of all balances. * It is NOT the sum of all the delegated votes! * * Requirements: * * - `timepoint` must be in the past */ function getPastTotalSupply(uint256 timepoint) public view virtual override returns (uint256) { require(timepoint < clock(), "ERC20Votes: future lookup"); return _checkpointsLookup(_totalSupplyCheckpoints, timepoint); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 timepoint) private view returns (uint256) { // We run a binary search to look for the last (most recent) checkpoint taken before (or at) `timepoint`. // // Initially we check if the block is recent to narrow the search range. // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `timepoint`, we look in [low, mid) // - If the middle checkpoint is before or equal to `timepoint`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `timepoint`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `timepoint`, but it works out // the same. uint256 length = ckpts.length; uint256 low = 0; uint256 high = length; if (length > 5) { uint256 mid = length - Math.sqrt(length); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; } else { low = mid + 1; } } while (low < high) { uint256 mid = Math.average(low, high); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; } else { low = mid + 1; } } unchecked { return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes; } } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual override { _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); _delegate(signer, delegatee); } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } /** * @dev Move voting power when tokens are transferred. * * Emits a {IVotes-DelegateVotesChanged} event. */ function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower(address src, address dst, uint256 amount) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; unchecked { Checkpoint memory oldCkpt = pos == 0 ? Checkpoint(0, 0) : _unsafeAccess(ckpts, pos - 1); oldWeight = oldCkpt.votes; newWeight = op(oldWeight, delta); if (pos > 0 && oldCkpt.fromBlock == clock()) { _unsafeAccess(ckpts, pos - 1).votes = SafeCast.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(clock()), votes: SafeCast.toUint224(newWeight)})); } } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } /** * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds. */ function _unsafeAccess(Checkpoint[] storage ckpts, uint256 pos) private pure returns (Checkpoint storage result) { assembly { mstore(0, ckpts.slot) result.slot := add(keccak256(0, 0x20), pos) } } }
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. * * _Available since v4.2._ */ abstract contract ERC20Votes is ERC20Permit, IERC5805 { struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; /** * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting). */ function clock() public view virtual override returns (uint48) { return SafeCast.toUint48(block.number); } /** * @dev Description of the clock */ // solhint-disable-next-line func-name-mixedcase function CLOCK_MODE() public view virtual override returns (string memory) { // Check that the clock was not modified require(clock() == block.number, "ERC20Votes: broken clock mode"); return "mode=blocknumber&from=default"; } /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } /** * @dev Get the address `account` is currently delegating to. */ function delegates(address account) public view virtual override returns (address) { return _delegates[account]; } /** * @dev Gets the current votes balance for `account` */ function getVotes(address account) public view virtual override returns (uint256) { uint256 pos = _checkpoints[account].length; unchecked { return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } } /** * @dev Retrieve the number of votes for `account` at the end of `timepoint`. * * Requirements: * * - `timepoint` must be in the past */ function getPastVotes(address account, uint256 timepoint) public view virtual override returns (uint256) { require(timepoint < clock(), "ERC20Votes: future lookup"); return _checkpointsLookup(_checkpoints[account], timepoint); } /** * @dev Retrieve the `totalSupply` at the end of `timepoint`. Note, this value is the sum of all balances. * It is NOT the sum of all the delegated votes! * * Requirements: * * - `timepoint` must be in the past */ function getPastTotalSupply(uint256 timepoint) public view virtual override returns (uint256) { require(timepoint < clock(), "ERC20Votes: future lookup"); return _checkpointsLookup(_totalSupplyCheckpoints, timepoint); } /** * @dev Lookup a value in a list of (sorted) checkpoints. */ function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 timepoint) private view returns (uint256) { // We run a binary search to look for the last (most recent) checkpoint taken before (or at) `timepoint`. // // Initially we check if the block is recent to narrow the search range. // During the loop, the index of the wanted checkpoint remains in the range [low-1, high). // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. // - If the middle checkpoint is after `timepoint`, we look in [low, mid) // - If the middle checkpoint is before or equal to `timepoint`, we look in [mid+1, high) // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not // out of bounds (in which case we're looking too far in the past and the result is 0). // Note that if the latest checkpoint available is exactly for `timepoint`, we end up with an index that is // past the end of the array, so we technically don't find a checkpoint after `timepoint`, but it works out // the same. uint256 length = ckpts.length; uint256 low = 0; uint256 high = length; if (length > 5) { uint256 mid = length - Math.sqrt(length); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; } else { low = mid + 1; } } while (low < high) { uint256 mid = Math.average(low, high); if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) { high = mid; } else { low = mid + 1; } } unchecked { return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes; } } /** * @dev Delegate votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual override { _delegate(_msgSender(), delegatee); } /** * @dev Delegates votes from signer to `delegatee` */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); _delegate(signer, delegatee); } /** * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1). */ function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } /** * @dev Snapshots the totalSupply after it has been increased. */ function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } /** * @dev Snapshots the totalSupply after it has been decreased. */ function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } /** * @dev Move voting power when tokens are transferred. * * Emits a {IVotes-DelegateVotesChanged} event. */ function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } /** * @dev Change delegation for `delegator` to `delegatee`. * * Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}. */ function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower(address src, address dst, uint256 amount) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; unchecked { Checkpoint memory oldCkpt = pos == 0 ? Checkpoint(0, 0) : _unsafeAccess(ckpts, pos - 1); oldWeight = oldCkpt.votes; newWeight = op(oldWeight, delta); if (pos > 0 && oldCkpt.fromBlock == clock()) { _unsafeAccess(ckpts, pos - 1).votes = SafeCast.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(clock()), votes: SafeCast.toUint224(newWeight)})); } } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } /** * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds. */ function _unsafeAccess(Checkpoint[] storage ckpts, uint256 pos) private pure returns (Checkpoint storage result) { assembly { mstore(0, ckpts.slot) result.slot := add(keccak256(0, 0x20), pos) } } }
12,499
4
// cost per token (cents 10^18) amounts for each tier.
uint256[] costPerToken = [ 3.85E21, 6.1E21, 4.15E21, 5.92E21, 9.47E21, 1.1E22, 1.123E22, 1.115E22, 1.135E22,
uint256[] costPerToken = [ 3.85E21, 6.1E21, 4.15E21, 5.92E21, 9.47E21, 1.1E22, 1.123E22, 1.115E22, 1.135E22,
81,372
75
// Throw these in here as well to save gas.
to != address(0) && tokenId == _tokenId && from == _owner && (msg.sender == _owner || msg.sender ==_approvedTransferer || _approveForAllAddresses[msg.sender]) , "Not authorized");
to != address(0) && tokenId == _tokenId && from == _owner && (msg.sender == _owner || msg.sender ==_approvedTransferer || _approveForAllAddresses[msg.sender]) , "Not authorized");
58,428
25
// Initialize storage variable referencing signed zone properties.
SignedZoneProperties storage signedZoneProperties = _signedZones[ signedZone ];
SignedZoneProperties storage signedZoneProperties = _signedZones[ signedZone ];
13,705
24
// the game object
struct Game { address player; GameState state; uint id; BetDirection direction; uint bet; uint8 firstRoll; uint8 finalRoll; uint winnings; }
struct Game { address player; GameState state; uint id; BetDirection direction; uint bet; uint8 firstRoll; uint8 finalRoll; uint winnings; }
7,014
281
// Returns the proper tokenURI only after the startingIndex is finalized./
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(startingIndex != 0 && block.timestamp >= REVEAL_TIMESTAMP) { string memory base = baseURI(); string memory tokenURIWithOffset = uint2str(((tokenId + startingIndex) % MAX_CRYPTO_SQUATCH_SUPPLY)); return string(abi.encodePacked(base, tokenURIWithOffset)); } else { return prerevealURI; } }
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(startingIndex != 0 && block.timestamp >= REVEAL_TIMESTAMP) { string memory base = baseURI(); string memory tokenURIWithOffset = uint2str(((tokenId + startingIndex) % MAX_CRYPTO_SQUATCH_SUPPLY)); return string(abi.encodePacked(base, tokenURIWithOffset)); } else { return prerevealURI; } }
37,367
37
// Get data info by index index index of dataArray /
function getDataByIndex(uint index) public view returns (string link, string encryptionType, string hashValue) { require(isValid == true, "contract invaild"); require(index >= 0, "Param index smaller than 0"); require(index < dataNum, "Param index not smaller than dataNum"); link = dataArray[index].link; encryptionType = dataArray[index].encryptionType; hashValue = dataArray[index].hashValue; }
function getDataByIndex(uint index) public view returns (string link, string encryptionType, string hashValue) { require(isValid == true, "contract invaild"); require(index >= 0, "Param index smaller than 0"); require(index < dataNum, "Param index not smaller than dataNum"); link = dataArray[index].link; encryptionType = dataArray[index].encryptionType; hashValue = dataArray[index].hashValue; }
31,063
6
// add a comment
uint id = comments.push(Comment(0, _name, _comment, _head_img, now)) - 1;
uint id = comments.push(Comment(0, _name, _comment, _head_img, now)) - 1;
12,902
220
// issue new network tokens to the system
mintNetworkTokens(address(this), poolAnchor, newNetworkLiquidityAmount);
mintNetworkTokens(address(this), poolAnchor, newNetworkLiquidityAmount);
33,889
49
// Receives a donation in Ether/
function receiveETH(address _beneficiary) internal { require(msg.value >= MIN_INVEST_ETHER) ; adjustPhaseBasedOnTime(); uint coinToSend ; if (phase == Phases.MainIco){ Backer storage mainBacker = mainBackers[_beneficiary]; require(mainBacker.weiReceived.add(msg.value) <= maximumCoinsPerAddress); coinToSend = msg.value.mul(MAIN_COIN_PER_ETHER_ICO).div(1 ether); require(coinToSend.add(mainCoinSentToEther) <= MAIN_MAX_CAP) ; mainBacker.coinSent = mainBacker.coinSent.add(coinToSend); mainBacker.weiReceived = mainBacker.weiReceived.add(msg.value); mainBacker.coinReadyToSend = mainBacker.coinReadyToSend.add(coinToSend); mainReadyToSendAddress.push(_beneficiary); // Update the total wei collected during the crowdfunding mainEtherReceived = mainEtherReceived.add(msg.value); mainCoinSentToEther = mainCoinSentToEther.add(coinToSend); // Send events LogReceivedETH(_beneficiary, mainEtherReceived); } }
function receiveETH(address _beneficiary) internal { require(msg.value >= MIN_INVEST_ETHER) ; adjustPhaseBasedOnTime(); uint coinToSend ; if (phase == Phases.MainIco){ Backer storage mainBacker = mainBackers[_beneficiary]; require(mainBacker.weiReceived.add(msg.value) <= maximumCoinsPerAddress); coinToSend = msg.value.mul(MAIN_COIN_PER_ETHER_ICO).div(1 ether); require(coinToSend.add(mainCoinSentToEther) <= MAIN_MAX_CAP) ; mainBacker.coinSent = mainBacker.coinSent.add(coinToSend); mainBacker.weiReceived = mainBacker.weiReceived.add(msg.value); mainBacker.coinReadyToSend = mainBacker.coinReadyToSend.add(coinToSend); mainReadyToSendAddress.push(_beneficiary); // Update the total wei collected during the crowdfunding mainEtherReceived = mainEtherReceived.add(msg.value); mainCoinSentToEther = mainCoinSentToEther.add(coinToSend); // Send events LogReceivedETH(_beneficiary, mainEtherReceived); } }
20,704
33
// uint endTime = block.timestamp + _endTime;
PriceTier[] memory priceTiers = _prices; Game storage game = games[nextGameId]; for(uint i = 0; i < priceTiers.length; i++) { require(priceTiers[i].number > 0, "All price tiers need an entry number" ); PriceTier memory p = PriceTier({ number: _prices[i].number, price: _prices[i].price });
PriceTier[] memory priceTiers = _prices; Game storage game = games[nextGameId]; for(uint i = 0; i < priceTiers.length; i++) { require(priceTiers[i].number > 0, "All price tiers need an entry number" ); PriceTier memory p = PriceTier({ number: _prices[i].number, price: _prices[i].price });
18,390
23
// Transfer token for a specified address /
function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
42,001
19
// Query balance of individual assetData
uint256 totalBalance = getBalance(ownerAddress, nestedAssetData[i]);
uint256 totalBalance = getBalance(ownerAddress, nestedAssetData[i]);
521
128
// }
}
}
1,206
84
// Update the index of positions for the asset
_indexOfAsset[assetId] = 0; _indexOfAsset[lastAssetId] = assetIndex; _count = _count.sub(1);
_indexOfAsset[assetId] = 0; _indexOfAsset[lastAssetId] = assetIndex; _count = _count.sub(1);
11,854
70
// IMMUTABLES & CONSTANTS / Fees are 6-decimal places. For example: 20106 = 20%
uint256 internal constant FEE_MULTIPLIER = 10**6;
uint256 internal constant FEE_MULTIPLIER = 10**6;
14,426
24
// now get the non snx backed debt.
(uint nonSnxDebt, bool ratesInvalid) = totalLong();
(uint nonSnxDebt, bool ratesInvalid) = totalLong();
40,367
152
// Whitelist Addresses
mapping(address => bool) public whitelistedAddressesList;
mapping(address => bool) public whitelistedAddressesList;
14,617
29
// Arbitrable Arbitrable abstract contract. When developing arbitrable contracts, we need to: -Define the action taken when a ruling is received by the contract. We should do so in executeRuling. -Allow dispute creation. For this a function must: -Call arbitrator.createDispute.value(_fee)(_choices,_extraData); -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions); /
contract Arbitrable is IArbitrable { Arbitrator public arbitrator; bytes public arbitratorExtraData; // Extra data to require particular dispute and appeal behaviour. modifier onlyArbitrator {require(msg.sender == address(arbitrator), "Can only be called by the arbitrator."); _;} /** @dev Constructor. Choose the arbitrator. * @param _arbitrator The arbitrator of the contract. * @param _arbitratorExtraData Extra data for the arbitrator. */ constructor(Arbitrator _arbitrator, bytes _arbitratorExtraData) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public onlyArbitrator { emit Ruling(Arbitrator(msg.sender),_disputeID,_ruling); executeRuling(_disputeID,_ruling); } /** @dev Execute a ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function executeRuling(uint _disputeID, uint _ruling) internal; }
contract Arbitrable is IArbitrable { Arbitrator public arbitrator; bytes public arbitratorExtraData; // Extra data to require particular dispute and appeal behaviour. modifier onlyArbitrator {require(msg.sender == address(arbitrator), "Can only be called by the arbitrator."); _;} /** @dev Constructor. Choose the arbitrator. * @param _arbitrator The arbitrator of the contract. * @param _arbitratorExtraData Extra data for the arbitrator. */ constructor(Arbitrator _arbitrator, bytes _arbitratorExtraData) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } /** @dev Give a ruling for a dispute. Must be called by the arbitrator. * The purpose of this function is to ensure that the address calling it has the right to rule on the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function rule(uint _disputeID, uint _ruling) public onlyArbitrator { emit Ruling(Arbitrator(msg.sender),_disputeID,_ruling); executeRuling(_disputeID,_ruling); } /** @dev Execute a ruling of a dispute. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision". */ function executeRuling(uint _disputeID, uint _ruling) internal; }
40,634
40
// Check signature (this contains a potential call -> EIP-1271)
checkSignature(delegate, signature, transferHashData, safe);
checkSignature(delegate, signature, transferHashData, safe);
30,748
24
// Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the /// transaction being reverted. /// Note: the contract address is always the message sender. /// @param _operator The address which called `safeTransferFrom` function /// @param _from The address which previously owned the token /// @param _tokenId The NFT identifier which is being transferred /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4); }
interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the /// transaction being reverted. /// Note: the contract address is always the message sender. /// @param _operator The address which called `safeTransferFrom` function /// @param _from The address which previously owned the token /// @param _tokenId The NFT identifier which is being transferred /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4); }
249
11
// Here we have to keep track of a initialized balanceOf to prevent any view issues
mapping(address => bool) public _balanceOfInitialized;
mapping(address => bool) public _balanceOfInitialized;
28,908
8
// The latest root that has been signed by the Updater
bytes32 public committedRoot;
bytes32 public committedRoot;
19,944