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
// Allows the vault contract to verify an account for a payout./
function verifyPayout(address _user) external view returns(bool);
function verifyPayout(address _user) external view returns(bool);
44,207
57
// we only need to set the cid to an empty string if we are replacing an offchain asset an onchain asset will already have an empty cid
projects[_projectId].externalAssetDependencies[_index].cid = "";
projects[_projectId].externalAssetDependencies[_index].cid = "";
13,018
1
// SPDX-License-Identifier: LGPL-3.0-or-later // BalanceSheetStorage Mainframe /
abstract contract BalanceSheetStorage { struct Vault { uint256 debt; uint256 freeCollateral; uint256 lockedCollateral; bool isOpen; } /** * @notice The unique Fintroller associated with this contract. */ FintrollerInterface public fintroller; /** * @dev One vault for each fyToken for each account. */ mapping(address => mapping(address => Vault)) internal vaults; /** * @notice Indicator that this is a BalanceSheet contract, for inspection. */ bool public constant isBalanceSheet = true; }
abstract contract BalanceSheetStorage { struct Vault { uint256 debt; uint256 freeCollateral; uint256 lockedCollateral; bool isOpen; } /** * @notice The unique Fintroller associated with this contract. */ FintrollerInterface public fintroller; /** * @dev One vault for each fyToken for each account. */ mapping(address => mapping(address => Vault)) internal vaults; /** * @notice Indicator that this is a BalanceSheet contract, for inspection. */ bool public constant isBalanceSheet = true; }
8,881
33
// https:explorer.optimism.io/address/0x81DDfAc111913d3d5218DEA999216323B7CD6356
ProxyERC20 public constant proxysmatic_i = ProxyERC20(0x81DDfAc111913d3d5218DEA999216323B7CD6356);
ProxyERC20 public constant proxysmatic_i = ProxyERC20(0x81DDfAc111913d3d5218DEA999216323B7CD6356);
22,554
57
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct OffchainData { address wrapper; address exchangeAddr; address allowanceTarget; uint256 price; uint256 protocolFee; bytes callData; }
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct OffchainData { address wrapper; address exchangeAddr; address allowanceTarget; uint256 price; uint256 protocolFee; bytes callData; }
36,290
116
// Remove time lock, only locker can removeaccount The address want to remove time lockindex Time lock index/
function _removeTimeLock(address account, uint8 index) internal { require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); uint len = _timeLocks[account].length; if (len - 1 != index) { // if it is not last item, swap it _timeLocks[account][index] = _timeLocks[account][len - 1]; } _timeLocks[account].pop(); emit TimeUnlocked(account); }
function _removeTimeLock(address account, uint8 index) internal { require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); uint len = _timeLocks[account].length; if (len - 1 != index) { // if it is not last item, swap it _timeLocks[account][index] = _timeLocks[account][len - 1]; } _timeLocks[account].pop(); emit TimeUnlocked(account); }
4,355
35
// ------------------------------------------------------------------------ Private function to register payouts ------------------------------------------------------------------------
function _addPayout(uint256 tokens) private{ // divide the funds among the currently staked tokens // scale the deposit and add the previous remainder uint256 available = (tokens.mul(scaling)).add(scaledRemainder); uint256 dividendPerToken = available.div(totalStakes); scaledRemainder = available.mod(totalStakes); totalDividends = totalDividends.add(dividendPerToken); payouts[round] = payouts[round - 1].add(dividendPerToken); emit PAYOUT(round, tokens, msg.sender); round++; }
function _addPayout(uint256 tokens) private{ // divide the funds among the currently staked tokens // scale the deposit and add the previous remainder uint256 available = (tokens.mul(scaling)).add(scaledRemainder); uint256 dividendPerToken = available.div(totalStakes); scaledRemainder = available.mod(totalStakes); totalDividends = totalDividends.add(dividendPerToken); payouts[round] = payouts[round - 1].add(dividendPerToken); emit PAYOUT(round, tokens, msg.sender); round++; }
49,287
79
// Change TokenPrice_rate is TokenPrice /
function changeRate(uint256 _rate) public onlyOwner { require(_rate != 0); rate = _rate; }
function changeRate(uint256 _rate) public onlyOwner { require(_rate != 0); rate = _rate; }
32,150
55
// This percentage goes for crowdfunding. /
uint public crowdfundingFactor = 20;
uint public crowdfundingFactor = 20;
48,531
5
// How Many NFT's available in Total
uint public MaxMintsAvailable = 1000; //tokenID should be <= TotalSupply
uint public MaxMintsAvailable = 1000; //tokenID should be <= TotalSupply
3,944
6
// ---------------------------------------------------------------------------- ERC Token Standard 20 Interface https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md ----------------------------------------------------------------------------
contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); }
contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); }
1,787
5
// Adjust this to change the test code's initial balance
uint public initialBalance = 1000000000 wei; Participant judge; Participant seller; Participant winner; Participant other;
uint public initialBalance = 1000000000 wei; Participant judge; Participant seller; Participant winner; Participant other;
28,531
6
// Register new symbol in the registrysymbol SymbolissuerName Name of the issuer/
function registerSymbol(bytes memory symbol, bytes memory issuerName) public verifySymbol(symbol) verifyPermission(msg.sig, msg.sender)
function registerSymbol(bytes memory symbol, bytes memory issuerName) public verifySymbol(symbol) verifyPermission(msg.sig, msg.sender)
9,876
89
// get TOKEN to team wallet
function seizeTOKEN( address tokenaddr ) external onlyGovernance { Erc20Token _token = Erc20Token(tokenaddr); uint256 _currentBalance = _token.balanceOf(address(this)); _token.transfer(_teamWallet, _currentBalance); }
function seizeTOKEN( address tokenaddr ) external onlyGovernance { Erc20Token _token = Erc20Token(tokenaddr); uint256 _currentBalance = _token.balanceOf(address(this)); _token.transfer(_teamWallet, _currentBalance); }
39,540
43
// Converts a uint to int and checks if positive/_x Number to be converted
function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); }
function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); }
33,455
12
// require(balances[_from] >= _value && allowed[_from][msg.sender] >=_value && balances[_to] + _value > balances[_to]);
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value;//接收账户增加token数量_value balances[_from] -= _value; //支出账户_from减去token数量_value allowed[_from][msg.sender] -= _value;//消息发送者可以从账户_from中转出的数量减少_value Transfer(_from, _to, _value);//触发转币交易事件 return true;
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value;//接收账户增加token数量_value balances[_from] -= _value; //支出账户_from减去token数量_value allowed[_from][msg.sender] -= _value;//消息发送者可以从账户_from中转出的数量减少_value Transfer(_from, _to, _value);//触发转币交易事件 return true;
1,339
6
// reset counters to 0
_totalSupply = 0; numHolders = 0; totalPremiums = 0;
_totalSupply = 0; numHolders = 0; totalPremiums = 0;
20,168
6
// amount to be migrated to wallet above. 0 means all funds
uint112 amount;
uint112 amount;
37,544
2
// Returned when an attempt is made to place a bid that exceeds the max configurable amount
error MaxBidExceeded();
error MaxBidExceeded();
14,645
50
// Bird's BErc20 Storage/
contract BErc20Storage { /** * @notice Underlying asset for this BToken */ address public underlying; }
contract BErc20Storage { /** * @notice Underlying asset for this BToken */ address public underlying; }
20,147
69
// Checks limit if minRatio is bigger than max/_minRatio Minimum ratio, bellow which repay can be triggered/_maxRatio Maximum ratio, over which boost can be triggered/ return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; }
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; }
18,004
112
// mid will always be strictly less than high and it rounds down
if (item.history[mid].fromBlock <= blockNumber) { low = mid; } else {
if (item.history[mid].fromBlock <= blockNumber) { low = mid; } else {
38,083
5
// Only owner can enable it.TODO: check if caller is owner. /
function enable() payable public { require (msg.value >= 100000); _storage.setBool(KEY_ENABLED, true); }
function enable() payable public { require (msg.value >= 100000); _storage.setBool(KEY_ENABLED, true); }
35,899
35
// Track result balance
uint256 _endBalance = IERC20(_fromToken).balanceOf(address(this));
uint256 _endBalance = IERC20(_fromToken).balanceOf(address(this));
65,203
27
// Replace or add any additional variables that you want to be available to the receiver function
msg.sender, loanAmount, punkIndex )
msg.sender, loanAmount, punkIndex )
11,695
267
// contractors created to work for Pass Dao
contractor[] public contractors; event NewPassContractor(address indexed Creator, address indexed Recipient, PassProject indexed Project, PassContractor Contractor);
contractor[] public contractors; event NewPassContractor(address indexed Creator, address indexed Recipient, PassProject indexed Project, PassContractor Contractor);
7,564
28
// Upgrades a root wrapped domain by calling the wrap function of the upgradeContractand burning the token of this contract Can be called by the owner of the name in this contract label Label as a string of the root name to upgrade wrappedOwner The owner of the wrapped name /
function upgrade( string calldata label, address wrappedOwner, address resolver
function upgrade( string calldata label, address wrappedOwner, address resolver
38,703
51
// Implementation of the TeleportCustody contract. There are two priviledged roles for the contract: "owner" and "admin". Owner: Has the ultimate control of the contract and the funds stored inside the contract. Including:1) "freeze" and "unfreeze" the contract: when the TeleportCustody is frozen, all deposits and withdrawals with the TeleportCustody is disabled. Thisshould only happen when a major security risk is spotted or if admin access is comprimised.2) assign "admins": owner has the authority to grant "unlock" permission to "admins" and set proper "unlock limit" for each "admin". Admin: Has the authority to "unlock" specific amount to tokens to receivers. /
contract TeleportCustody is TeleportAdmin { // USDC // ERC20 internal _tokenContract = ERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDT TetherToken internal _tokenContract = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); // Records that an unlock transaction has been executed mapping(bytes32 => bool) internal _unlocked; // Emmitted when user locks token and initiates teleport event Locked(uint256 amount, bytes8 indexed flowAddress, address indexed ethereumAddress); // Emmitted when teleport completes and token gets unlocked event Unlocked(uint256 amount, address indexed ethereumAddress, bytes32 indexed flowHash); /** * @dev User locks token and initiates teleport request. */ function lock(uint256 amount, bytes8 flowAddress) public notFrozen { address sender = _msgSender(); // NOTE: Return value should be checked. However, Tether does not have return value. _tokenContract.transferFrom(sender, address(this), amount); emit Locked(amount, flowAddress, sender); } // Admin methods /** * @dev TeleportAdmin unlocks token upon receiving teleport request from Flow. */ function unlock(uint256 amount, address ethereumAddress, bytes32 flowHash) public notFrozen consumeAuthorization(amount) { _unlock(amount, ethereumAddress, flowHash); } // Owner methods /** * @dev Owner unlocks token upon receiving teleport request from Flow. * There is no unlock limit for owner. */ function unlockByOwner(uint256 amount, address ethereumAddress, bytes32 flowHash) public notFrozen onlyOwner { _unlock(amount, ethereumAddress, flowHash); } // Internal methods /** * @dev Internal function for processing unlock requests. * * There is no way TeleportCustody can check the validity of the target address * beforehand so user and admin should always make sure the provided information * is correct. */ function _unlock(uint256 amount, address ethereumAddress, bytes32 flowHash) internal { require(ethereumAddress != address(0), "TeleportCustody: ethereumAddress is the zero address"); require(!_unlocked[flowHash], "TeleportCustody: same unlock hash has been executed"); _unlocked[flowHash] = true; // NOTE: Return value should be checked. However, Tether does not have return value. _tokenContract.transfer(ethereumAddress, amount); emit Unlocked(amount, ethereumAddress, flowHash); } }
contract TeleportCustody is TeleportAdmin { // USDC // ERC20 internal _tokenContract = ERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDT TetherToken internal _tokenContract = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7); // Records that an unlock transaction has been executed mapping(bytes32 => bool) internal _unlocked; // Emmitted when user locks token and initiates teleport event Locked(uint256 amount, bytes8 indexed flowAddress, address indexed ethereumAddress); // Emmitted when teleport completes and token gets unlocked event Unlocked(uint256 amount, address indexed ethereumAddress, bytes32 indexed flowHash); /** * @dev User locks token and initiates teleport request. */ function lock(uint256 amount, bytes8 flowAddress) public notFrozen { address sender = _msgSender(); // NOTE: Return value should be checked. However, Tether does not have return value. _tokenContract.transferFrom(sender, address(this), amount); emit Locked(amount, flowAddress, sender); } // Admin methods /** * @dev TeleportAdmin unlocks token upon receiving teleport request from Flow. */ function unlock(uint256 amount, address ethereumAddress, bytes32 flowHash) public notFrozen consumeAuthorization(amount) { _unlock(amount, ethereumAddress, flowHash); } // Owner methods /** * @dev Owner unlocks token upon receiving teleport request from Flow. * There is no unlock limit for owner. */ function unlockByOwner(uint256 amount, address ethereumAddress, bytes32 flowHash) public notFrozen onlyOwner { _unlock(amount, ethereumAddress, flowHash); } // Internal methods /** * @dev Internal function for processing unlock requests. * * There is no way TeleportCustody can check the validity of the target address * beforehand so user and admin should always make sure the provided information * is correct. */ function _unlock(uint256 amount, address ethereumAddress, bytes32 flowHash) internal { require(ethereumAddress != address(0), "TeleportCustody: ethereumAddress is the zero address"); require(!_unlocked[flowHash], "TeleportCustody: same unlock hash has been executed"); _unlocked[flowHash] = true; // NOTE: Return value should be checked. However, Tether does not have return value. _tokenContract.transfer(ethereumAddress, amount); emit Unlocked(amount, ethereumAddress, flowHash); } }
32,950
45
// delete the user and update stake
totalStakes = totalStakes.sub(_stake.amount); // update stake totalNumberOfStakers = totalNumberOfStakers.sub(1); delete addressToStakeMap[_msgSender()];
totalStakes = totalStakes.sub(_stake.amount); // update stake totalNumberOfStakers = totalNumberOfStakers.sub(1); delete addressToStakeMap[_msgSender()];
41,608
35
// passthrough for direct testing
function approveDigest(bytes32 _digest) public { return self.approveDigest(_digest); }
function approveDigest(bytes32 _digest) public { return self.approveDigest(_digest); }
50,091
140
// During the ICO phase - 100% refundable
balances[_beneficiary] += acceptedAmount;
balances[_beneficiary] += acceptedAmount;
32,896
1
// account the account to incentivize/incentive the associated incentive contract/only UAD manager can set Incentive contract
function setIncentiveContract(address account, address incentive) external { require( ERC20Ubiquity.manager.hasRole( ERC20Ubiquity.manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender ), "Dollar: must have admin role" ); incentiveContract[account] = incentive;
function setIncentiveContract(address account, address incentive) external { require( ERC20Ubiquity.manager.hasRole( ERC20Ubiquity.manager.UBQ_TOKEN_MANAGER_ROLE(), msg.sender ), "Dollar: must have admin role" ); incentiveContract[account] = incentive;
53,509
221
// 将资金转移到合约地址
payable(addressOfPayment).transfer(msg.value);
payable(addressOfPayment).transfer(msg.value);
35,432
1
// risk param bounds
function PARAMS_MIN(uint256 idx) external view returns (uint256); function PARAMS_MAX(uint256 idx) external view returns (uint256);
function PARAMS_MIN(uint256 idx) external view returns (uint256); function PARAMS_MAX(uint256 idx) external view returns (uint256);
38,452
74
// x^y = 2^{log_2{x}y}/ For $0 \leq x \lt 1$, since the unsigned {log2} is undefined, an equivalent formula is used:/ i = \frac{1}{x}/ w = 2^{log_2{i}y}/ x^y = \frac{1}{w}/ - Refer to the notes in {log2} and {mul}./ - Refer to the requirements in {exp2}, {log2}, and {mul}.
uint256 xUint = x.unwrap(); uint256 yUint = y.unwrap();
uint256 xUint = x.unwrap(); uint256 yUint = y.unwrap();
27,697
48
// Case 1: Token owner is this contract and token.
while (rootOwnerAddress == address(this)) { (rootOwnerAddress, _childTokenId) = _ownerOfChild( rootOwnerAddress, _childTokenId ); }
while (rootOwnerAddress == address(this)) { (rootOwnerAddress, _childTokenId) = _ownerOfChild( rootOwnerAddress, _childTokenId ); }
21,370
22
// Quarterly bonus (5%)
usersFinance.makePayment(_client, qpWallet, basePriceCent * 5 / 100, PAY_CODE_QUART_PAR); curPriceCent -= basePriceCent * 5 / 100; curPriceCent = partnerScheme(_client, mentor, curPriceCent);
usersFinance.makePayment(_client, qpWallet, basePriceCent * 5 / 100, PAY_CODE_QUART_PAR); curPriceCent -= basePriceCent * 5 / 100; curPriceCent = partnerScheme(_client, mentor, curPriceCent);
3,114
4
// Returns exact gateway router address for token/_token Sending token address on L1/ return Gateway router address for sending token
function getGateway(address _token) external view returns (address);
function getGateway(address _token) external view returns (address);
22,892
208
// Rollup Config
uint256 public confirmPeriodBlocks; uint256 public extraChallengeTimeBlocks; uint256 public arbGasSpeedLimitPerBlock; uint256 public baseStake;
uint256 public confirmPeriodBlocks; uint256 public extraChallengeTimeBlocks; uint256 public arbGasSpeedLimitPerBlock; uint256 public baseStake;
35,831
60
// check battle & trade contract
EtheremonBattle battle = EtheremonBattle(battleContract); EtheremonTradeInterface trade = EtheremonTradeInterface(tradeContract); return (!battle.isOnBattle(obj.monsterId) && !trade.isOnTrading(obj.monsterId));
EtheremonBattle battle = EtheremonBattle(battleContract); EtheremonTradeInterface trade = EtheremonTradeInterface(tradeContract); return (!battle.isOnBattle(obj.monsterId) && !trade.isOnTrading(obj.monsterId));
29,427
73
// Allows arbitrator to accept a seller _arbitrator address of a licensed arbitrator /
function requestArbitrator(address _arbitrator) public { require(isLicenseOwner(_arbitrator), "Arbitrator should have a valid license"); require(!arbitratorlicenseDetails[_arbitrator].acceptAny, "Arbitrator already accepts all cases"); bytes32 _id = keccak256(abi.encodePacked(_arbitrator, msg.sender)); RequestStatus _status = requests[_id].status; require(_status != RequestStatus.AWAIT && _status != RequestStatus.ACCEPTED, "Invalid request status"); if(_status == RequestStatus.REJECTED || _status == RequestStatus.CLOSED){ require(requests[_id].date + 3 days < block.timestamp, "Must wait 3 days before requesting the arbitrator again"); } requests[_id] = Request({ seller: msg.sender, arbitrator: _arbitrator, status: RequestStatus.AWAIT, date: block.timestamp }); emit ArbitratorRequested(_id, msg.sender, _arbitrator); }
function requestArbitrator(address _arbitrator) public { require(isLicenseOwner(_arbitrator), "Arbitrator should have a valid license"); require(!arbitratorlicenseDetails[_arbitrator].acceptAny, "Arbitrator already accepts all cases"); bytes32 _id = keccak256(abi.encodePacked(_arbitrator, msg.sender)); RequestStatus _status = requests[_id].status; require(_status != RequestStatus.AWAIT && _status != RequestStatus.ACCEPTED, "Invalid request status"); if(_status == RequestStatus.REJECTED || _status == RequestStatus.CLOSED){ require(requests[_id].date + 3 days < block.timestamp, "Must wait 3 days before requesting the arbitrator again"); } requests[_id] = Request({ seller: msg.sender, arbitrator: _arbitrator, status: RequestStatus.AWAIT, date: block.timestamp }); emit ArbitratorRequested(_id, msg.sender, _arbitrator); }
26,078
32
// Whitelisting list
mapping(address => bool) public whiteListed;
mapping(address => bool) public whiteListed;
199
126
// Restore tax, liquidity, burn and funding fees
_taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _fundingFee = _previousFundingFee; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) restoreAllFee();
_taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _fundingFee = _previousFundingFee; if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) restoreAllFee();
16,450
108
// Default assumes totalSupply can't be over max (2^256 - 1).If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.Replace the if with this one instead.require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]);
require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true;
require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true;
12,756
2
// Struct to track token info/
struct tokenInfo { uint256 tokenId; address owner; uint256 status; uint256 timeStaked; }
struct tokenInfo { uint256 tokenId; address owner; uint256 status; uint256 timeStaked; }
14,505
35
// The token being distributed
address public immutable override token;
address public immutable override token;
3,580
21
// convenience function for fetching the current total shares of `user` in this strategy, byquerying the `delegationManager` contract /
function shares(address user) public view virtual returns (uint256) { return IDelegationManager(delegationManager).investorDelegationShares(user, IDelegationShare(address(this))); }
function shares(address user) public view virtual returns (uint256) { return IDelegationManager(delegationManager).investorDelegationShares(user, IDelegationShare(address(this))); }
3,986
155
// Require merkle proof with `to` and `maxAmount` to be successfully verified
require(MerkleProof.verify(proof, merkleRoot, keccak256(abi.encodePacked(to, maxAmount))), "!PROOF");
require(MerkleProof.verify(proof, merkleRoot, keccak256(abi.encodePacked(to, maxAmount))), "!PROOF");
33,764
15
// Transfers the tokens to the ScheduledTokenLock contract, locking the tokens over the specified schedule. Also adds the address of the deployed contract to an array of all deployed Scheduled Token Lock contracts.
_gaussToken.transfer(newScheduledLock.contractAddress(), amount); _scheduledVestingContracts.push(newScheduledLock); emit VestingCreated(beneficiary, newScheduledLock.contractAddress(), amount); return newScheduledLock.contractAddress();
_gaussToken.transfer(newScheduledLock.contractAddress(), amount); _scheduledVestingContracts.push(newScheduledLock); emit VestingCreated(beneficiary, newScheduledLock.contractAddress(), amount); return newScheduledLock.contractAddress();
5,397
50
// The following memory slots will be used when populating call data for the transfer; read the values and restore them later.
let memPointer := mload(FreeMemoryPointerSlot) let slot0x80 := mload(Slot0x80) let slot0xA0 := mload(Slot0xA0) let slot0xC0 := mload(Slot0xC0)
let memPointer := mload(FreeMemoryPointerSlot) let slot0x80 := mload(Slot0x80) let slot0xA0 := mload(Slot0xA0) let slot0xC0 := mload(Slot0xC0)
33,498
38
// ------------------------------------------------------------------------ Query to get the pending reward ------------------------------------------------------------------------
function pendingReward(address user) public view returns(uint256 _pendingReward){ uint256 reward = (onePercent(stakers[user].stakedAmount)).mul(stakers[user].rewardPercentage); reward = reward.sub(stakers[user].rewardsClaimed); return reward.add(stakers[msg.sender].pending); }
function pendingReward(address user) public view returns(uint256 _pendingReward){ uint256 reward = (onePercent(stakers[user].stakedAmount)).mul(stakers[user].rewardPercentage); reward = reward.sub(stakers[user].rewardsClaimed); return reward.add(stakers[msg.sender].pending); }
11,386
89
// Set the URI for a custom cardtokenId The token ID whose URI is being set. customURI The URI which point to an unique metadata file. /
function setCustomURI(uint256 tokenId, string memory customURI) external;
function setCustomURI(uint256 tokenId, string memory customURI) external;
21,788
208
// Calculates the Net asset value of this fund/gav Gross asset value of this fund in QUOTE_ASSET and multiplied by 10shareDecimals/unclaimedFees The sum of both managementFee and performanceFee in QUOTE_ASSET and multiplied by 10shareDecimals/ return nav Net asset value in QUOTE_ASSET and multiplied by 10shareDecimals
function calcNav(uint gav, uint unclaimedFees) view returns (uint nav)
function calcNav(uint gav, uint unclaimedFees) view returns (uint nav)
45,599
138
// Save the price (convert to special zero representation value if necessary). prices[_id].value = (_value == 0) ? ZERO_PRICE : _value;
uintStorage[keccak256(abi.encodePacked("prices.", _id, ".value"))] = (_value == 0) ? ZERO_PRICE : _value;
uintStorage[keccak256(abi.encodePacked("prices.", _id, ".value"))] = (_value == 0) ? ZERO_PRICE : _value;
61,218
15
// Address of the ProxyAdmin predeploy.
address internal constant PROXY_ADMIN = 0x4200000000000000000000000000000000000018;
address internal constant PROXY_ADMIN = 0x4200000000000000000000000000000000000018;
27,661
250
// example symbol: LP ETH 04DEC2020 C
function getMarketSymbol( string memory underlying, uint256 expiryTime, bool isPut
function getMarketSymbol( string memory underlying, uint256 expiryTime, bool isPut
11,190
2
// stores blockhashes of the given block numbers in the configured blockhash store, assumingthey are availble though the blockhash() instruction. blockNumbers the block numbers to store the blockhashes of. Must be available via theblockhash() instruction, otherwise this function call will revert. /
function store(uint256[] memory blockNumbers) public { for (uint256 i = 0; i < blockNumbers.length; i++) { // skip the block if it's not storeable, the caller will have to check // after the transaction is mined to see if the blockhash was truly stored. if (!storeableBlock(blockNumbers[i])) { continue; } BHS.store(blockNumbers[i]); } }
function store(uint256[] memory blockNumbers) public { for (uint256 i = 0; i < blockNumbers.length; i++) { // skip the block if it's not storeable, the caller will have to check // after the transaction is mined to see if the blockhash was truly stored. if (!storeableBlock(blockNumbers[i])) { continue; } BHS.store(blockNumbers[i]); } }
51,783
5
// Function to replace current minter by a new minter. It is used when we want to use a new DAO contract newMinter The address of the minter to removereturn True if the operation was successful. /
function updateMinter(address newMinter) public virtual onlyMinter returns (bool)
function updateMinter(address newMinter) public virtual onlyMinter returns (bool)
46,525
334
// Remove White List /
function removeWhiteList(uint256 boxType, address[] memory whiteUsers) external onlyRole(MANAGER_ROLE)
function removeWhiteList(uint256 boxType, address[] memory whiteUsers) external onlyRole(MANAGER_ROLE)
17,910
145
// Load signature items.
sig = sigs[i]; address user = sig.user;
sig = sigs[i]; address user = sig.user;
38,434
88
// Permits modifications only by the owner of the specified node.
modifier only_owner(bytes32 node) { require(records[node].owner == msg.sender); _; }
modifier only_owner(bytes32 node) { require(records[node].owner == msg.sender); _; }
61,789
221
// Only Keeper /
function pause() external onlyKeeper { _pause(); }
function pause() external onlyKeeper { _pause(); }
31,604
6
// Emitted when `tokenId` token is transferred from `from` to `to`. /
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
26,184
70
// Keep track of the index for which tokens still exist in the bucket
uint lastIndexToDelete = 0;
uint lastIndexToDelete = 0;
37,198
87
// -------------------------------Uniswap V3 Locker contract-------------------------------1. The contract deployer will be the owner of the contract.2. Only the current owner can change ownership.3. To lock the liquidity, the owner must transfer LP tokens to the locker contract and call the "lock" function with the unlock date.4. It is possible to transfer LP tokens from the locker contract only by calling the "unlock" function.5. If the unlock function is called before the unlock date (unlockDate), it will fail.6. It is possible to extend the lock period with the "lock" function, but it cannot be reduced. 7. It is possible to add liquidity to
contract UniswapV3LiquidityLocker { /* @dev Contract constants and variables: * "public" means that the variable can be read by public (e.g. any bscscan.com user). * "private" means that the variable can be accessed by this contract only. * "immutable" means that the variable can be set once when the contract is created and cannot be changed after that. */ /// @notice Uniswap V3 Pool address address public immutable uniswapV3Pool; /// @notice Uniswap V3: Positions NFT contract address address public immutable uniswapV3PositionManager; /// @notice The owner of the locker contract and liquidity. address public owner; /// @notice Unlock date as a unix timestamp. You can convert the timestamp to a readable date-time at https://www.unixtimestamp.com/. uint public unlockDate; /// @notice Uniswap V3 Position Token ID uint256[] private tokenIds; // Definition of events. // If event is emitted, it stores the arguments passed in transaction logs. // These logs are stored on blockchain and are accessible using address of the contract. event OwnerChanged(address oldOwner, address newOwner); event LiquidityLocked(uint until); event LiquidityUnlocked(uint256 tokenId, uint date); event ERC721TokenReceived(address sender, address owner, uint256 tokenId); /** * @notice Locker contract constructor. It will only be called once when deploying * contract. */ constructor(address _uniswapV3Pool, address _uniswapV3PositionManager) { // Set the locker contract owner to the creator of the contract (msg.sender) owner = msg.sender; // Set Uniswap V3 Pool address uniswapV3Pool = _uniswapV3Pool; // Set Uniswap V3: Position NFT contract address uniswapV3PositionManager = _uniswapV3PositionManager; } /** * @notice The modifier will be used later with the lock and unlock functions, so only the owner of * contract owner can call these functions. */ modifier onlyOwner() { // The function will fail if the contract is not called by its owner require (msg.sender == owner); // The _; symbol is a special symbol that is used in Solidity modifiers to indicate the end of // the modifier and the beginning of the function that the modifier is modifying. _; } /* * --------------------------------------------------------------------------------- * Functions that change the state of the blockchain * --------------------------------------------------------------------------------- */ /** * @notice * Change locker contract owner (Transfer ownership). * @param _newOwner new owner of the locker contract */ function changeOwner(address _newOwner) external // Only owner can call this function onlyOwner { // Emit public event to notify subscribers emit OwnerChanged(owner, _newOwner); // Set new owner to _newOwner owner = _newOwner; } // @notice The function called when the ERC721 token is received by the contract. function onERC721Received( address, address from, uint256 tokenId, bytes calldata ) external returns (bytes4) { // Allow access to Uniswap V3 Position Manager contract only require (msg.sender == uniswapV3PositionManager, "Denied"); // Enable NFT transfers to the contract to the contract owner only. require (from == owner, "Denied"); // Check if the token is a Uniswap V3 NFT Position token (address token0, address token1,,,) = getPositionByTokenId(tokenId); // Check if the token belongs to the Uniswap V3 Pool (uniswapV3Pool) require ((token0 == IUniswapV3Pool(uniswapV3Pool).token0()) && (token1 == IUniswapV3Pool(uniswapV3Pool).token1()), "Invalid token"); // Check if tokenId is not in the list of tokens require (getTokenIndexById(tokenId) == type(uint256).max, "Token exists"); // Add token ID to a list of tokens tokenIds.push(tokenId); emit ERC721TokenReceived(msg.sender, IERC721(uniswapV3PositionManager).ownerOf(tokenId), tokenId); // Return selector according to ERC721 return this.onERC721Received.selector; } /** * @notice Lock function. The owner must call this function to lock or to extend the lock of * the liquidity. * @param _unlockDate the unlock date */ function lock(uint _unlockDate) public // Only owner can call this function onlyOwner { // The new unlock date must be greater than the last unlock date. // This condition guarantees that we cannot reduce the blocking period, // but we can increase it. require (_unlockDate > unlockDate, "Invalid unlock date"); // The unlock date must be in the future. require (_unlockDate > block.timestamp, "Invalid unlock date"); // Set the date to unlock liquidity. Before this date, it is // not possible to transfer LP tokens from the contract. unlockDate = _unlockDate; // Emit a LiquidityLocked event so that it is visible to any event subscriber emit LiquidityLocked(unlockDate); } /** * @notice Unlock LP-token. This function will transfer LP-token from the contract to the owner. * If the function is called before the unlockDate, it will fail. * @param tokenId is the liquidity pool token ID to unlock */ function unlock(uint256 tokenId) external // Only owner can call the function onlyOwner { // Check if the current date is greater than or equal to unlockDate. Fail if it is not. require (block.timestamp >= unlockDate, "Not yet"); // Search liquidity token tokenId in the tokenIds list uint256 index = getTokenIndexById(tokenId); // Require tokenId is in the list of received Uniswap V3 Position NFTs require (index < type(uint256).max, "tokenId not found"); // Move last element of tokenIds to the found one tokenIds[index] = tokenIds[tokenIds.length - 1]; // Pop (delete) last element of tokenIds tokenIds.pop(); // Transfer Uniswap V3 Position NFT with tokenId to the owner IERC721(uniswapV3PositionManager).safeTransferFrom(address(this), owner, tokenId); // Emit a LiquidityUnlocked event so that it is visible to any event subscriber emit LiquidityUnlocked(tokenId, block.timestamp); } /** * @notice Collect earned fees for position by tockenId * Only owner can call the function. Fees will be transfered to the owner account. * @param tokenId position Token ID * @return amount0 * @return amount1 */ function collectFeesByTokenId(uint256 tokenId) external onlyOwner returns (uint256 amount0, uint256 amount1) { // Set CollectParams to request fees // set amount0Max and amount1Max to uint256.max to collect all fees INonfungiblePositionManager.CollectParams memory params = INonfungiblePositionManager.CollectParams({ tokenId: tokenId, // ERC721 token ID recipient: owner, // recipient of fees amount0Max: type(uint128).max, amount1Max: type(uint128).max }); (amount0, amount1) = INonfungiblePositionManager(uniswapV3PositionManager).collect(params); } /** * @dev * ------------------------------------------------------------------------------------------- * Read-only functions to retrieve information from the contract to make it publicly available * ------------------------------------------------------------------------------------------- */ /** * @notice Get list of liquidity tokens locked on the contract */ function getTokenIds() public view returns (uint256[] memory) { return tokenIds; } /* @dev Get tokenId index in tokenIds list @return index the tokenId index in the tokenIds list or the maximum uint256 value if no token is found. */ function getTokenIndexById(uint256 tokenId) private view returns (uint256 index) { // Search liquidity token tokenId in the tokenIds list index = type(uint256).max; for (uint256 i = 0; i < tokenIds.length; i++) { if (tokenIds[i] == tokenId) { index = i; break; } } return index; } /** * @notice Get position information by token ID * @param tokenId Token ID * Range is [tickLower, tickUpper] * @return token0 The token0 contract address * @return token1 The token1 contract address * @return tickLower lower tick value * @return tickUpper upper tick value * @return liquidity the liquidity of the position */ function getPositionByTokenId(uint256 tokenId) public view returns (address token0, address token1, int24 tickLower, int24 tickUpper, uint128 liquidity) { (,, token0, token1,, tickLower, tickUpper, liquidity,,,,) = INonfungiblePositionManager(uniswapV3PositionManager).positions(tokenId); return (token0, token1, tickLower, tickUpper, liquidity); } /** * @notice Get total liquidity of the Uniswap V3 Pool in range. * @return totalLiquidity the total liquidity of the Uniswap V3 Pool in range */ function getTotalLiquidityInRange() public view returns (uint128 totalLiquidity) { return IUniswapV3Pool(uniswapV3Pool).liquidity(); } /** * @notice Get locked liquidity information: percent of the total liquidity locked, percent X 100, * current tick, liquidity sum of the contract in range, total liquidity in range */ function getLockedLiquidityInfo() public view returns ( uint256 lockedPercentOfTotalLiquidityInRange, uint256 lockedPercentX100, int24 tick, uint128 liquiditySumInRange, uint128 totalLiquidityInRange) { // Get current tick tick = IUniswapV3Pool(uniswapV3Pool).slot0().tick; // Calculate sum of liquidity for all contract positions that are in range liquiditySumInRange = 0; // Go through the list of contract liquidity tokens for (uint256 i = 0; i < tokenIds.length; i++) { // Get position data for tokenId (,, int24 tickLower, int24 tickUpper, uint128 liquidity) = getPositionByTokenId(tokenIds[i]); // Check if liquidity of position is in the range if ((tickLower <= tick) && (tick <= tickUpper)) { // Add lposition iquidity to the sum liquiditySumInRange += liquidity; } } // Get total liquidity in range totalLiquidityInRange = getTotalLiquidityInRange(); // Check total liquidity in range require (totalLiquidityInRange > 0, "Total liquidity is zero"); // Calculate the percentage of locked liquidity lockedPercentX100 = liquiditySumInRange * 100 * 100 / totalLiquidityInRange; // Return values return ( lockedPercentX100 / 100, lockedPercentX100, tick, liquiditySumInRange, totalLiquidityInRange); } }
contract UniswapV3LiquidityLocker { /* @dev Contract constants and variables: * "public" means that the variable can be read by public (e.g. any bscscan.com user). * "private" means that the variable can be accessed by this contract only. * "immutable" means that the variable can be set once when the contract is created and cannot be changed after that. */ /// @notice Uniswap V3 Pool address address public immutable uniswapV3Pool; /// @notice Uniswap V3: Positions NFT contract address address public immutable uniswapV3PositionManager; /// @notice The owner of the locker contract and liquidity. address public owner; /// @notice Unlock date as a unix timestamp. You can convert the timestamp to a readable date-time at https://www.unixtimestamp.com/. uint public unlockDate; /// @notice Uniswap V3 Position Token ID uint256[] private tokenIds; // Definition of events. // If event is emitted, it stores the arguments passed in transaction logs. // These logs are stored on blockchain and are accessible using address of the contract. event OwnerChanged(address oldOwner, address newOwner); event LiquidityLocked(uint until); event LiquidityUnlocked(uint256 tokenId, uint date); event ERC721TokenReceived(address sender, address owner, uint256 tokenId); /** * @notice Locker contract constructor. It will only be called once when deploying * contract. */ constructor(address _uniswapV3Pool, address _uniswapV3PositionManager) { // Set the locker contract owner to the creator of the contract (msg.sender) owner = msg.sender; // Set Uniswap V3 Pool address uniswapV3Pool = _uniswapV3Pool; // Set Uniswap V3: Position NFT contract address uniswapV3PositionManager = _uniswapV3PositionManager; } /** * @notice The modifier will be used later with the lock and unlock functions, so only the owner of * contract owner can call these functions. */ modifier onlyOwner() { // The function will fail if the contract is not called by its owner require (msg.sender == owner); // The _; symbol is a special symbol that is used in Solidity modifiers to indicate the end of // the modifier and the beginning of the function that the modifier is modifying. _; } /* * --------------------------------------------------------------------------------- * Functions that change the state of the blockchain * --------------------------------------------------------------------------------- */ /** * @notice * Change locker contract owner (Transfer ownership). * @param _newOwner new owner of the locker contract */ function changeOwner(address _newOwner) external // Only owner can call this function onlyOwner { // Emit public event to notify subscribers emit OwnerChanged(owner, _newOwner); // Set new owner to _newOwner owner = _newOwner; } // @notice The function called when the ERC721 token is received by the contract. function onERC721Received( address, address from, uint256 tokenId, bytes calldata ) external returns (bytes4) { // Allow access to Uniswap V3 Position Manager contract only require (msg.sender == uniswapV3PositionManager, "Denied"); // Enable NFT transfers to the contract to the contract owner only. require (from == owner, "Denied"); // Check if the token is a Uniswap V3 NFT Position token (address token0, address token1,,,) = getPositionByTokenId(tokenId); // Check if the token belongs to the Uniswap V3 Pool (uniswapV3Pool) require ((token0 == IUniswapV3Pool(uniswapV3Pool).token0()) && (token1 == IUniswapV3Pool(uniswapV3Pool).token1()), "Invalid token"); // Check if tokenId is not in the list of tokens require (getTokenIndexById(tokenId) == type(uint256).max, "Token exists"); // Add token ID to a list of tokens tokenIds.push(tokenId); emit ERC721TokenReceived(msg.sender, IERC721(uniswapV3PositionManager).ownerOf(tokenId), tokenId); // Return selector according to ERC721 return this.onERC721Received.selector; } /** * @notice Lock function. The owner must call this function to lock or to extend the lock of * the liquidity. * @param _unlockDate the unlock date */ function lock(uint _unlockDate) public // Only owner can call this function onlyOwner { // The new unlock date must be greater than the last unlock date. // This condition guarantees that we cannot reduce the blocking period, // but we can increase it. require (_unlockDate > unlockDate, "Invalid unlock date"); // The unlock date must be in the future. require (_unlockDate > block.timestamp, "Invalid unlock date"); // Set the date to unlock liquidity. Before this date, it is // not possible to transfer LP tokens from the contract. unlockDate = _unlockDate; // Emit a LiquidityLocked event so that it is visible to any event subscriber emit LiquidityLocked(unlockDate); } /** * @notice Unlock LP-token. This function will transfer LP-token from the contract to the owner. * If the function is called before the unlockDate, it will fail. * @param tokenId is the liquidity pool token ID to unlock */ function unlock(uint256 tokenId) external // Only owner can call the function onlyOwner { // Check if the current date is greater than or equal to unlockDate. Fail if it is not. require (block.timestamp >= unlockDate, "Not yet"); // Search liquidity token tokenId in the tokenIds list uint256 index = getTokenIndexById(tokenId); // Require tokenId is in the list of received Uniswap V3 Position NFTs require (index < type(uint256).max, "tokenId not found"); // Move last element of tokenIds to the found one tokenIds[index] = tokenIds[tokenIds.length - 1]; // Pop (delete) last element of tokenIds tokenIds.pop(); // Transfer Uniswap V3 Position NFT with tokenId to the owner IERC721(uniswapV3PositionManager).safeTransferFrom(address(this), owner, tokenId); // Emit a LiquidityUnlocked event so that it is visible to any event subscriber emit LiquidityUnlocked(tokenId, block.timestamp); } /** * @notice Collect earned fees for position by tockenId * Only owner can call the function. Fees will be transfered to the owner account. * @param tokenId position Token ID * @return amount0 * @return amount1 */ function collectFeesByTokenId(uint256 tokenId) external onlyOwner returns (uint256 amount0, uint256 amount1) { // Set CollectParams to request fees // set amount0Max and amount1Max to uint256.max to collect all fees INonfungiblePositionManager.CollectParams memory params = INonfungiblePositionManager.CollectParams({ tokenId: tokenId, // ERC721 token ID recipient: owner, // recipient of fees amount0Max: type(uint128).max, amount1Max: type(uint128).max }); (amount0, amount1) = INonfungiblePositionManager(uniswapV3PositionManager).collect(params); } /** * @dev * ------------------------------------------------------------------------------------------- * Read-only functions to retrieve information from the contract to make it publicly available * ------------------------------------------------------------------------------------------- */ /** * @notice Get list of liquidity tokens locked on the contract */ function getTokenIds() public view returns (uint256[] memory) { return tokenIds; } /* @dev Get tokenId index in tokenIds list @return index the tokenId index in the tokenIds list or the maximum uint256 value if no token is found. */ function getTokenIndexById(uint256 tokenId) private view returns (uint256 index) { // Search liquidity token tokenId in the tokenIds list index = type(uint256).max; for (uint256 i = 0; i < tokenIds.length; i++) { if (tokenIds[i] == tokenId) { index = i; break; } } return index; } /** * @notice Get position information by token ID * @param tokenId Token ID * Range is [tickLower, tickUpper] * @return token0 The token0 contract address * @return token1 The token1 contract address * @return tickLower lower tick value * @return tickUpper upper tick value * @return liquidity the liquidity of the position */ function getPositionByTokenId(uint256 tokenId) public view returns (address token0, address token1, int24 tickLower, int24 tickUpper, uint128 liquidity) { (,, token0, token1,, tickLower, tickUpper, liquidity,,,,) = INonfungiblePositionManager(uniswapV3PositionManager).positions(tokenId); return (token0, token1, tickLower, tickUpper, liquidity); } /** * @notice Get total liquidity of the Uniswap V3 Pool in range. * @return totalLiquidity the total liquidity of the Uniswap V3 Pool in range */ function getTotalLiquidityInRange() public view returns (uint128 totalLiquidity) { return IUniswapV3Pool(uniswapV3Pool).liquidity(); } /** * @notice Get locked liquidity information: percent of the total liquidity locked, percent X 100, * current tick, liquidity sum of the contract in range, total liquidity in range */ function getLockedLiquidityInfo() public view returns ( uint256 lockedPercentOfTotalLiquidityInRange, uint256 lockedPercentX100, int24 tick, uint128 liquiditySumInRange, uint128 totalLiquidityInRange) { // Get current tick tick = IUniswapV3Pool(uniswapV3Pool).slot0().tick; // Calculate sum of liquidity for all contract positions that are in range liquiditySumInRange = 0; // Go through the list of contract liquidity tokens for (uint256 i = 0; i < tokenIds.length; i++) { // Get position data for tokenId (,, int24 tickLower, int24 tickUpper, uint128 liquidity) = getPositionByTokenId(tokenIds[i]); // Check if liquidity of position is in the range if ((tickLower <= tick) && (tick <= tickUpper)) { // Add lposition iquidity to the sum liquiditySumInRange += liquidity; } } // Get total liquidity in range totalLiquidityInRange = getTotalLiquidityInRange(); // Check total liquidity in range require (totalLiquidityInRange > 0, "Total liquidity is zero"); // Calculate the percentage of locked liquidity lockedPercentX100 = liquiditySumInRange * 100 * 100 / totalLiquidityInRange; // Return values return ( lockedPercentX100 / 100, lockedPercentX100, tick, liquiditySumInRange, totalLiquidityInRange); } }
9,412
318
// to get the staker's unlocked tokens which were staked _stakerAddress is the address of the staker _stakerIndex is the index of stakerreturn amount /
function getStakerUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount)
function getStakerUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount)
1,927
16
// Character
TIERS[7] = [7, 23, 237, 329, 380, 394, 427, 471, 507, 512];
TIERS[7] = [7, 23, 237, 329, 380, 394, 427, 471, 507, 512];
76,700
35
// /
function initialize( address _owner, Config calldata _config, string calldata _baseCurrency, bool _nativePaymentsEnabled, AggregatorV3Interface _nativeTokenPriceOracle, IERC20Upgradeable[] calldata tokens, AggregatorV3Interface[] calldata oracles, uint8[] calldata decimals
function initialize( address _owner, Config calldata _config, string calldata _baseCurrency, bool _nativePaymentsEnabled, AggregatorV3Interface _nativeTokenPriceOracle, IERC20Upgradeable[] calldata tokens, AggregatorV3Interface[] calldata oracles, uint8[] calldata decimals
29,610
447
// write 4 characters
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) resultPtr := add(resultPtr, 1)
4,009
291
// Internal function to tell the information for a module based on a given ID_id ID of the module being queried return addr Current address of the requested module return disabled Whether the module has been disabled/
function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) { addr = _getModuleAddress(_id); disabled = _isModuleDisabled(addr); }
function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) { addr = _getModuleAddress(_id); disabled = _isModuleDisabled(addr); }
12,907
149
// if left + right overflows, prevent overflow
if (left + right < left) { left = left.div(2); right = right.div(2); denominator = denominator.div(2); }
if (left + right < left) { left = left.div(2); right = right.div(2); denominator = denominator.div(2); }
67,189
50
// Maximum tokens to be allocated (2.2 billion IDC)
uint256 public constant HARD_CAP = 2200000000 * 10**uint256(decimals);
uint256 public constant HARD_CAP = 2200000000 * 10**uint256(decimals);
21,296
114
// as staker
Staker storage staker = proposal.stakers[_beneficiary]; uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; uint256 totalStakesLeftAfterCallBounty = proposal.stakes[NO].add(proposal.stakes[YES]).sub(calcExecuteCallBounty(_proposalId)); if (staker.amount > 0) { if (proposal.state == ProposalState.ExpiredInQueue) {
Staker storage staker = proposal.stakers[_beneficiary]; uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; uint256 totalStakesLeftAfterCallBounty = proposal.stakes[NO].add(proposal.stakes[YES]).sub(calcExecuteCallBounty(_proposalId)); if (staker.amount > 0) { if (proposal.state == ProposalState.ExpiredInQueue) {
18,551
15
// In homage to Bitcoin, the initial minting of WHAPcoin is set to 21 million tokens (210000001e18 in terms of the smallest unit).These tokens are the starting supply before any rewards are minted through the WHAPcoin Power-Law-HalvingMechanism.
uint256 _initialMinting = 21000000 * 1e18; initialMinting = _initialMinting; remainingRewards = _max_Supply - _initialMinting; // Remaining tokens that will be minted as rewards over time.
uint256 _initialMinting = 21000000 * 1e18; initialMinting = _initialMinting; remainingRewards = _max_Supply - _initialMinting; // Remaining tokens that will be minted as rewards over time.
24,813
250
// Convex Strategies common variables and helper functions
abstract contract ConvexStrategyBase { using SafeERC20 for IERC20; address public constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant BOOSTER = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31; address public immutable cvxCrvRewards; uint256 public immutable convexPoolId; bool public isClaimRewards; uint256 internal constant SUSHISWAP_ROUTER_INDEX = 1; struct ClaimableRewardInfo { address token; uint256 amount; } constructor(address _crvLp, uint256 _convexPoolId) { (address _lp, , , address _reward, , ) = IConvex(BOOSTER).poolInfo(_convexPoolId); require(_lp == address(_crvLp), "incorrect-lp-token"); cvxCrvRewards = _reward; convexPoolId = _convexPoolId; } function _getRewardTokens() internal view returns (address[] memory) { uint256 extraRewardCount; for (uint256 i = 0; i < Rewards(cvxCrvRewards).extraRewardsLength(); i++) { Rewards rewardContract = Rewards(Rewards(cvxCrvRewards).extraRewards(i)); // Some pool has CVX as extra rewards but other do not. CVX still reward token if (rewardContract.rewardToken() != CRV && rewardContract.rewardToken() != CVX) { extraRewardCount++; } } address[] memory _rewardTokens = new address[](extraRewardCount + 2); _rewardTokens[0] = CRV; _rewardTokens[1] = CVX; uint256 index = 2; for (uint256 i = 0; i < Rewards(cvxCrvRewards).extraRewardsLength(); i++) { Rewards rewardContract = Rewards(Rewards(cvxCrvRewards).extraRewards(i)); // CRV and CVX already added in array if (rewardContract.rewardToken() != CRV && rewardContract.rewardToken() != CVX) { _rewardTokens[index] = rewardContract.rewardToken(); index++; } } return _rewardTokens; } /// @dev Returns a list of (token, amount) for all rewards claimable in a Convex Pool function _claimableRewards() internal view returns (ClaimableRewardInfo[] memory) { uint256 _extraRewardCount = Rewards(cvxCrvRewards).extraRewardsLength(); ClaimableRewardInfo[] memory _claimableRewardsInfo = new ClaimableRewardInfo[](_extraRewardCount + 2); uint256 _baseReward = Rewards(cvxCrvRewards).earned(address(this)); // CVX rewards are minted proportionally to baseReward (CRV) uint256 _cvxReward = _calculateCVXRewards(_baseReward); _claimableRewardsInfo[0] = ClaimableRewardInfo(CRV, _baseReward); _claimableRewardsInfo[1] = ClaimableRewardInfo(CVX, _cvxReward); // Don't care if there are additional CRV, or CVX in extraRewards // total amount will be summed together in claimableRewardsInCollateral() for (uint256 i = 0; i < _extraRewardCount; i++) { Rewards _rewardContract = Rewards(Rewards(cvxCrvRewards).extraRewards(i)); _claimableRewardsInfo[2 + i] = ClaimableRewardInfo( _rewardContract.rewardToken(), _rewardContract.earned(address(this)) ); } return _claimableRewardsInfo; } // TODO: review this again. There may be substitute function _calculateCVXRewards(uint256 _claimableCrvRewards) internal view returns (uint256 _total) { // CVX Rewards are minted based on CRV rewards claimed upon withdraw // This will calculate the CVX amount based on CRV rewards accrued // without having to claim CRV rewards first // ref 1: https://github.com/convex-eth/platform/blob/main/contracts/contracts/Cvx.sol#L61-L76 // ref 2: https://github.com/convex-eth/platform/blob/main/contracts/contracts/Booster.sol#L458-L466 uint256 _reductionPerCliff = IConvexToken(CVX).reductionPerCliff(); uint256 _totalSupply = IConvexToken(CVX).totalSupply(); uint256 _maxSupply = IConvexToken(CVX).maxSupply(); uint256 _cliff = _totalSupply / _reductionPerCliff; uint256 _totalCliffs = 1000; if (_cliff < _totalCliffs) { //for reduction% take inverse of current cliff uint256 _reduction = _totalCliffs - _cliff; //reduce _total = (_claimableCrvRewards * _reduction) / _totalCliffs; //supply cap check uint256 _amtTillMax = _maxSupply - _totalSupply; if (_total > _amtTillMax) { _total = _amtTillMax; } } } }
abstract contract ConvexStrategyBase { using SafeERC20 for IERC20; address public constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address private constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant BOOSTER = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31; address public immutable cvxCrvRewards; uint256 public immutable convexPoolId; bool public isClaimRewards; uint256 internal constant SUSHISWAP_ROUTER_INDEX = 1; struct ClaimableRewardInfo { address token; uint256 amount; } constructor(address _crvLp, uint256 _convexPoolId) { (address _lp, , , address _reward, , ) = IConvex(BOOSTER).poolInfo(_convexPoolId); require(_lp == address(_crvLp), "incorrect-lp-token"); cvxCrvRewards = _reward; convexPoolId = _convexPoolId; } function _getRewardTokens() internal view returns (address[] memory) { uint256 extraRewardCount; for (uint256 i = 0; i < Rewards(cvxCrvRewards).extraRewardsLength(); i++) { Rewards rewardContract = Rewards(Rewards(cvxCrvRewards).extraRewards(i)); // Some pool has CVX as extra rewards but other do not. CVX still reward token if (rewardContract.rewardToken() != CRV && rewardContract.rewardToken() != CVX) { extraRewardCount++; } } address[] memory _rewardTokens = new address[](extraRewardCount + 2); _rewardTokens[0] = CRV; _rewardTokens[1] = CVX; uint256 index = 2; for (uint256 i = 0; i < Rewards(cvxCrvRewards).extraRewardsLength(); i++) { Rewards rewardContract = Rewards(Rewards(cvxCrvRewards).extraRewards(i)); // CRV and CVX already added in array if (rewardContract.rewardToken() != CRV && rewardContract.rewardToken() != CVX) { _rewardTokens[index] = rewardContract.rewardToken(); index++; } } return _rewardTokens; } /// @dev Returns a list of (token, amount) for all rewards claimable in a Convex Pool function _claimableRewards() internal view returns (ClaimableRewardInfo[] memory) { uint256 _extraRewardCount = Rewards(cvxCrvRewards).extraRewardsLength(); ClaimableRewardInfo[] memory _claimableRewardsInfo = new ClaimableRewardInfo[](_extraRewardCount + 2); uint256 _baseReward = Rewards(cvxCrvRewards).earned(address(this)); // CVX rewards are minted proportionally to baseReward (CRV) uint256 _cvxReward = _calculateCVXRewards(_baseReward); _claimableRewardsInfo[0] = ClaimableRewardInfo(CRV, _baseReward); _claimableRewardsInfo[1] = ClaimableRewardInfo(CVX, _cvxReward); // Don't care if there are additional CRV, or CVX in extraRewards // total amount will be summed together in claimableRewardsInCollateral() for (uint256 i = 0; i < _extraRewardCount; i++) { Rewards _rewardContract = Rewards(Rewards(cvxCrvRewards).extraRewards(i)); _claimableRewardsInfo[2 + i] = ClaimableRewardInfo( _rewardContract.rewardToken(), _rewardContract.earned(address(this)) ); } return _claimableRewardsInfo; } // TODO: review this again. There may be substitute function _calculateCVXRewards(uint256 _claimableCrvRewards) internal view returns (uint256 _total) { // CVX Rewards are minted based on CRV rewards claimed upon withdraw // This will calculate the CVX amount based on CRV rewards accrued // without having to claim CRV rewards first // ref 1: https://github.com/convex-eth/platform/blob/main/contracts/contracts/Cvx.sol#L61-L76 // ref 2: https://github.com/convex-eth/platform/blob/main/contracts/contracts/Booster.sol#L458-L466 uint256 _reductionPerCliff = IConvexToken(CVX).reductionPerCliff(); uint256 _totalSupply = IConvexToken(CVX).totalSupply(); uint256 _maxSupply = IConvexToken(CVX).maxSupply(); uint256 _cliff = _totalSupply / _reductionPerCliff; uint256 _totalCliffs = 1000; if (_cliff < _totalCliffs) { //for reduction% take inverse of current cliff uint256 _reduction = _totalCliffs - _cliff; //reduce _total = (_claimableCrvRewards * _reduction) / _totalCliffs; //supply cap check uint256 _amtTillMax = _maxSupply - _totalSupply; if (_total > _amtTillMax) { _total = _amtTillMax; } } } }
19,118
54
// Calculate remaining tab after operation
tab = tab - owe; // safe since owe <= tab
tab = tab - owe; // safe since owe <= tab
36,567
2
// helper function to get a document's sha256
function proofFor(string document) constant returns (bytes32) { return sha256(document); }
function proofFor(string document) constant returns (bytes32) { return sha256(document); }
40,211
44
// See in IERC897Proxy.
function implementation() external view override returns (address) { return _implementation(); }
function implementation() external view override returns (address) { return _implementation(); }
33,321
6
// Returns the addition of two unsigned integers, reverting onoverflow. Counterpart to Solidity's `+` operator. Requirements:- Addition cannot overflow. /
function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
15,417
6
// Sets multi-swap issuance property
_mip.remainingInputAmount = _mip.inputAmount;
_mip.remainingInputAmount = _mip.inputAmount;
2,418
877
// currencyId /,/ initializedTime /,/ assetArrayLength /,/ parameters / No overflow here, checked above
uint256 timeSinceLastClaim = blockTime - lastClaimTime; uint256 incentiveRate = _getIncentiveRate( timeSinceLastClaim,
uint256 timeSinceLastClaim = blockTime - lastClaimTime; uint256 incentiveRate = _getIncentiveRate( timeSinceLastClaim,
65,230
223
// Event emitted when DFL is accrued
event AccrueDFL(uint uniswapPart, uint minerLeaguePart, uint operatorPart, uint technicalPart, uint supplyPart, uint dflSupplyIndex);
event AccrueDFL(uint uniswapPart, uint minerLeaguePart, uint operatorPart, uint technicalPart, uint supplyPart, uint dflSupplyIndex);
26,363
158
// Transfer to array of addresses
function transfer(address[] memory recipients, uint256[] memory amounts) public returns(bool) { require(recipients.length == amounts.length, "Arrays lengths not equal"); // transfer to all addresses for (uint i = 0; i < recipients.length; i++) { _transfer(msg.sender, recipients[i], amounts[i]); } return true; }
function transfer(address[] memory recipients, uint256[] memory amounts) public returns(bool) { require(recipients.length == amounts.length, "Arrays lengths not equal"); // transfer to all addresses for (uint i = 0; i < recipients.length; i++) { _transfer(msg.sender, recipients[i], amounts[i]); } return true; }
36,713
112
// No need for SafeMath: for this to overflow array size should be ~2^255
uint256 mid = (high + low + 1) / 2; Checkpoint storage checkpoint = self.history[mid]; uint64 midTime = checkpoint.time; if (_time > midTime) { low = mid; } else if (_time < midTime) {
uint256 mid = (high + low + 1) / 2; Checkpoint storage checkpoint = self.history[mid]; uint64 midTime = checkpoint.time; if (_time > midTime) { low = mid; } else if (_time < midTime) {
7,363
157
// calculate USDC price and inflate by 1018
uint256 tokenPrice = priceNativeToUSDC[1].mul(10**18).div(priceNativeToTOKEN[1]); return(tokenPrice);
uint256 tokenPrice = priceNativeToUSDC[1].mul(10**18).div(priceNativeToTOKEN[1]); return(tokenPrice);
35,966
105
// Approve the passed address to spend the specified amount of tokens on behalf ofmsg.sender. This method is included for ERC20 compatibility.increaseAllowance and decreaseAllowance should be used instead.Changing an allowance with this method brings the risk that someone may transfer boththe old and the new allowance - if they are both greater than zero - if a transfertransaction is mined before the later approve() call is mined.spender The address which will spend the funds. value The amount of tokens to be spent. /
function approve(address spender, uint256 value) external validRecipient(spender) returns (bool)
function approve(address spender, uint256 value) external validRecipient(spender) returns (bool)
3,961
32
// Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position are not funding-rate adjusted because the multiplier only affects their redemption value, not their notional.
{ FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
{ FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
19,166
25
// Add back in dashes at correct positions
if (i == 7 || i == 11 || i == 15 || i == 19) { j++; bytesArray[j] = "-"; }
if (i == 7 || i == 11 || i == 15 || i == 19) { j++; bytesArray[j] = "-"; }
18,612
50
// The following memory slots will be used when populating call data for the transfer; read the values and restore them later.
let memPointer := mload(FreeMemoryPointerSlot) let slot0x80 := mload(Slot0x80) let slot0xA0 := mload(Slot0xA0) let slot0xC0 := mload(Slot0xC0)
let memPointer := mload(FreeMemoryPointerSlot) let slot0x80 := mload(Slot0x80) let slot0xA0 := mload(Slot0xA0) let slot0xC0 := mload(Slot0xC0)
22,739
29
// Fail if transfer not allowed // Do not allow self-transfers // Get the allowance, infinite for the account owner // Do the calculations, checking for {under,over}flow // EFFECTS & INTERACTIONS (No safe failures beyond this point)
accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew;
accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew;
9,394
24
// ------------------------------------------------------------------------ 1,000,000 FWD Tokens per 1 ETH ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 1500000; } else { tokens = msg.value * 1000000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); }
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 1500000; } else { tokens = msg.value * 1000000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); }
28,916
193
// Set claim as complete
claim.status = ClaimStatus.Complete; DistributeFees(msg.sender, _jobId, _claimId, fees);
claim.status = ClaimStatus.Complete; DistributeFees(msg.sender, _jobId, _claimId, fees);
30,493
12
// Informational function returning if the mint is currently ongoing
function mintIsOpen() public view returns (bool) { return block.timestamp > MINT_START_AT && block.timestamp <= MINT_START_AT + MINT_DURATION; }
function mintIsOpen() public view returns (bool) { return block.timestamp > MINT_START_AT && block.timestamp <= MINT_START_AT + MINT_DURATION; }
17,735
13
// BPool
function bp_swapExactAmountIn( address bpool, address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice ) external returns (uint tokenAmountOut, uint spotPriceAfter);
function bp_swapExactAmountIn( address bpool, address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice ) external returns (uint tokenAmountOut, uint spotPriceAfter);
3,825
48
// Arbitrary limit, Chainlink's threshold is always less than a day
if (_heartbeat > 2 days) revert InvalidHeartbeat(); if (_heartbeat == assetData[_asset].heartbeat) { return false; }
if (_heartbeat > 2 days) revert InvalidHeartbeat(); if (_heartbeat == assetData[_asset].heartbeat) { return false; }
31,352
49
// Specify a new schedule for staking rewards. Contract must already hold enough tokens.Can only be called by reward distributor. Owner must approve distributionToken for withdrawal.epochDuration must divide reward evenly, otherwise any remainder will be lost.rewardThe amount of rewards to distribute per second. /
function notifyRewardAmount(uint256 reward) external override onlyOwner updateRewards { if (block.timestamp < endTimestamp) { uint256 remaining = endTimestamp - block.timestamp; uint256 leftover = remaining * rewardRate; reward += leftover; } if (reward < nextEpochDuration) revert USR_ZeroRewardsPerEpoch(); uint256 rewardBalance = distributionToken.balanceOf(address(this)); uint256 pendingRewards = reward + rewardsReady; if (rewardBalance < pendingRewards) revert STATE_RewardsNotFunded(rewardBalance, pendingRewards); // prevent overflow when computing rewardPerToken uint256 proposedRewardRate = reward / nextEpochDuration; if (proposedRewardRate >= ((type(uint256).max / ONE) / nextEpochDuration)) { revert USR_RewardTooLarge(); } if (totalDeposits == 0) { // No deposits yet, so keep rewards pending until first deposit // Incrementing in case it is called twice rewardsReady += reward; } else { // Ready to start _startProgram(reward); } lastAccountingTimestamp = block.timestamp; }
function notifyRewardAmount(uint256 reward) external override onlyOwner updateRewards { if (block.timestamp < endTimestamp) { uint256 remaining = endTimestamp - block.timestamp; uint256 leftover = remaining * rewardRate; reward += leftover; } if (reward < nextEpochDuration) revert USR_ZeroRewardsPerEpoch(); uint256 rewardBalance = distributionToken.balanceOf(address(this)); uint256 pendingRewards = reward + rewardsReady; if (rewardBalance < pendingRewards) revert STATE_RewardsNotFunded(rewardBalance, pendingRewards); // prevent overflow when computing rewardPerToken uint256 proposedRewardRate = reward / nextEpochDuration; if (proposedRewardRate >= ((type(uint256).max / ONE) / nextEpochDuration)) { revert USR_RewardTooLarge(); } if (totalDeposits == 0) { // No deposits yet, so keep rewards pending until first deposit // Incrementing in case it is called twice rewardsReady += reward; } else { // Ready to start _startProgram(reward); } lastAccountingTimestamp = block.timestamp; }
27,868
137
// FinishMintingCrowdsale FinishMintingCrowdsale prevents token generation after sale ended. /
contract FinishMintingCrowdsale is BaseCrowdsale { function afterGeneratorHook() internal { require(finishMinting()); super.afterGeneratorHook(); } }
contract FinishMintingCrowdsale is BaseCrowdsale { function afterGeneratorHook() internal { require(finishMinting()); super.afterGeneratorHook(); } }
81,341
142
// free
if (mintedQty < FREE_MINT_MAX_QTY) { require(mintedQty + _mintQty <= FREE_MINT_MAX_QTY, "MAXL"); require(minterToTokenQty[msg.sender] + _mintQty <= maxFreeQtyPerWallet, "MAXF"); }
if (mintedQty < FREE_MINT_MAX_QTY) { require(mintedQty + _mintQty <= FREE_MINT_MAX_QTY, "MAXL"); require(minterToTokenQty[msg.sender] + _mintQty <= maxFreeQtyPerWallet, "MAXF"); }
66,441
31
// Retrieve the token balance of any single address. /
function balanceOf(address _customerAddress) view public returns(uint256)
function balanceOf(address _customerAddress) view public returns(uint256)
8,820
18
// Set the verified address to the calling address
loginToAddressVerified[reqToLogin[_requestId]] = reqToAddress[_requestId];
loginToAddressVerified[reqToLogin[_requestId]] = reqToAddress[_requestId];
4,520