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
7
// Retrieves the "actual" size of loan offer corresponding to particular lender (after excess has been removed) This value would only differ from return value of getLenderOffer()for the same lender if total amount offered > total amount requested and the lender is near the end of the queue This value should only differ from return value of getLenderOffer() for ONE lender in a Market instance /
function actualLenderOffer(address _address, uint _marketId) public view returns (uint) { return markets[_marketId].lenderOffers[_address].sub(calculateExcess(_marketId, _address)); }
function actualLenderOffer(address _address, uint _marketId) public view returns (uint) { return markets[_marketId].lenderOffers[_address].sub(calculateExcess(_marketId, _address)); }
35,447
6
// Converts a JoinPoolRequest into a PoolBalanceChange, with no runtime cost. /
function _toPoolBalanceChange(JoinPoolRequest memory request) private pure returns (PoolBalanceChange memory change)
function _toPoolBalanceChange(JoinPoolRequest memory request) private pure returns (PoolBalanceChange memory change)
12,000
4
// @inheritdoc IERC165 /
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, AccessControl) returns (bool)
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, AccessControl) returns (bool)
8,914
30
// Function to open the factory
function openFactory() external onlyOwner { factoryOpen = true; }
function openFactory() external onlyOwner { factoryOpen = true; }
8,776
220
// every warriors starts from 1 lv (10 level points per level) // PVP rating, every warrior starts with 100 rating / 0 - idle
uint32 action;
uint32 action;
66,270
102
// Sets `value` as allowance of `spender` account over `owner` account's WETH10 token, given `owner` account's signed approval.
/// Emits {Approval} event. /// Requirements: /// - `deadline` must be timestamp in future. /// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments. /// - the signature must use `owner` account's current nonce (see {nonces}). /// - the signer cannot be zero address and must be `owner` account. /// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section]. /// WETH10 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol. function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override { require(block.timestamp <= deadline, "WETH: Expired permit"); uint256 chainId; assembly {chainId := chainid()} bytes32 DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this))); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); bytes32 hash = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(hash, v, r, s); require(signer != address(0) && signer == owner, "WETH: invalid permit"); // _approve(owner, spender, value); allowance[owner][spender] = value; emit Approval(owner, spender, value); }
/// Emits {Approval} event. /// Requirements: /// - `deadline` must be timestamp in future. /// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments. /// - the signature must use `owner` account's current nonce (see {nonces}). /// - the signer cannot be zero address and must be `owner` account. /// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section]. /// WETH10 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol. function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override { require(block.timestamp <= deadline, "WETH: Expired permit"); uint256 chainId; assembly {chainId := chainid()} bytes32 DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), chainId, address(this))); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); bytes32 hash = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(hash, v, r, s); require(signer != address(0) && signer == owner, "WETH: invalid permit"); // _approve(owner, spender, value); allowance[owner][spender] = value; emit Approval(owner, spender, value); }
6,680
37
// AddressSet
struct AddressSet { Set _inner; }
struct AddressSet { Set _inner; }
30,221
34
// NOTE: In practice, it was discovered that <50 was the maximum we've see for this variance
return _migrate(account, amount, 0);
return _migrate(account, amount, 0);
29,030
10
// computes square roots using the babylonian method https:en.wikipedia.org/wiki/Methods_of_computing_square_rootsBabylonian_method
library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } }
library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } }
19,461
28
// todo: check if the external contract is legal whitelist.
whiteListContract = newWhiteList; emit whiteListChanged(newWhiteList);
whiteListContract = newWhiteList; emit whiteListChanged(newWhiteList);
6,477
48
// id => (owner => balance)
mapping (uint256 => mapping(address => uint256)) internal balances;
mapping (uint256 => mapping(address => uint256)) internal balances;
27,439
48
// Pick out the remaining bytes.
uint256 mask = 256 ** (32 - (_length % 32)) - 1; assembly { mstore( dest, or( and(mload(src), not(mask)), and(mload(dest), mask) ) ) }
uint256 mask = 256 ** (32 - (_length % 32)) - 1; assembly { mstore( dest, or( and(mload(src), not(mask)), and(mload(dest), mask) ) ) }
34,495
33
// Check that the auction's endTime has passed
require( idToMarketItem[tokenId].endTime <= block.timestamp, "This auction has not ended yet." );
require( idToMarketItem[tokenId].endTime <= block.timestamp, "This auction has not ended yet." );
25,881
30
// Collects account's received already split funds./accountId The account ID./erc20 The used ERC-20 token./ return amt The collected amount
function _collect(uint256 accountId, IERC20 erc20) internal returns (uint128 amt) { SplitsBalance storage balance = _splitsStorage().splitsStates[accountId].balances[erc20]; amt = balance.collectable; balance.collectable = 0; emit Collected(accountId, erc20, amt); }
function _collect(uint256 accountId, IERC20 erc20) internal returns (uint128 amt) { SplitsBalance storage balance = _splitsStorage().splitsStates[accountId].balances[erc20]; amt = balance.collectable; balance.collectable = 0; emit Collected(accountId, erc20, amt); }
21,464
273
// Tell if a given module is active_id ID of the module to be checked_addr Address of the module to be checked return True if the given module address has the requested ID and is enabled/
function isActive(bytes32 _id, address _addr) external view returns (bool) { Module storage module = allModules[_addr]; return module.id == _id && !module.disabled; }
function isActive(bytes32 _id, address _addr) external view returns (bool) { Module storage module = allModules[_addr]; return module.id == _id && !module.disabled; }
12,889
321
// forfeit stake and retrieve KEEPER /
function forfeit() external returns ( uint ) { Claim memory info = warmupInfo[ msg.sender ]; delete warmupInfo[ msg.sender ]; gonsInWarmup = gonsInWarmup.sub(info.gons); KEEPER.safeTransfer( msg.sender, info.deposit ); return info.deposit; }
function forfeit() external returns ( uint ) { Claim memory info = warmupInfo[ msg.sender ]; delete warmupInfo[ msg.sender ]; gonsInWarmup = gonsInWarmup.sub(info.gons); KEEPER.safeTransfer( msg.sender, info.deposit ); return info.deposit; }
32,900
7
// Reserve chosen token amount
profileStorage.setWithdrawalAmount(identity, amount); emit WithdrawalInitiated(identity, amount, withdrawalTime);
profileStorage.setWithdrawalAmount(identity, amount); emit WithdrawalInitiated(identity, amount, withdrawalTime);
43,937
38
// Returns the current chain name as a string./ return name of the current chain
function CURRENT_CHAIN() public view returns (string memory) { return _toString(CURRENT_CHAIN_B32); }
function CURRENT_CHAIN() public view returns (string memory) { return _toString(CURRENT_CHAIN_B32); }
2,010
19
// Returns the clubs (IDs) associated to a given country. /
function getClubsForCountry (string calldata country) public view returns (uint[] memory)
function getClubsForCountry (string calldata country) public view returns (uint[] memory)
7,625
11
// See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan intomultiple smaller scans if the collection is large enough to causean out-of-gas error (10K pfp collections should be fine). /
function tokensOfOwner(address owner) external view returns (uint256[] memory) { unchecked { uint256 tokenIdsIdx; address currOwnershipAddr; uint256 tokenIdsLength = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenIdsLength); TokenOwnership memory ownership; for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) { ownership = _ownerships[i]; if (ownership.burned) {
function tokensOfOwner(address owner) external view returns (uint256[] memory) { unchecked { uint256 tokenIdsIdx; address currOwnershipAddr; uint256 tokenIdsLength = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenIdsLength); TokenOwnership memory ownership; for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) { ownership = _ownerships[i]; if (ownership.burned) {
3,801
33
// ERC223 additions to ERC20 /
contract Standard223Token is ERC223, StandardToken { //function that is called when a user or another contract wants to transfer funds function transfer(address _to, uint _value, bytes _data) returns (bool success) { //filtering if the target is a contract with bytecode inside it if (!super.transfer(_to, _value)) throw; // do a normal token transfer if (isContract(_to)) return contractFallback(msg.sender, _to, _value, _data); return true; } function transferFrom(address _from, address _to, uint _value, bytes _data) returns (bool success) { if (!super.transferFrom(_from, _to, _value)) throw; // do a normal token transfer if (isContract(_to)) return contractFallback(_from, _to, _value, _data); return true; } function transfer(address _to, uint _value) returns (bool success) { return transfer(_to, _value, new bytes(0)); } function transferFrom(address _from, address _to, uint _value) returns (bool success) { return transferFrom(_from, _to, _value, new bytes(0)); } //function that is called when transaction target is a contract function contractFallback(address _origin, address _to, uint _value, bytes _data) private returns (bool success) { ERC223Receiver reciever = ERC223Receiver(_to); return reciever.tokenFallback(msg.sender, _origin, _value, _data); } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } }
contract Standard223Token is ERC223, StandardToken { //function that is called when a user or another contract wants to transfer funds function transfer(address _to, uint _value, bytes _data) returns (bool success) { //filtering if the target is a contract with bytecode inside it if (!super.transfer(_to, _value)) throw; // do a normal token transfer if (isContract(_to)) return contractFallback(msg.sender, _to, _value, _data); return true; } function transferFrom(address _from, address _to, uint _value, bytes _data) returns (bool success) { if (!super.transferFrom(_from, _to, _value)) throw; // do a normal token transfer if (isContract(_to)) return contractFallback(_from, _to, _value, _data); return true; } function transfer(address _to, uint _value) returns (bool success) { return transfer(_to, _value, new bytes(0)); } function transferFrom(address _from, address _to, uint _value) returns (bool success) { return transferFrom(_from, _to, _value, new bytes(0)); } //function that is called when transaction target is a contract function contractFallback(address _origin, address _to, uint _value, bytes _data) private returns (bool success) { ERC223Receiver reciever = ERC223Receiver(_to); return reciever.tokenFallback(msg.sender, _origin, _value, _data); } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } }
8,314
21
// An array can't have a total length larger than the max uint256 value.
unchecked { i++; }
unchecked { i++; }
25,238
0
// Constructor. _ens The address of the ENS registry. _rootNode The node that this registrar administers. /
constructor(ENS _ens, bytes32 _rootNode) { ens = _ens; rootNode = _rootNode; }
constructor(ENS _ens, bytes32 _rootNode) { ens = _ens; rootNode = _rootNode; }
78,937
16
// Check if the value is less than 0.00001 ETH (10000000000000 wei)
if (weiValue < 10000000000000) { return "0"; }
if (weiValue < 10000000000000) { return "0"; }
4,028
47
// Rate and cap for tier 1
uint256 public tier_rate_1 = 1800; uint256 public tier_cap_1 = 48;
uint256 public tier_rate_1 = 1800; uint256 public tier_cap_1 = 48;
7,802
0
// 0: INACTIVE, 1: PRE_SALE, 2: PUBLIC_SALE
uint256 public SALE_STATE = 0; bytes32 private merkleRoot; mapping(address => uint256) whitelistMints; Counters.Counter private idTracker; string public baseURI;
uint256 public SALE_STATE = 0; bytes32 private merkleRoot; mapping(address => uint256) whitelistMints; Counters.Counter private idTracker; string public baseURI;
77,640
1,016
// Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable/ across time or markets but implied rates are. The goal here is to ensure that the implied rate/ before and after the rate anchor update is the same. Therefore, the market will trade at the same implied/ rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage/ which will hurt the liquidity providers.// The rate anchor will update as the market rolls down to maturity. The calculation is:/ newExchangeRate = e^(lastImpliedRatetimeToMaturity / Constants.IMPLIED_RATE_TIME)/ newAnchor =
function _getRateAnchor( int256 totalfCash, uint256 lastImpliedRate, int256 totalCashUnderlying, int256 rateScalar, uint256 timeToMaturity
function _getRateAnchor( int256 totalfCash, uint256 lastImpliedRate, int256 totalCashUnderlying, int256 rateScalar, uint256 timeToMaturity
35,789
15
// See `WeightedJoinsLib.joinAllTokensInForExactBPTOut`. /
function joinAllTokensInForExactBPTOut(
function joinAllTokensInForExactBPTOut(
18,986
12
// metadata for each of those NFTs is `${baseURIForTokens}/${tokenId}`._encryptedBaseURI The encrypted base URI for the batch of NFTs being lazy minted. return batchIdA unique integer identifier for the batch of NFTs lazy minted together. /
function lazyMint( uint256 _amount, string calldata _baseURIForTokens, bytes calldata _encryptedBaseURI ) public virtual override returns (uint256 batchId) { if (_encryptedBaseURI.length != 0) { _setEncryptedBaseURI(nextTokenIdToLazyMint + _amount, _encryptedBaseURI); }
function lazyMint( uint256 _amount, string calldata _baseURIForTokens, bytes calldata _encryptedBaseURI ) public virtual override returns (uint256 batchId) { if (_encryptedBaseURI.length != 0) { _setEncryptedBaseURI(nextTokenIdToLazyMint + _amount, _encryptedBaseURI); }
6,797
9
// Snapshot of the value of totalStakes, taken immediately after the latest liquidation
uint public totalStakesSnapshot;
uint public totalStakesSnapshot;
28,491
93
// Requests new Riskcoins be made for a given address. The address cannot be a contract, only a simple wallet (with 0 codesize). Contracts must use the Approve, transferFrom pattern and move coins from wallets_user Allows coins to be created and sent to other people return transaction ID which can be viewed in the pending mapping/
_TransID=NewCoinInternal(_user,cast(msg.value),Action.NewRisk);
_TransID=NewCoinInternal(_user,cast(msg.value),Action.NewRisk);
35,195
5
// Set the current contract administrator. account account of contract administrator. /
function setAdmin(address account) external;
function setAdmin(address account) external;
21,428
25
// Require amount greater than 0
require(RatePerCoin[address(token)].exists==true,"token doesnt have a rate"); require(_amount > 0, "amount cannot be 0"); if (stakers[msg.sender].balance[address(token)] > 0) { claimToken(address(token)); }
require(RatePerCoin[address(token)].exists==true,"token doesnt have a rate"); require(_amount > 0, "amount cannot be 0"); if (stakers[msg.sender].balance[address(token)] > 0) { claimToken(address(token)); }
48,358
2
// exchnageRateStored last time we cumulated
uint256 public prevExchnageRateCurrent;
uint256 public prevExchnageRateCurrent;
32,676
15
// Getter function to retrieve subprotocol data/_name Name of the subprotocol to query/ return subprotocolData stored under _name. owner will be set to address(0) if subprotocol does not exist
function getSubprotocol(string calldata _name) external view returns (SubprotocolData memory) { return subprotocols[_name]; }
function getSubprotocol(string calldata _name) external view returns (SubprotocolData memory) { return subprotocols[_name]; }
9,750
24
// remove an address from the operators addr addressreturn true if the address was removed from the operators,false if the address wasn't in the operators in the first place /
function removeAddressFromOperators(address addr) onlyOwner public returns(bool success) { if (operators[addr]) { operators[addr] = false; emit OperatorAddressRemoved(addr); success = true; } }
function removeAddressFromOperators(address addr) onlyOwner public returns(bool success) { if (operators[addr]) { operators[addr] = false; emit OperatorAddressRemoved(addr); success = true; } }
22,966
198
// mint all available claims for FA holders
function holderMintAll() public { uint256[] memory ownedTokens = walletOfFAOwner(msg.sender); for(uint256 i; i < ownedTokens.length; i++) { uint256 _curToken = ownedTokens[i]; //token exist in Acid Apes? If yes, continue. If no, then call holderMint if( _exists(_curToken) ) { continue; } else { holderMint(_curToken, 0); } } }
function holderMintAll() public { uint256[] memory ownedTokens = walletOfFAOwner(msg.sender); for(uint256 i; i < ownedTokens.length; i++) { uint256 _curToken = ownedTokens[i]; //token exist in Acid Apes? If yes, continue. If no, then call holderMint if( _exists(_curToken) ) { continue; } else { holderMint(_curToken, 0); } } }
65,567
140
// unstake p3crv from pickleMasterChef
uint _ratio = pickleJar.getRatio(); _amount = _amount.mul(1e18).div(_ratio); (uint _stakedAmount,) = pickleMasterChef.userInfo(poolId, address(this)); if (_amount > _stakedAmount) { _amount = _stakedAmount; }
uint _ratio = pickleJar.getRatio(); _amount = _amount.mul(1e18).div(_ratio); (uint _stakedAmount,) = pickleMasterChef.userInfo(poolId, address(this)); if (_amount > _stakedAmount) { _amount = _stakedAmount; }
25,240
95
// Ram Vault distributes fees equally amongst staked pools Have fun reading it. Hopefully it's bug-free. God bless.
contract RAMVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 boostAmount; uint256 boostLevel; uint256 spentMultiplierTokens; } // At any point in time, the amount of RAMs entitled to a user but is pending to be distributed is: // // pending reward = (user.amount+user.boostAmount * pool.accRAMPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRAMPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4, User's `boostAmount` gets updated. // 5. Pool's `effectiveAdditionalTokensFromBoosts` gets updated. // 4. User's `rewardDebt` gets updated. // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. RAMs to distribute per block. uint256 accRAMPerShare; // Accumulated RAMs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; uint256 effectiveAdditionalTokensFromBoosts; // Track the total additional accounting staked tokens from boosts. } // The RAM TOKEN! INBUNIERC20 public ram; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes 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; // pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Boosts address public regeneratoraddr; address public teamaddr; uint256 public boostFees; uint256 public boostLevelOneCost; uint256 public boostLevelTwoCost; uint256 public boostLevelThreeCost; uint256 public boostLevelFourCost; uint256 public boostLevelOneMultiplier; uint256 public boostLevelTwoMultiplier; uint256 public boostLevelThreeMultiplier; uint256 public boostLevelFourMultiplier; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } 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 ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); event Boost(address indexed user, uint256 indexed pid, uint256 indexed level); function initialize( address _ram, address _devaddr, address _teamaddr, address _regeneratoraddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 724; ram = INBUNIERC20(_ram); devaddr = _devaddr; teamaddr = _teamaddr; regeneratoraddr = _regeneratoraddr; contractStartBlock = block.number; _superAdmin = superAdmin; // Initial boost multipliers and costs boostLevelOneCost = 5 * 1e18; // 5 RAM tokens boostLevelTwoCost = 15 * 1e18; // 15 RAM tokens boostLevelThreeCost = 30 * 1e18; // 30 RAM tokens boostLevelFourCost = 60 * 1e18; // 60 RAM tokens boostLevelOneMultiplier = 5000000000000000000; // 5% boostLevelTwoMultiplier = 15000000000000000000; // 15% boostLevelThreeMultiplier = 30000000000000000000; // 30% boostLevelFourMultiplier = 60000000000000000000; // 60% } // -------------------------------------------- // Pools // -------------------------------------------- function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing RAM governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accRAMPerShare: 0, withdrawable : _withdrawable, effectiveAdditionalTokensFromBoosts: 0 }) ); } // Update the given pool's RAMs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing RAM governance consensus 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; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing RAM governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // View function to see pending RAMs on frontend. function pendingRam(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRAMPerShare = pool.accRAMPerShare; uint256 effectiveAmount = user.amount.add(user.boostAmount); return effectiveAmount.mul(accRAMPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the RAM token. // ---- uint256 private ramBalance; function addPendingRewards(uint256 _amount) public { uint256 newRewards = _amount; // uint256 newRewards = ram.balanceOf(_amount).sub(ramBalance); if(newRewards > 0) { // ramBalance = ram.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 ramRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } ramRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 ramRewardFee = ramRewardWhole.mul(DEV_FEE).div(10000); uint256 ramRewardToDistribute = ramRewardWhole.sub(ramRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(ramRewardFee); // Add pool's effective additional token amount from boosts uint256 effectivePoolStakedSupply = tokenSupply.add(pool.effectiveAdditionalTokensFromBoosts); // Calculate RAMPerShare using effective pool staked supply (not just total supply) pool.accRAMPerShare = pool.accRAMPerShare.add(ramRewardToDistribute.mul(1e12).div(effectivePoolStakedSupply)); } // Deposit tokens to RamVault for RAM allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens to user updateAndPayOutPending(_pid, msg.sender); // save gas if(_amount > 0) { pool.token.transferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // Users that have bought multipliers will have an extra balance added to their stake according to the boost multiplier. if (user.boostLevel > 0) { uint256 prevBalancesAccounting = user.boostAmount; // Calculate and set user's new accounting balance uint256 accTotalMultiplier = getTotalMultiplier(user.boostLevel); uint256 newBalancesAccounting = user.amount .mul(accTotalMultiplier) .div(1e18) .sub(user.amount); user.boostAmount = newBalancesAccounting; // Adjust total accounting supply accordingly uint256 diffBalancesAccounting = newBalancesAccounting.sub(prevBalancesAccounting); pool.effectiveAdditionalTokensFromBoosts = pool.effectiveAdditionalTokensFromBoosts.add(diffBalancesAccounting); } } uint256 effectiveAmount = user.amount.add(user.boostAmount); user.rewardDebt = effectiveAmount.mul(pool.accRAMPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.transferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address // Users that have bought multipliers will have an extra balance added to their stake according to the boost multiplier. if (user.boostLevel > 0) { uint256 prevBalancesAccounting = user.boostAmount; // Calculate and set user's new accounting balance uint256 accTotalMultiplier = getTotalMultiplier(user.boostLevel); uint256 newBalancesAccounting = user.amount .mul(accTotalMultiplier) .div(1e18) .sub(user.amount); user.boostAmount = newBalancesAccounting; // Adjust total accounting supply accordingly uint256 diffBalancesAccounting = newBalancesAccounting.sub(prevBalancesAccounting); pool.effectiveAdditionalTokensFromBoosts = pool.effectiveAdditionalTokensFromBoosts.add(diffBalancesAccounting); } } uint256 effectiveAmount = user.amount.add(user.boostAmount); user.rewardDebt = effectiveAmount.mul(pool.accRAMPerShare).div(1e12); // This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from RamVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming RAM farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); // Users who have bought multipliers will have their accounting balances readjusted. if (user.boostLevel > 0) { // The previous extra balance user had uint256 prevBalancesAccounting = user.boostAmount; // Calculate and set user's new accounting balance uint256 accTotalMultiplier = getTotalMultiplier(user.boostLevel); uint256 newBalancesAccounting = user.amount .mul(accTotalMultiplier) .div(1e18) .sub(user.amount); user.boostAmount = newBalancesAccounting; // Subtract the withdrawn amount from the accounting balance // If all tokens are withdrawn the balance will be 0. uint256 diffBalancesAccounting = prevBalancesAccounting.sub(newBalancesAccounting); pool.effectiveAdditionalTokensFromBoosts = pool.effectiveAdditionalTokensFromBoosts.sub(diffBalancesAccounting); } } uint256 effectiveAmount = user.amount.add(user.boostAmount); user.rewardDebt = effectiveAmount.mul(pool.accRAMPerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingRam(_pid, from); if(pending > 0) { safeRamTransfer(from, pending); } } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.boostAmount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // -------------------------------------------- // Boosts // -------------------------------------------- // Purchase a multiplier level for an individual user for an individual pool, same level cannot be purchased twice. function purchase(uint256 _pid, uint256 level) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require( level > user.boostLevel, "Cannot downgrade level or same level" ); // Cost will be reduced by the amount already spent on multipliers. uint256 cost = calculateCost(level); uint256 finalCost = cost.sub(user.spentMultiplierTokens); // Transfer RAM tokens to the contract require(ram.transferFrom(msg.sender, address(this), finalCost), "Transfer failed"); // Update balances and level user.spentMultiplierTokens = user.spentMultiplierTokens.add(finalCost); user.boostLevel = level; // If user has staked balances, then set their new accounting balance if (user.amount > 0) { // Get the new multiplier uint256 accTotalMultiplier = getTotalMultiplier(level); // Calculate new accounting balance uint256 newAccountingAmount = user.amount .mul(accTotalMultiplier) .div(1e18) .div(100); // Get the user's previous accounting balance uint256 prevBalancesAccounting = user.boostAmount; // Set the user' new accounting balance user.boostAmount = newAccountingAmount; // Get the difference to adjust the total accounting balance uint256 diffBalancesAccounting = newAccountingAmount.sub(prevBalancesAccounting); pool.effectiveAdditionalTokensFromBoosts = pool.effectiveAdditionalTokensFromBoosts.add(diffBalancesAccounting); } boostFees = boostFees.add(finalCost); emit Boost(msg.sender, _pid, level); } // Returns the multiplier for user. function getTotalMultiplier(uint256 boostLevel) public view returns (uint256) { uint256 boostMultiplier = 0; if (boostLevel == 1) { boostMultiplier = boostLevelOneMultiplier; } else if (boostLevel == 2) { boostMultiplier = boostLevelTwoMultiplier; } else if (boostLevel == 3) { boostMultiplier = boostLevelThreeMultiplier; } else if (boostLevel == 4) { boostMultiplier = boostLevelFourMultiplier; } return boostMultiplier; } // Calculate the cost for purchasing a boost. function calculateCost(uint256 level) public view returns (uint256) { if (level == 1) { return boostLevelOneCost; } else if (level == 2) { return boostLevelTwoCost; } else if (level == 3) { return boostLevelThreeCost; } else if (level == 4) { return boostLevelFourCost; } } // Returns the users current multiplier level function getLevel(address account, uint256 pid) external view returns (uint256) { UserInfo memory user = userInfo[pid][account]; return user.boostLevel; } // Return the amount spent on multipliers, used for subtracting for future purchases. function getSpent(address account, uint256 pid) external view returns (uint256) { UserInfo memory user = userInfo[pid][account]; return user.spentMultiplierTokens; } // Distributes fees to devs and protocol function distributeFees() public { // Reset taxes to 0 before distributing any funds uint256 totalBoostDistAmt = boostFees; boostFees = 0; // Distribute taxes to regenerator and team 50/50% uint256 halfDistAmt = totalBoostDistAmt.div(2); if (halfDistAmt > 0) { // 50% to regenerator require(ram.transfer(regeneratoraddr, halfDistAmt), "Transfer failed."); // 70% of the other 50% to devs uint256 devDistAmt = halfDistAmt.mul(70).div(100); if (devDistAmt > 0) { require(ram.transfer(devaddr, devDistAmt), "Transfer failed."); } // 30% of the other 50% to team uint256 teamDistAmt = halfDistAmt.mul(30).div(100); if (teamDistAmt > 0) { require(ram.transfer(teamaddr, teamDistAmt), "Transfer failed."); } } } function updateBoosts( uint256[] memory _boostMultipliers, uint256[] memory _boostCosts ) public onlyOwner { require(_boostMultipliers.length == 4, "Must specify 4 multipliers"); require(_boostCosts.length == 4, "Must specify 4 multipliers"); // Update boost costs boostLevelOneCost = _boostCosts[0]; boostLevelTwoCost = _boostCosts[1]; boostLevelThreeCost = _boostCosts[2]; boostLevelFourCost = _boostCosts[3]; // Update boost multipliers boostLevelOneMultiplier = _boostMultipliers[0]; boostLevelTwoMultiplier = _boostMultipliers[1]; boostLevelThreeMultiplier = _boostMultipliers[2]; boostLevelFourMultiplier = _boostMultipliers[3]; } // -------------------------------------------- // Utils // -------------------------------------------- // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing RAM governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Safe ram transfer function, just in case if rounding error causes pool to not have enough RAMs. function safeRamTransfer(address _to, uint256 _amount) internal { uint256 ramBal = ram.balanceOf(address(this)); if (_amount > ramBal) { ram.transfer(_to, ramBal); ramBalance = ram.balanceOf(address(this)); } else { ram.transfer(_to, _amount); ramBalance = ram.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 devDistAmt; uint256 teamDistAmt; uint256 ramBal = ram.balanceOf(address(this)); if (pending_DEV_rewards > ramBal) { devDistAmt = ramBal.mul(70).div(100); teamDistAmt = ramBal.mul(30).div(100); } else { devDistAmt = pending_DEV_rewards.mul(70).div(100); teamDistAmt = pending_DEV_rewards.mul(30).div(100); } if (devDistAmt > 0) { ram.transfer(devaddr, devDistAmt); } if (teamDistAmt > 0) { ram.transfer(teamaddr, teamDistAmt);} ramBalance = ram.balanceOf(address(this)); pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing RAM governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } // -------------------------------------------- // Admin // -------------------------------------------- address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
contract RAMVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 boostAmount; uint256 boostLevel; uint256 spentMultiplierTokens; } // At any point in time, the amount of RAMs entitled to a user but is pending to be distributed is: // // pending reward = (user.amount+user.boostAmount * pool.accRAMPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRAMPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4, User's `boostAmount` gets updated. // 5. Pool's `effectiveAdditionalTokensFromBoosts` gets updated. // 4. User's `rewardDebt` gets updated. // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. RAMs to distribute per block. uint256 accRAMPerShare; // Accumulated RAMs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; uint256 effectiveAdditionalTokensFromBoosts; // Track the total additional accounting staked tokens from boosts. } // The RAM TOKEN! INBUNIERC20 public ram; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes 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; // pending rewards awaiting anyone to massUpdate uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Boosts address public regeneratoraddr; address public teamaddr; uint256 public boostFees; uint256 public boostLevelOneCost; uint256 public boostLevelTwoCost; uint256 public boostLevelThreeCost; uint256 public boostLevelFourCost; uint256 public boostLevelOneMultiplier; uint256 public boostLevelTwoMultiplier; uint256 public boostLevelThreeMultiplier; uint256 public boostLevelFourMultiplier; // Returns fees generated since start of this contract function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); } // Returns averge fees in this epoch function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function startNewEpoch() public { require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } 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 ); event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); event Boost(address indexed user, uint256 indexed pid, uint256 indexed level); function initialize( address _ram, address _devaddr, address _teamaddr, address _regeneratoraddr, address superAdmin ) public initializer { OwnableUpgradeSafe.__Ownable_init(); DEV_FEE = 724; ram = INBUNIERC20(_ram); devaddr = _devaddr; teamaddr = _teamaddr; regeneratoraddr = _regeneratoraddr; contractStartBlock = block.number; _superAdmin = superAdmin; // Initial boost multipliers and costs boostLevelOneCost = 5 * 1e18; // 5 RAM tokens boostLevelTwoCost = 15 * 1e18; // 15 RAM tokens boostLevelThreeCost = 30 * 1e18; // 30 RAM tokens boostLevelFourCost = 60 * 1e18; // 60 RAM tokens boostLevelOneMultiplier = 5000000000000000000; // 5% boostLevelTwoMultiplier = 15000000000000000000; // 15% boostLevelThreeMultiplier = 30000000000000000000; // 30% boostLevelFourMultiplier = 60000000000000000000; // 60% } // -------------------------------------------- // Pools // -------------------------------------------- function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing RAM governance consensus function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accRAMPerShare: 0, withdrawable : _withdrawable, effectiveAdditionalTokensFromBoosts: 0 }) ); } // Update the given pool's RAMs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing RAM governance consensus 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; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing RAM governance consensus function setPoolWithdrawable( uint256 _pid, bool _withdrawable ) public onlyOwner { poolInfo[_pid].withdrawable = _withdrawable; } // View function to see pending RAMs on frontend. function pendingRam(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRAMPerShare = pool.accRAMPerShare; uint256 effectiveAmount = user.amount.add(user.boostAmount); return effectiveAmount.mul(accRAMPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { console.log("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.add(updatePool(pid)); } pendingRewards = pendingRewards.sub(allRewards); } // ---- // Function that adds pending rewards, called by the RAM token. // ---- uint256 private ramBalance; function addPendingRewards(uint256 _amount) public { uint256 newRewards = _amount; // uint256 newRewards = ram.balanceOf(_amount).sub(ramBalance); if(newRewards > 0) { // ramBalance = ram.balanceOf(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.add(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) internal returns (uint256 ramRewardWhole) { PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.balanceOf(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } ramRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get .div(totalAllocPoint); // we can do this because pools are only mass updated uint256 ramRewardFee = ramRewardWhole.mul(DEV_FEE).div(10000); uint256 ramRewardToDistribute = ramRewardWhole.sub(ramRewardFee); pending_DEV_rewards = pending_DEV_rewards.add(ramRewardFee); // Add pool's effective additional token amount from boosts uint256 effectivePoolStakedSupply = tokenSupply.add(pool.effectiveAdditionalTokensFromBoosts); // Calculate RAMPerShare using effective pool staked supply (not just total supply) pool.accRAMPerShare = pool.accRAMPerShare.add(ramRewardToDistribute.mul(1e12).div(effectivePoolStakedSupply)); } // Deposit tokens to RamVault for RAM allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; massUpdatePools(); // Transfer pending tokens to user updateAndPayOutPending(_pid, msg.sender); // save gas if(_amount > 0) { pool.token.transferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // Users that have bought multipliers will have an extra balance added to their stake according to the boost multiplier. if (user.boostLevel > 0) { uint256 prevBalancesAccounting = user.boostAmount; // Calculate and set user's new accounting balance uint256 accTotalMultiplier = getTotalMultiplier(user.boostLevel); uint256 newBalancesAccounting = user.amount .mul(accTotalMultiplier) .div(1e18) .sub(user.amount); user.boostAmount = newBalancesAccounting; // Adjust total accounting supply accordingly uint256 diffBalancesAccounting = newBalancesAccounting.sub(prevBalancesAccounting); pool.effectiveAdditionalTokensFromBoosts = pool.effectiveAdditionalTokensFromBoosts.add(diffBalancesAccounting); } } uint256 effectiveAmount = user.amount.add(user.boostAmount); user.rewardDebt = effectiveAmount.mul(pool.accRAMPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; massUpdatePools(); // Transfer pending tokens // to user updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.transferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); // This is depositedFor address // Users that have bought multipliers will have an extra balance added to their stake according to the boost multiplier. if (user.boostLevel > 0) { uint256 prevBalancesAccounting = user.boostAmount; // Calculate and set user's new accounting balance uint256 accTotalMultiplier = getTotalMultiplier(user.boostLevel); uint256 newBalancesAccounting = user.amount .mul(accTotalMultiplier) .div(1e18) .sub(user.amount); user.boostAmount = newBalancesAccounting; // Adjust total accounting supply accordingly uint256 diffBalancesAccounting = newBalancesAccounting.sub(prevBalancesAccounting); pool.effectiveAdditionalTokensFromBoosts = pool.effectiveAdditionalTokensFromBoosts.add(diffBalancesAccounting); } } uint256 effectiveAmount = user.amount.add(user.boostAmount); user.rewardDebt = effectiveAmount.mul(pool.accRAMPerShare).div(1e12); // This is deposited for address emit Deposit(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); _withdraw(_pid, _amount, owner, msg.sender); } // Withdraw tokens from RamVault. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); massUpdatePools(); updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming RAM farmed if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.token.safeTransfer(address(to), _amount); // Users who have bought multipliers will have their accounting balances readjusted. if (user.boostLevel > 0) { // The previous extra balance user had uint256 prevBalancesAccounting = user.boostAmount; // Calculate and set user's new accounting balance uint256 accTotalMultiplier = getTotalMultiplier(user.boostLevel); uint256 newBalancesAccounting = user.amount .mul(accTotalMultiplier) .div(1e18) .sub(user.amount); user.boostAmount = newBalancesAccounting; // Subtract the withdrawn amount from the accounting balance // If all tokens are withdrawn the balance will be 0. uint256 diffBalancesAccounting = prevBalancesAccounting.sub(newBalancesAccounting); pool.effectiveAdditionalTokensFromBoosts = pool.effectiveAdditionalTokensFromBoosts.sub(diffBalancesAccounting); } } uint256 effectiveAmount = user.amount.add(user.boostAmount); user.rewardDebt = effectiveAmount.mul(pool.accRAMPerShare).div(1e12); emit Withdraw(to, _pid, _amount); } function updateAndPayOutPending(uint256 _pid, address from) internal { uint256 pending = pendingRam(_pid, from); if(pending > 0) { safeRamTransfer(from, pending); } } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.boostAmount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // -------------------------------------------- // Boosts // -------------------------------------------- // Purchase a multiplier level for an individual user for an individual pool, same level cannot be purchased twice. function purchase(uint256 _pid, uint256 level) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require( level > user.boostLevel, "Cannot downgrade level or same level" ); // Cost will be reduced by the amount already spent on multipliers. uint256 cost = calculateCost(level); uint256 finalCost = cost.sub(user.spentMultiplierTokens); // Transfer RAM tokens to the contract require(ram.transferFrom(msg.sender, address(this), finalCost), "Transfer failed"); // Update balances and level user.spentMultiplierTokens = user.spentMultiplierTokens.add(finalCost); user.boostLevel = level; // If user has staked balances, then set their new accounting balance if (user.amount > 0) { // Get the new multiplier uint256 accTotalMultiplier = getTotalMultiplier(level); // Calculate new accounting balance uint256 newAccountingAmount = user.amount .mul(accTotalMultiplier) .div(1e18) .div(100); // Get the user's previous accounting balance uint256 prevBalancesAccounting = user.boostAmount; // Set the user' new accounting balance user.boostAmount = newAccountingAmount; // Get the difference to adjust the total accounting balance uint256 diffBalancesAccounting = newAccountingAmount.sub(prevBalancesAccounting); pool.effectiveAdditionalTokensFromBoosts = pool.effectiveAdditionalTokensFromBoosts.add(diffBalancesAccounting); } boostFees = boostFees.add(finalCost); emit Boost(msg.sender, _pid, level); } // Returns the multiplier for user. function getTotalMultiplier(uint256 boostLevel) public view returns (uint256) { uint256 boostMultiplier = 0; if (boostLevel == 1) { boostMultiplier = boostLevelOneMultiplier; } else if (boostLevel == 2) { boostMultiplier = boostLevelTwoMultiplier; } else if (boostLevel == 3) { boostMultiplier = boostLevelThreeMultiplier; } else if (boostLevel == 4) { boostMultiplier = boostLevelFourMultiplier; } return boostMultiplier; } // Calculate the cost for purchasing a boost. function calculateCost(uint256 level) public view returns (uint256) { if (level == 1) { return boostLevelOneCost; } else if (level == 2) { return boostLevelTwoCost; } else if (level == 3) { return boostLevelThreeCost; } else if (level == 4) { return boostLevelFourCost; } } // Returns the users current multiplier level function getLevel(address account, uint256 pid) external view returns (uint256) { UserInfo memory user = userInfo[pid][account]; return user.boostLevel; } // Return the amount spent on multipliers, used for subtracting for future purchases. function getSpent(address account, uint256 pid) external view returns (uint256) { UserInfo memory user = userInfo[pid][account]; return user.spentMultiplierTokens; } // Distributes fees to devs and protocol function distributeFees() public { // Reset taxes to 0 before distributing any funds uint256 totalBoostDistAmt = boostFees; boostFees = 0; // Distribute taxes to regenerator and team 50/50% uint256 halfDistAmt = totalBoostDistAmt.div(2); if (halfDistAmt > 0) { // 50% to regenerator require(ram.transfer(regeneratoraddr, halfDistAmt), "Transfer failed."); // 70% of the other 50% to devs uint256 devDistAmt = halfDistAmt.mul(70).div(100); if (devDistAmt > 0) { require(ram.transfer(devaddr, devDistAmt), "Transfer failed."); } // 30% of the other 50% to team uint256 teamDistAmt = halfDistAmt.mul(30).div(100); if (teamDistAmt > 0) { require(ram.transfer(teamaddr, teamDistAmt), "Transfer failed."); } } } function updateBoosts( uint256[] memory _boostMultipliers, uint256[] memory _boostCosts ) public onlyOwner { require(_boostMultipliers.length == 4, "Must specify 4 multipliers"); require(_boostCosts.length == 4, "Must specify 4 multipliers"); // Update boost costs boostLevelOneCost = _boostCosts[0]; boostLevelTwoCost = _boostCosts[1]; boostLevelThreeCost = _boostCosts[2]; boostLevelFourCost = _boostCosts[3]; // Update boost multipliers boostLevelOneMultiplier = _boostMultipliers[0]; boostLevelTwoMultiplier = _boostMultipliers[1]; boostLevelThreeMultiplier = _boostMultipliers[2]; boostLevelFourMultiplier = _boostMultipliers[3]; } // -------------------------------------------- // Utils // -------------------------------------------- // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing RAM governance consensus uint16 DEV_FEE; function setDevFee(uint16 _DEV_FEE) public onlyOwner { require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).approve(contractAddress, _amount); } function isContract(address addr) public returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } // Safe ram transfer function, just in case if rounding error causes pool to not have enough RAMs. function safeRamTransfer(address _to, uint256 _amount) internal { uint256 ramBal = ram.balanceOf(address(this)); if (_amount > ramBal) { ram.transfer(_to, ramBal); ramBalance = ram.balanceOf(address(this)); } else { ram.transfer(_to, _amount); ramBalance = ram.balanceOf(address(this)); } //Avoids possible recursion loop // proxy? transferDevFee(); } function transferDevFee() public { if(pending_DEV_rewards == 0) return; uint256 devDistAmt; uint256 teamDistAmt; uint256 ramBal = ram.balanceOf(address(this)); if (pending_DEV_rewards > ramBal) { devDistAmt = ramBal.mul(70).div(100); teamDistAmt = ramBal.mul(30).div(100); } else { devDistAmt = pending_DEV_rewards.mul(70).div(100); teamDistAmt = pending_DEV_rewards.mul(30).div(100); } if (devDistAmt > 0) { ram.transfer(devaddr, devDistAmt); } if (teamDistAmt > 0) { ram.transfer(teamaddr, teamDistAmt);} ramBalance = ram.balanceOf(address(this)); pending_DEV_rewards = 0; } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing RAM governance token holders to do this functions. function setDevFeeReciever(address _devaddr) public onlyOwner { devaddr = _devaddr; } // -------------------------------------------- // Admin // -------------------------------------------- address private _superAdmin; event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current super admin */ function superAdmin() public view returns (address) { return _superAdmin; } /** * @dev Throws if called by any account other than the superAdmin */ modifier onlySuperAdmin() { require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function burnSuperAdmin() public virtual onlySuperAdmin { emit SuperAdminTransfered(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; } }
12,920
41
// Performs checkpoint for Arbitrum gauge, forwarding ETH to pay bridge costs. /
function _checkpointArbitrumGauge(address gauge) private { uint256 checkpointCost = ArbitrumRootGauge(gauge).getTotalBridgeCost(); _authorizerAdaptorEntrypoint.performAction{ value: checkpointCost }( gauge, abi.encodeWithSelector(IStakelessGauge.checkpoint.selector) ); }
function _checkpointArbitrumGauge(address gauge) private { uint256 checkpointCost = ArbitrumRootGauge(gauge).getTotalBridgeCost(); _authorizerAdaptorEntrypoint.performAction{ value: checkpointCost }( gauge, abi.encodeWithSelector(IStakelessGauge.checkpoint.selector) ); }
34,481
144
// Returns the packed ownership data of 'tokenId'. /
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { uint256 packed = _packedOwnerships[curr]; // If not burned. if (packed & _BITMASK_BURNED == 0) { // Invariant: // There will always be an initialized ownership slot // (i.e. 'ownership.addr != address(0) && ownership.burned == false') // before an unintialized ownership slot // (i.e. 'ownership.addr == address(0) && ownership.burned == false') // Hence, 'curr' will not underflow. // // We can directly compare the packed value. // If the address is zero, packed will be zero. while (packed == 0) { packed = _packedOwnerships[--curr]; } return packed; } } } revert OwnerQueryForNonexistentToken(); }
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { uint256 packed = _packedOwnerships[curr]; // If not burned. if (packed & _BITMASK_BURNED == 0) { // Invariant: // There will always be an initialized ownership slot // (i.e. 'ownership.addr != address(0) && ownership.burned == false') // before an unintialized ownership slot // (i.e. 'ownership.addr == address(0) && ownership.burned == false') // Hence, 'curr' will not underflow. // // We can directly compare the packed value. // If the address is zero, packed will be zero. while (packed == 0) { packed = _packedOwnerships[--curr]; } return packed; } } } revert OwnerQueryForNonexistentToken(); }
36,607
264
// adding referrer if any
if(_referrer != address(0) && referrer[msg.sender] == address(0)){ referrer[msg.sender] = _referrer; }
if(_referrer != address(0) && referrer[msg.sender] == address(0)){ referrer[msg.sender] = _referrer; }
20,361
127
// Transfer wBTC to strategy so strategy can complete the swap.
wBTC.safeTransfer(strategy, _amount); uint256 amount = ISwapStrategy(strategy).swapTokens(address(wBTC), address(renBTC), _amount, _slippage); require(amount > minAmount, "swapped amount less than min amount");
wBTC.safeTransfer(strategy, _amount); uint256 amount = ISwapStrategy(strategy).swapTokens(address(wBTC), address(renBTC), _amount, _slippage); require(amount > minAmount, "swapped amount less than min amount");
48,784
13
// tip images
function tipImageOwner(uint _id) public payable { //validate require(_id > 0 && _id <= imageCount); //pickimage with _id Image memory _image = images[_id]; address payable _author = _image.author; //we need to pay author address(_author).transfer(msg.value); //increment tip for image _image.tipAmount = _image.tipAmount + msg.value; //store updated image back images[_id] = _image; emit ImageTipped(_id, _image.hash, _image.description, _image.tipAmount, _author); }
function tipImageOwner(uint _id) public payable { //validate require(_id > 0 && _id <= imageCount); //pickimage with _id Image memory _image = images[_id]; address payable _author = _image.author; //we need to pay author address(_author).transfer(msg.value); //increment tip for image _image.tipAmount = _image.tipAmount + msg.value; //store updated image back images[_id] = _image; emit ImageTipped(_id, _image.hash, _image.description, _image.tipAmount, _author); }
38,045
13
// Storage position of the owner of the contract
bytes32 private constant proxyOwnerPosition = keccak256("org.zeppelinos.proxy.owner");
bytes32 private constant proxyOwnerPosition = keccak256("org.zeppelinos.proxy.owner");
31,421
31
// see {Pausable _unpause} Requirements : - caller should be owner /
function unpause() external onlyOwner { _unpause(); }
function unpause() external onlyOwner { _unpause(); }
5,034
20
// a {address}The address of the authorised individual
modifier onlyBy(address a) { if (msg.sender != a) revert(); _; }
modifier onlyBy(address a) { if (msg.sender != a) revert(); _; }
42,225
30
// SSP
list(PRYCTO,0x624d520BAB2E4aD83935Fa503fB130614374E850);
list(PRYCTO,0x624d520BAB2E4aD83935Fa503fB130614374E850);
29,082
8
// refund whatever wasn't deposited.
uint256 refund = amount.sub(amountDeposited);
uint256 refund = amount.sub(amountDeposited);
32,374
23
// Sets the app_appNickname Nickname (e.g. twitter)_appId ID (e.g. 1)/
function setApp( string _appNickname, uint _appId ) external onlyOwner
function setApp( string _appNickname, uint _appId ) external onlyOwner
75,826
93
// Validates the source and destination is not 0 address. /
require(_from != address(0), "this is illegal address"); require(_to != address(0), "this is illegal address"); require(_value != 0, "illegal transfer value");
require(_from != address(0), "this is illegal address"); require(_to != address(0), "this is illegal address"); require(_value != 0, "illegal transfer value");
2,824
56
// delivery token for buyer/a start point/b end point
function deliveryToken(uint a, uint b) public onlyOwner validOriginalBuyPrice
function deliveryToken(uint a, uint b) public onlyOwner validOriginalBuyPrice
35,041
9
// BAYC whitelist sale data
createPresale(4, 0.135 ether, 1000);
createPresale(4, 0.135 ether, 1000);
4,444
23
// Performs the proxy call via a delegatecall.
function _doProxyCall() internal { address impl = _getImplementation(); require(impl != address(0), "Proxy: implementation not initialized"); assembly { // Copy calldata into memory at 0x0....calldatasize. calldatacopy(0x0, 0x0, calldatasize()) // Perform the delegatecall, make sure to pass all available gas. let success := delegatecall(gas(), impl, 0x0, calldatasize(), 0x0, 0x0) // Copy returndata into memory at 0x0....returndatasize. Note that this *will* // overwrite the calldata that we just copied into memory but that doesn't really // matter because we'll be returning in a second anyway. returndatacopy(0x0, 0x0, returndatasize()) // Success == 0 means a revert. We'll revert too and pass the data up. if iszero(success) { revert(0x0, returndatasize()) } // Otherwise we'll just return and pass the data up. return(0x0, returndatasize()) } }
function _doProxyCall() internal { address impl = _getImplementation(); require(impl != address(0), "Proxy: implementation not initialized"); assembly { // Copy calldata into memory at 0x0....calldatasize. calldatacopy(0x0, 0x0, calldatasize()) // Perform the delegatecall, make sure to pass all available gas. let success := delegatecall(gas(), impl, 0x0, calldatasize(), 0x0, 0x0) // Copy returndata into memory at 0x0....returndatasize. Note that this *will* // overwrite the calldata that we just copied into memory but that doesn't really // matter because we'll be returning in a second anyway. returndatacopy(0x0, 0x0, returndatasize()) // Success == 0 means a revert. We'll revert too and pass the data up. if iszero(success) { revert(0x0, returndatasize()) } // Otherwise we'll just return and pass the data up. return(0x0, returndatasize()) } }
41,596
14
// REVIEWSECTION
reviews[productId].push(Review(user,productId,rating,comment,0)); userReviews[user].push(productId); products[productId].totalRating += rating; products[productId].numReviews++; emit ReviewAdded(productId,user,rating,comment); reviewsCounter++;
reviews[productId].push(Review(user,productId,rating,comment,0)); userReviews[user].push(productId); products[productId].totalRating += rating; products[productId].numReviews++; emit ReviewAdded(productId,user,rating,comment); reviewsCounter++;
22,531
4
// Governed function to create a new NFT Cannot mint any NFT more than once
function mint( address _account, uint256 _id, uint256 _amount, bytes memory _data ) public override(LodgeToken, ILodge)
function mint( address _account, uint256 _id, uint256 _amount, bytes memory _data ) public override(LodgeToken, ILodge)
7,076
4
// Opening Move Event/Emitted when a player makes an opening move (there are no other/ moves stored in the contract), or the player makes the same move that is/ already been played, in which case the play 'gets in line' for resolution./ The contract will have a limit at which only so many duplicate moves can/ be made before the contract reverts further attempts.The limit will be/ indicated by turning the `maxReached` value `true`.Without plays/ resolving, any more duplicate plays will be reverted by the contract./when `maxReached` returns `false`, the UI can allow additional duplicate/ plays.When it reads `true` the UI
event OpeningMove(Move move, bool maxReached);
event OpeningMove(Move move, bool maxReached);
43,382
69
// Method to create any offer for any NFT.
function makeAnOffer( uint256 tokenID, address _mintableToken, address _erc20Token, uint256 amount
function makeAnOffer( uint256 tokenID, address _mintableToken, address _erc20Token, uint256 amount
13,888
237
// can only be ran once
require(activated_ == false, "it is already activated");
require(activated_ == false, "it is already activated");
2,092
98
// make sure we have enough fUSD tokens to cover the sale what is the practical meaning of minting fUSD here if the pool is depleted?
readyBalance(fUsdToken, sellValueExFee, msg.sender);
readyBalance(fUsdToken, sellValueExFee, msg.sender);
41,162
11
// in line assembly code
assembly { codeSize := extcodesize(_addr) }
assembly { codeSize := extcodesize(_addr) }
20,652
71
// Initilizes the token with given address and allocates tokens.
* @param _token {address} the address of token contract. */ function setToken(address _token) external onlyOwner whenPaused { require(state == State.NEW); require(_token != address(0)); require(token == address(0)); token = BitImageToken(_token); tokenIcoAllocated = token.totalSupply().mul(62).div(100); tokenTeamAllocated = token.totalSupply().mul(18).div(100); tokenAdvisorsAllocated = token.totalSupply().mul(4).div(100); tokenBountyAllocated = token.totalSupply().mul(6).div(100); tokenReservationAllocated = token.totalSupply().mul(10).div(100); require(token.totalSupply() == tokenIcoAllocated.add(tokenTeamAllocated).add(tokenAdvisorsAllocated).add(tokenBountyAllocated).add(tokenReservationAllocated)); }
* @param _token {address} the address of token contract. */ function setToken(address _token) external onlyOwner whenPaused { require(state == State.NEW); require(_token != address(0)); require(token == address(0)); token = BitImageToken(_token); tokenIcoAllocated = token.totalSupply().mul(62).div(100); tokenTeamAllocated = token.totalSupply().mul(18).div(100); tokenAdvisorsAllocated = token.totalSupply().mul(4).div(100); tokenBountyAllocated = token.totalSupply().mul(6).div(100); tokenReservationAllocated = token.totalSupply().mul(10).div(100); require(token.totalSupply() == tokenIcoAllocated.add(tokenTeamAllocated).add(tokenAdvisorsAllocated).add(tokenBountyAllocated).add(tokenReservationAllocated)); }
39,214
259
// Calculates floor(xy÷denominator) with full precision.//An extension of "mulDiv" for signed numbers. Works by computing the signs and the absolute values separately.// Requirements:/ - None of the inputs can be type(int256).min./ - The result must fit within int256.//x The multiplicand as an int256./y The multiplier as an int256./denominator The divisor as an int256./ return result The result as an int256.
function mulDivSigned( int256 x, int256 y, int256 denominator
function mulDivSigned( int256 x, int256 y, int256 denominator
22,571
21
// Returns true if the specified address is whitelisted. _address The address to check for whitelisting status. /
function isWhitelisted(address _address) public view returns (bool) { return whitelist[_address]; }
function isWhitelisted(address _address) public view returns (bool) { return whitelist[_address]; }
28,627
191
// Disables the reward feature.
* Emits a {DisabledReward} event. * * Requirements: * * - reward feature mush be enabled. */ function disableReward() public onlyOwner { require(_rewardEnabled, "Reward feature is already disabled."); setTaxReward(0, 0); _rewardEnabled = false; emit DisabledReward(); }
* Emits a {DisabledReward} event. * * Requirements: * * - reward feature mush be enabled. */ function disableReward() public onlyOwner { require(_rewardEnabled, "Reward feature is already disabled."); setTaxReward(0, 0); _rewardEnabled = false; emit DisabledReward(); }
25,274
66
// get reward balance and safety check
_rewardToken = IERC20Detailed(_reward); _rewardBalance = _rewardToken.balanceOf(address(this)); if (_rewardBalance == 0) continue; _router = IUniswapV2Router02( rewardRouter[_reward] );
_rewardToken = IERC20Detailed(_reward); _rewardBalance = _rewardToken.balanceOf(address(this)); if (_rewardBalance == 0) continue; _router = IUniswapV2Router02( rewardRouter[_reward] );
67,313
144
// Library used to query support of an interface declared via {IERC165}. As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
12,775
27
// This will be the getter function that everyone can call to check the charity pictureURL.Parameters of this function will include uint charityId /
function getCharityPictureURL( uint256 charityId ) public view returns (string memory)
function getCharityPictureURL( uint256 charityId ) public view returns (string memory)
35,775
167
// funds withdrawal for owner
function withdrawEther() external onlyOwner { payable(msg.sender).transfer(address(this).balance); }
function withdrawEther() external onlyOwner { payable(msg.sender).transfer(address(this).balance); }
28,797
5
// Class
contract SimpleStorage { // This wiil get initialize to 0! uint256 favoriteNumber; struct People { uint256 favoriteNumber; string name; } People[] public people; mapping(string => uint256) public nameToFavoriteNumeber; function store(uint256 _favoriteNumber) public { favoriteNumber = _favoriteNumber; } // view, pure -> reading of blockchain function retrieve() public view returns (uint256) { return favoriteNumber; } // memory -> during the function // storage -> on the contract function addPerson(string memory _name, uint256 _favoriteNumber) public { people.push(People({favoriteNumber: _favoriteNumber, name: _name})); nameToFavoriteNumeber[_name] = _favoriteNumber; } }
contract SimpleStorage { // This wiil get initialize to 0! uint256 favoriteNumber; struct People { uint256 favoriteNumber; string name; } People[] public people; mapping(string => uint256) public nameToFavoriteNumeber; function store(uint256 _favoriteNumber) public { favoriteNumber = _favoriteNumber; } // view, pure -> reading of blockchain function retrieve() public view returns (uint256) { return favoriteNumber; } // memory -> during the function // storage -> on the contract function addPerson(string memory _name, uint256 _favoriteNumber) public { people.push(People({favoriteNumber: _favoriteNumber, name: _name})); nameToFavoriteNumeber[_name] = _favoriteNumber; } }
15,799
14
// We combine random value with The Divine's result to prevent manipulation https:github.com/chiro-hiro/thedivine
_entropy ^= uint256(data.readUint256(0)) ^ _theDivine.rand(); return true;
_entropy ^= uint256(data.readUint256(0)) ^ _theDivine.rand(); return true;
427
50
// Crowdsale end time has been changed
event EndsAtChanged(uint newEndsAt); function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { owner = msg.sender; name = _name; token = FractionalERC20Ext(_token);
event EndsAtChanged(uint newEndsAt); function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { owner = msg.sender; name = _name; token = FractionalERC20Ext(_token);
24,206
9
// Buyer's amounts/ return Buyer's amounts for address
mapping(address => uint) public buyerAmounts;
mapping(address => uint) public buyerAmounts;
50,955
2
// Emitted when the admin sets a new flash fee./admin The address of the contract admin./oldFlashFee The old flash fee, denoted as a fixed-point number./newFlashFee The new flash fee, denoted as a fixed-point number.
event SetFlashFee(address indexed admin, UD60x18 oldFlashFee, UD60x18 newFlashFee);
event SetFlashFee(address indexed admin, UD60x18 oldFlashFee, UD60x18 newFlashFee);
23,258
7
// PURCHASE TOKENS
function purchase(uint amount) public payable { // IF THE CONTRACT HAS BEEN INITIALIZED // IF THE SENDER HAS SUFFICIENT FUNDS require(initialized, 'contract has not been initialized'); require(msg.value == amount * price, 'insufficient funds provided'); // FIX FOR OVERFLOW uint sum = tokens[msg.sender] + amount; require(sum >= tokens[msg.sender], 'token overflow error'); // INCREASE TOKEN COUNT FOR SENDER tokens[msg.sender] += amount; }
function purchase(uint amount) public payable { // IF THE CONTRACT HAS BEEN INITIALIZED // IF THE SENDER HAS SUFFICIENT FUNDS require(initialized, 'contract has not been initialized'); require(msg.value == amount * price, 'insufficient funds provided'); // FIX FOR OVERFLOW uint sum = tokens[msg.sender] + amount; require(sum >= tokens[msg.sender], 'token overflow error'); // INCREASE TOKEN COUNT FOR SENDER tokens[msg.sender] += amount; }
26,857
91
// Unpauses the contract.// Once the contract is unpaused, it can be used normally.// .. note:: This function can only be called when the contract is paused./ .. note:: This function can only be called by the contract owner.
function unpause() external onlyOwner { _unpause(); }
function unpause() external onlyOwner { _unpause(); }
8,185
59
// send `_value` token to `_to` from `msg.sender` _to The address of the recipient _value The amount of token to be transferredreturn Whether the transfer was successful or not /
function transfer(address _to, uint256 _value) external returns (bool success);
function transfer(address _to, uint256 _value) external returns (bool success);
36,087
133
// start block should be less than ending block
_startBlock >= _endBlock ||
_startBlock >= _endBlock ||
22,760
213
// premium = twapMarketPrice - twapIndexPrice timeFraction = fundingPeriod(1 hour) / 1 day premiumFraction = premiumtimeFraction
Decimal.decimal memory underlyingPrice = getUnderlyingTwapPrice(spotPriceTwapInterval); SignedDecimal.signedDecimal memory premium = MixedDecimal.fromDecimal(getTwapPrice(spotPriceTwapInterval)).subD(underlyingPrice); premiumFraction = premium.mulScalar(fundingPeriod).divScalar(int256(1 days));
Decimal.decimal memory underlyingPrice = getUnderlyingTwapPrice(spotPriceTwapInterval); SignedDecimal.signedDecimal memory premium = MixedDecimal.fromDecimal(getTwapPrice(spotPriceTwapInterval)).subD(underlyingPrice); premiumFraction = premium.mulScalar(fundingPeriod).divScalar(int256(1 days));
21,981
4
// Emit info used by client-side test code
emit GoToNextEpochTestInfo( currentEpoch, blockTimestamp );
emit GoToNextEpochTestInfo( currentEpoch, blockTimestamp );
22,650
264
// Amount must be greater than 0.
require(_amount > 0, "TicketBooth::lock: NO_OP");
require(_amount > 0, "TicketBooth::lock: NO_OP");
71,342
48
// Will return the approved recipient for a key, if any. _tokenId The ID of the token we're inquiring about.return address The approved address (if any) /
function getApproved( uint _tokenId ) external view returns (address);
function getApproved( uint _tokenId ) external view returns (address);
13,145
66
// Rebalance, Compound or Pay off debt here
function tend() external whenNotPaused { revert("no op"); // NOTE: For now tend is replaced by manualRebalance }
function tend() external whenNotPaused { revert("no op"); // NOTE: For now tend is replaced by manualRebalance }
67,110
9
// Receive tokens and generate a log event from Address from which to transfer tokens value Amount of tokens to transfer token Address of token extraData Additional data to log /
function receiveApproval(address from, uint256 value, address token, bytes extraData) public { ERC20 t = ERC20(token); require(t.transferFrom(from, this, value)); ReceivedTokens(from, value, token, extraData); }
function receiveApproval(address from, uint256 value, address token, bytes extraData) public { ERC20 t = ERC20(token); require(t.transferFrom(from, this, value)); ReceivedTokens(from, value, token, extraData); }
18,449
81
// error / exception
failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages( _payload.length, keccak256(_payload) ); emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload);
failedMessages[_srcChainId][_srcAddress][_nonce] = FailedMessages( _payload.length, keccak256(_payload) ); emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload);
27,178
26
// pesimistically charge 0.5% on the withdrawal. Actual fee might be lesser if the vault keeps keeps a buffer
uint strategyFee = sett.mul(controller.strategies(pool.lpToken).withdrawalFee()).div(1000); lp = sett.sub(strategyFee).mul(pool.sett.getPricePerFullShare()).div(1e18); fee = fee.add(strategyFee);
uint strategyFee = sett.mul(controller.strategies(pool.lpToken).withdrawalFee()).div(1000); lp = sett.sub(strategyFee).mul(pool.sett.getPricePerFullShare()).div(1e18); fee = fee.add(strategyFee);
37,432
30
// This method can be overridden to enable some sender to buy token for a different address
function senderAllowedFor(address buyer) internal view returns(bool)
function senderAllowedFor(address buyer) internal view returns(bool)
562
582
// Claims all rewarded tokens from a pool.// The pool and stake MUST be updated before calling this function.//_poolId The pool to claim rewards from.//use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal { Stake.Data storage _stake = _stakes[msg.sender][_poolId]; uint256 _claimAmount = _stake.totalUnclaimed; _stake.totalUnclaimed = 0; reward.mint(msg.sender, _claimAmount); emit TokensClaimed(msg.sender, _poolId, _claimAmount); }
function _claim(uint256 _poolId) internal { Stake.Data storage _stake = _stakes[msg.sender][_poolId]; uint256 _claimAmount = _stake.totalUnclaimed; _stake.totalUnclaimed = 0; reward.mint(msg.sender, _claimAmount); emit TokensClaimed(msg.sender, _poolId, _claimAmount); }
20,368
64
// We also need to add the previous root to the history, and set the timestamp at which it was expired.
rootHistory[preRoot] = uint128(block.timestamp);
rootHistory[preRoot] = uint128(block.timestamp);
31,122
53
// Getter for the amount of `token` tokens already released to a payee. `token` should be the address of anIERC20 contract. /
function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; }
function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; }
26,975
60
// admin can transfer out reward tokens from this contract one month after vault has ended
uint public adminCanClaimAfter = 395 days; uint public vaultDeployTime; uint public adminClaimableTime; uint public vaultEndTime; EnumerableSet.AddressSet private holders; mapping (address => uint) public depositedTokens; mapping (address => uint) public depositTime;
uint public adminCanClaimAfter = 395 days; uint public vaultDeployTime; uint public adminClaimableTime; uint public vaultEndTime; EnumerableSet.AddressSet private holders; mapping (address => uint) public depositedTokens; mapping (address => uint) public depositTime;
41,906
22
// Returns decimals of token/
function decimals() public pure returns(uint256){ return _decimals; }
function decimals() public pure returns(uint256){ return _decimals; }
19,055
16
// Check whether another token is still available
modifier ensureAvailability() { require(availableTokenCount() > 0, "No more tokens available"); _; }
modifier ensureAvailability() { require(availableTokenCount() > 0, "No more tokens available"); _; }
37,653
22
// The ETH balance of the account is not enough to perform the operation. /
error AddressInsufficientBalance(address account);
error AddressInsufficientBalance(address account);
8,684
11
// Order Tree Root & Height.
uint256 orderRoot; // NOLINT: constable-states uninitialized-state. uint256 orderTreeHeight; // NOLINT: constable-states uninitialized-state.
uint256 orderRoot; // NOLINT: constable-states uninitialized-state. uint256 orderTreeHeight; // NOLINT: constable-states uninitialized-state.
16,004
9
// game rewards
uint256 rewardPoolAmount = _calculateFee(_amount, 3000); address rewardPool = 0xd657d402e12cF2619d40b1B5069818B2989f17B4; pika().transfer(rewardPool, rewardPoolAmount); _mint(_msgSender(), _amount / 10000); emit Evolved(_msgSender(), _amount);
uint256 rewardPoolAmount = _calculateFee(_amount, 3000); address rewardPool = 0xd657d402e12cF2619d40b1B5069818B2989f17B4; pika().transfer(rewardPool, rewardPoolAmount); _mint(_msgSender(), _amount / 10000); emit Evolved(_msgSender(), _amount);
67,825
114
// The block number when LV1Token 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( LV1Token _lv1,
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( LV1Token _lv1,
16,709
1
// tokenId => sell price in wei
mapping(uint256 => uint256) public sellPrices;
mapping(uint256 => uint256) public sellPrices;
24,860
34
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i];
for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i];
2,208
50
// ...and copy migration set to current set
copySet(currentSet, migrationSet);
copySet(currentSet, migrationSet);
32,187