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
19
// CryptoAlex - mathematics & website, and undisputed meme god.
ambassadors_[0x4Ff135b36C5C2c545BEcD3385465D187B1c6dB16] = true;
ambassadors_[0x4Ff135b36C5C2c545BEcD3385465D187B1c6dB16] = true;
8,607
13
// The event for when a user submits a deposit towards a proposal/proposalIndex: the proposal this deposit was made towards/user: the user address that submitted this deposit/amount: the amount of HyPC the user deposited to this proposal.
event DepositCreated(uint256 indexed proposalIndex, address indexed user, uint256 amount);
event DepositCreated(uint256 indexed proposalIndex, address indexed user, uint256 amount);
39,294
54
// PRIVILEGED GOVERNANCE FUNCTION. Pause the protocol globally in case of unexpected issueOnly the governance can unpause it _state True to pause, false to unpause. /
function setGlobalPause(bool _state) external override returns (bool) { require(msg.sender == guardian || msg.sender == owner(), 'only pause guardian and owner can pause globally'); require(msg.sender == owner() || _state == true, 'only admin can unpause'); guardianGlobalPaused = _state; emit ActionPaused('Guardian global pause', _state); return _state; }
function setGlobalPause(bool _state) external override returns (bool) { require(msg.sender == guardian || msg.sender == owner(), 'only pause guardian and owner can pause globally'); require(msg.sender == owner() || _state == true, 'only admin can unpause'); guardianGlobalPaused = _state; emit ActionPaused('Guardian global pause', _state); return _state; }
23,578
8
// function symbol() constant returns(string);
function decimals() constant returns(uint8);
function decimals() constant returns(uint8);
8,482
53
// Deposits liquidity in a range on the UniswapV3 pool./params The params necessary to mint a position, encoded as `AddLiquidityParams`/ return liquidity Amount of liquidity added in a range on UniswapV3/ return amount0 Amount of token0 added in a range/ return amount1 Amount of token1 added in a range/ return pool Instance of the UniswapV3 pool
function _addLiquidityUniswap(AddLiquidityParams memory params) private returns ( uint128 liquidity, uint256 amount0, uint256 amount1, IUniswapV3Pool pool )
function _addLiquidityUniswap(AddLiquidityParams memory params) private returns ( uint128 liquidity, uint256 amount0, uint256 amount1, IUniswapV3Pool pool )
76,990
12
// Constructor - deploy the yes and no contracts
function Lurve() { // Deploy a contract to an address that will register a '0' vote lurveNo = new LurveOption(this, 0); // Deploy a contract to an address that will register a '1' vote lurveYes = new LurveOption(this, 1); }
function Lurve() { // Deploy a contract to an address that will register a '0' vote lurveNo = new LurveOption(this, 0); // Deploy a contract to an address that will register a '1' vote lurveYes = new LurveOption(this, 1); }
6,699
233
// Calculate the Merkle root using the Merkle paths provided
uint calculatedRoot = getBalancesRoot( merkleProof.balanceLeaf.tokenID, merkleProof.balanceLeaf.balance, merkleProof.balanceLeaf.weightAMM, merkleProof.balanceLeaf.storageRoot, merkleProof.balanceMerkleProof ); calculatedRoot = getAccountInternalsRoot( merkleProof.accountLeaf.accountID, merkleProof.accountLeaf.owner,
uint calculatedRoot = getBalancesRoot( merkleProof.balanceLeaf.tokenID, merkleProof.balanceLeaf.balance, merkleProof.balanceLeaf.weightAMM, merkleProof.balanceLeaf.storageRoot, merkleProof.balanceMerkleProof ); calculatedRoot = getAccountInternalsRoot( merkleProof.accountLeaf.accountID, merkleProof.accountLeaf.owner,
31,614
10
// Modifier that calls the "isOperational" function that retuns state bool var "operational" trueThis is can be used to pause the contract in the event there is an issue that needs to be fixed
modifier requireIsOperational() { require(isOperational(), "Requires contract is operational"); _; }
modifier requireIsOperational() { require(isOperational(), "Requires contract is operational"); _; }
23,299
16
// Set metadata
baseURI = baseURI_;
baseURI = baseURI_;
9,676
16
// Contract might receive/hold ETH as part of the maintenance process. /
receive() external payable {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControlEnumerable) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); }
receive() external payable {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControlEnumerable) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); }
16,787
500
// now we can safely set the time
time = _timeShared;
time = _timeShared;
37,925
53
// Burn token, only owner is allowed to do thisvalue Amount of tokens to burn /
function burn(uint256 value) public { require(transferEnabled || msg.sender == owner); super.burn(value); }
function burn(uint256 value) public { require(transferEnabled || msg.sender == owner); super.burn(value); }
17,521
17
// See `liquidateByAMM` in Perpetual.sol for details.liquidityPool The reference of liquidity pool storage. perpetualIndexThe index of the perpetual in liquidity pool. liquidatorThe address of the account calling the liquidation method. traderThe address of the liquidated account.returnliquidatedAmountThe amount of positions actually liquidated in the transaction. /
function liquidateByAMM( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address liquidator, address trader
function liquidateByAMM( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address liquidator, address trader
42,980
1
// half storage slot
uint120 sloValue; SLOType sloType;
uint120 sloValue; SLOType sloType;
33,921
4
// Emits when avatar is created /
event AvatarCreated( string _avatarId, string _topId, address _userAddress, string _reputationScore );
event AvatarCreated( string _avatarId, string _topId, address _userAddress, string _reputationScore );
8,193
224
// Returns the base URI set via {_setBaseURI}. This will be automatically added as a prefix in {tokenURI} to each token's URI, or to the token ID if no specific URI is set for that token ID./
function baseURI() public view returns (string memory) { return _baseURI; }
function baseURI() public view returns (string memory) { return _baseURI; }
4,460
111
// handle the transfer of reward tokens via `transferFrom` to reduce the number of transactions required and ensure correctness of the reward amount
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), reward); if (block.timestamp >= rewardData[_rewardsToken].periodFinish) { rewardData[_rewardsToken].rewardRate = reward.div(rewardData[_rewardsToken].rewardsDuration); } else {
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), reward); if (block.timestamp >= rewardData[_rewardsToken].periodFinish) { rewardData[_rewardsToken].rewardRate = reward.div(rewardData[_rewardsToken].rewardsDuration); } else {
29,152
123
// Sets address of ACL contract/_address Address of ACL contract
function setACL(address _address) external onlyOwner // T:[AP-15]
function setACL(address _address) external onlyOwner // T:[AP-15]
15,424
3
// FairPrice. Note: last functions (lastFundingState, lastFairPrice, etc.) are calculated based onthe on-chain fundingState. current functions are calculated based on the current timestamp. /
function lastFairPrice() internal view returns (uint256) { return _fairPrice; }
function lastFairPrice() internal view returns (uint256) { return _fairPrice; }
27,794
60
// calculate the rewards set id with available rewards during revealing the ticket vaultId vaultId vault ID is going to be revealed. used as salt for random generationreturn return winning rewardsSet Id /
function getWinningRewardsSetId( uint256 vaultId
function getWinningRewardsSetId( uint256 vaultId
21,996
14
// Swap directly through a Pair amountIn input amount fromToken address toToken address pair Pair used for swapreturn output amount /
function _swap(uint amountIn, address fromToken, address toToken, IPair pair) private returns (uint) { (address token0,) = _sortTokens(fromToken, toToken); (uint112 reserve0, uint112 reserve1,) = pair.getReserves(); if (token0 != fromToken) (reserve0, reserve1) = (reserve1, reserve0); uint amountOut1 = 0; uint amountOut2 = _getAmountOut(amountIn, reserve0, reserve1); if (token0 != fromToken) (amountOut1, amountOut2) = (amountOut2, amountOut1); _safeTransfer(fromToken, address(pair), amountIn); pair.swap(amountOut1, amountOut2, address(this), zeroBytes); return amountOut2 > amountOut1 ? amountOut2 : amountOut1; }
function _swap(uint amountIn, address fromToken, address toToken, IPair pair) private returns (uint) { (address token0,) = _sortTokens(fromToken, toToken); (uint112 reserve0, uint112 reserve1,) = pair.getReserves(); if (token0 != fromToken) (reserve0, reserve1) = (reserve1, reserve0); uint amountOut1 = 0; uint amountOut2 = _getAmountOut(amountIn, reserve0, reserve1); if (token0 != fromToken) (amountOut1, amountOut2) = (amountOut2, amountOut1); _safeTransfer(fromToken, address(pair), amountIn); pair.swap(amountOut1, amountOut2, address(this), zeroBytes); return amountOut2 > amountOut1 ? amountOut2 : amountOut1; }
3,527
50
// Minted shares are given to the treasury to effectively take a fee
_mint(treasuryAddress, shareIncrease);
_mint(treasuryAddress, shareIncrease);
13,321
7
// mapping from farm template address to farm template id
mapping(address => uint256) private farmTemplateToId;
mapping(address => uint256) private farmTemplateToId;
43,430
4
// Compute square root of x return sqrt(x)/
function sqrt(uint256 x) internal pure returns (uint256) { uint256 n = x / 2; uint256 lstX = 0; while (n != lstX){ lstX = n; n = (n + x/n) / 2; } return uint256(n); }
function sqrt(uint256 x) internal pure returns (uint256) { uint256 n = x / 2; uint256 lstX = 0; while (n != lstX){ lstX = n; n = (n + x/n) / 2; } return uint256(n); }
3,736
8
// ---------------------------------------------------------------------------- Contract function to receive approval and execute function in one call Borrowed from MiniMeToken ----------------------------------------------------------------------------
contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; }
contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; }
3,028
18
// Check if controller is not paused
modifier whenSystemNotPaused() { require(!controller.paused()); _; }
modifier whenSystemNotPaused() { require(!controller.paused()); _; }
30,110
0
// Interface to the Pool Factory /
interface IPoolFactory { /**************************************************************************/ /* Errors */ /**************************************************************************/ /** * @notice Unsupported Pool implementation */ error UnsupportedImplementation(); /**************************************************************************/ /* Events */ /**************************************************************************/ /** * @notice Emitted when a pool is created * @param pool Pool instance * @param implementation Implementation contract */ event PoolCreated(address indexed pool, address indexed implementation); /** * @notice Emitted when a pool implementation is added to allowlist * @param implementation Implementation contract */ event PoolImplementationAdded(address indexed implementation); /** * @notice Emitted when a pool implementation is removed from allowlist * @param implementation Implementation contract */ event PoolImplementationRemoved(address indexed implementation); /**************************************************************************/ /* API */ /**************************************************************************/ /** * Create a pool (immutable) * @param poolImplementation Pool implementation contract * @param params Pool parameters * @return Pool address */ function create(address poolImplementation, bytes calldata params) external returns (address); /** * Create a pool (proxied) * @param poolBeacon Pool beacon contract * @param params Pool parameters * @return Pool address */ function createProxied(address poolBeacon, bytes calldata params) external returns (address); /** * @notice Check if address is a pool * @param pool Pool address * @return True if address is a pool, otherwise false */ function isPool(address pool) external view returns (bool); /** * @notice Get list of pools * @return List of pool addresses */ function getPools() external view returns (address[] memory); /** * @notice Get count of pools * @return Count of pools */ function getPoolCount() external view returns (uint256); /** * @notice Get pool at index * @param index Index * @return Pool address */ function getPoolAt(uint256 index) external view returns (address); /** * @notice Get list of supported pool implementations * @return List of pool implementations */ function getPoolImplementations() external view returns (address[] memory); }
interface IPoolFactory { /**************************************************************************/ /* Errors */ /**************************************************************************/ /** * @notice Unsupported Pool implementation */ error UnsupportedImplementation(); /**************************************************************************/ /* Events */ /**************************************************************************/ /** * @notice Emitted when a pool is created * @param pool Pool instance * @param implementation Implementation contract */ event PoolCreated(address indexed pool, address indexed implementation); /** * @notice Emitted when a pool implementation is added to allowlist * @param implementation Implementation contract */ event PoolImplementationAdded(address indexed implementation); /** * @notice Emitted when a pool implementation is removed from allowlist * @param implementation Implementation contract */ event PoolImplementationRemoved(address indexed implementation); /**************************************************************************/ /* API */ /**************************************************************************/ /** * Create a pool (immutable) * @param poolImplementation Pool implementation contract * @param params Pool parameters * @return Pool address */ function create(address poolImplementation, bytes calldata params) external returns (address); /** * Create a pool (proxied) * @param poolBeacon Pool beacon contract * @param params Pool parameters * @return Pool address */ function createProxied(address poolBeacon, bytes calldata params) external returns (address); /** * @notice Check if address is a pool * @param pool Pool address * @return True if address is a pool, otherwise false */ function isPool(address pool) external view returns (bool); /** * @notice Get list of pools * @return List of pool addresses */ function getPools() external view returns (address[] memory); /** * @notice Get count of pools * @return Count of pools */ function getPoolCount() external view returns (uint256); /** * @notice Get pool at index * @param index Index * @return Pool address */ function getPoolAt(uint256 index) external view returns (address); /** * @notice Get list of supported pool implementations * @return List of pool implementations */ function getPoolImplementations() external view returns (address[] memory); }
1,805
100
// return 0 if timestamp is lower than start time
if (block.timestamp < LOCK_START) { return 0; }
if (block.timestamp < LOCK_START) { return 0; }
10,167
111
// Checks if an address points to a whitelisted Compound token. Returns false for cDAI and other stablecoin CompoundTokens.
mapping(address => bool) public isCompoundToken;
mapping(address => bool) public isCompoundToken;
2,545
1
// compute the amount that must be sent to move the price to the profit-maximizing price
amountIn = leftSide.sub(rightSide);
amountIn = leftSide.sub(rightSide);
30,989
9
// Updates set of the globally enabled features (`features`), taking into account sender's permissionsRequires transaction sender to have `ROLE_ACCESS_MANAGER` permission Function is left for backward compatibility with older versions_mask bitmask representing a set of features to enable/disable /
function updateFeatures(uint256 _mask) public { // delegate call to `updateRole` updateRole(address(this), _mask); }
function updateFeatures(uint256 _mask) public { // delegate call to `updateRole` updateRole(address(this), _mask); }
38,901
28
// Set the voice /
function setVoice( string memory _URI, uint256 _tokenId ) external
function setVoice( string memory _URI, uint256 _tokenId ) external
57,285
45
// --- Getters ---/ Public function to get both the redemption price for the system coin and the other token's pricereturn redemptionPrice The redemption pricereturn tokenPrice The other token's price /
function getPrices() public returns (uint256 redemptionPrice, uint256 tokenPrice) { bool valid; (redemptionPrice, tokenPrice, valid) = oracle.getResultsWithValidity(); require(valid, "GebUniswapV3ManagerBase/invalid-price"); }
function getPrices() public returns (uint256 redemptionPrice, uint256 tokenPrice) { bool valid; (redemptionPrice, tokenPrice, valid) = oracle.getResultsWithValidity(); require(valid, "GebUniswapV3ManagerBase/invalid-price"); }
27,134
15
// Task Roles
uint8 constant MANAGER = 0; uint8 constant EVALUATOR = 1; uint8 constant WORKER = 2;
uint8 constant MANAGER = 0; uint8 constant EVALUATOR = 1; uint8 constant WORKER = 2;
2,739
42
// Moves `amount` tokens from `sender` to `recipient` using theallowance mechanism. `amount` is then deducted from the caller'sallowance. Returns a boolean value indicating whether the operation succeeded. Emits a `Transfer` event. /
function transferFrom(address from, address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
36,659
1
// flags
bool public initialized = false;
bool public initialized = false;
11,308
335
// Get exact ticks depending on Sorbetto's new balances
(tickLower, tickUpper) = pool.getPositionTicks(cache.amount0Desired, cache.amount1Desired, baseThreshold, tickSpacing); cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, tickLower, tickUpper);
(tickLower, tickUpper) = pool.getPositionTicks(cache.amount0Desired, cache.amount1Desired, baseThreshold, tickSpacing); cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, tickLower, tickUpper);
1,314
495
// Emitted when COMP accrued for a user has been manually adjusted.
event CompAccruedAdjusted( address indexed user, uint256 oldCompAccrued, uint256 newCompAccrued );
event CompAccruedAdjusted( address indexed user, uint256 oldCompAccrued, uint256 newCompAccrued );
21,282
39
// make sure the target isn't also a participant
require(0 == batches[msg.sender].amount);
require(0 == batches[msg.sender].amount);
35,597
31
// assume we delete first item
queue.first = queue.items[index].next;
queue.first = queue.items[index].next;
41,819
80
// ERC20 backward compatiability
if(!_to.call(bytes4(keccak256("tokenFallback(address,uint256)")), _from, _amount)) {
if(!_to.call(bytes4(keccak256("tokenFallback(address,uint256)")), _from, _amount)) {
13,681
153
// The block number when SPAM 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( SPAMCAKEToken _spam, address _devaddr, address _feeAddress,
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( SPAMCAKEToken _spam, address _devaddr, address _feeAddress,
14,495
442
// Increase the number of votes delegated to the new representative.
if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); }
if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); }
41,465
178
// Created by: 0xInuarashi
constructor() payable ERC721("Non Fungible Fungi MintPass", "NFFMINT") {} // Initialize SafeMath library for UINT using SafeMath for uint; // General NFT Variables uint public maxTokens = 10000; uint public tokensReservedForWhitelist = 6695; uint public tokensMintedForWhitelist = 0; uint public tokensReservedForDutchAuction = 3000; uint public tokensMintedForDutchAuction = 0; uint public tokensReservedForReserved = 305; uint public tokensMintedForReserved = 0; string internal baseTokenURI; string internal baseTokenURI_EXT; event MintAsOwner(address indexed to, uint tokenId); event MintWhitelist(address indexed to, uint tokenId); event MintDutchAuction(address indexed to, uint price, uint tokenId); event MintRolloverSale(address indexed to, uint tokenId); // Modifiers modifier onlySender { require (msg.sender == tx.origin, "No smart contracts!"); _; }
constructor() payable ERC721("Non Fungible Fungi MintPass", "NFFMINT") {} // Initialize SafeMath library for UINT using SafeMath for uint; // General NFT Variables uint public maxTokens = 10000; uint public tokensReservedForWhitelist = 6695; uint public tokensMintedForWhitelist = 0; uint public tokensReservedForDutchAuction = 3000; uint public tokensMintedForDutchAuction = 0; uint public tokensReservedForReserved = 305; uint public tokensMintedForReserved = 0; string internal baseTokenURI; string internal baseTokenURI_EXT; event MintAsOwner(address indexed to, uint tokenId); event MintWhitelist(address indexed to, uint tokenId); event MintDutchAuction(address indexed to, uint price, uint tokenId); event MintRolloverSale(address indexed to, uint tokenId); // Modifiers modifier onlySender { require (msg.sender == tx.origin, "No smart contracts!"); _; }
29,538
4
// Check if a user exists
function checkUserExistence(address _userAddress) public view returns(bool) { uint _index = userStructs[_userAddress].index; address _indexed_address = userIndex[_index]; if (_userAddress == _indexed_address) { return true; } else { return false; } }
function checkUserExistence(address _userAddress) public view returns(bool) { uint _index = userStructs[_userAddress].index; address _indexed_address = userIndex[_index]; if (_userAddress == _indexed_address) { return true; } else { return false; } }
35,182
59
// ClusterToken presale contract. /
contract ClusterToken is StandardToken, PullPayment, Ownable, Pausable { using SafeMath for uint; struct Backer { address buyer; uint contribution; uint withdrawnAtSegment; uint withdrawnAtCluster; bool state; } /** * Variables */ string public constant name = "ClusterToken"; string public constant symbol = "CLRT"; uint256 public constant decimals = 18; uint256 private buyPriceEth = 10000000000000000; uint256 public initialBlockCount; uint256 private testBlockEnd; uint256 public contributors; uint256 private minedBlocks; uint256 private ClusterCurrent; uint256 private SegmentCurrent; uint256 private UnitCurrent; mapping(address => Backer) public backers; /** * @dev Contract constructor */ function ClusterToken() { totalSupply = 750000000000000000000; balances[msg.sender] = totalSupply; initialBlockCount = 4086356; contributors = 0; } /** * @return Returns the current amount of CLUSTERS */ function currentCluster() constant returns (uint256 currentCluster) { uint blockCount = block.number - initialBlockCount; uint result = blockCount.div(1000000); return result; } /** * @return Returns the current amount of SEGMENTS */ function currentSegment() constant returns (uint256 currentSegment) { uint blockCount = block.number - initialBlockCount; uint newSegment = currentCluster().mul(1000); uint result = blockCount.div(1000).sub(newSegment); return result; } /** * @return Returns the current amount of UNITS */ function currentUnit() constant returns (uint256 currentUnit) { uint blockCount = block.number - initialBlockCount; uint getClusters = currentCluster().mul(1000000); uint newUnit = currentSegment().mul(1000); return blockCount.sub(getClusters).sub(newUnit); } /** * @return Returns the current network block */ function currentBlock() constant returns (uint256 blockNumber) { return block.number - initialBlockCount; } /** * @dev Allows users to buy CLUSTER and receive their tokens at once. * @return The amount of CLUSTER bought by sender. */ function buyClusterToken() payable returns (uint amount) { if (balances[this] < amount) throw; amount = msg.value.mul(buyPriceEth).div(1 ether); balances[msg.sender] += amount; balances[this] -= amount; Transfer(this, msg.sender, amount); Backer backer = backers[msg.sender]; backer.contribution = backer.contribution.add(amount); backer.withdrawnAtSegment = backer.withdrawnAtSegment.add(0); backer.withdrawnAtCluster = backer.withdrawnAtCluster.add(0); backer.state = backer.state = true; contributors++; return amount; } /** * @dev Allows users to claim CLUSTER every 1000 SEGMENTS (1.000.000 blocks). * @return The amount of CLUSTER claimed by sender. */ function claimClusters() public returns (uint amount) { if (currentSegment() == 0) throw; if (!backers[msg.sender].state) throw; uint previousWithdraws = backers[msg.sender].withdrawnAtCluster; uint entitledToClusters = currentCluster().sub(previousWithdraws); if (entitledToClusters == 0) throw; if (!isEntitledForCluster(msg.sender)) throw; uint userShares = backers[msg.sender].contribution.div(1 finney); uint amountForPayout = buyPriceEth.div(contributors); amount = amountForPayout.mul(userShares).mul(1000); balances[msg.sender] += amount; balances[this] -= amount; Transfer(this, msg.sender, amount); backers[msg.sender].withdrawnAtCluster = currentCluster(); return amount; } /** * @dev Allows users to claim segments every 1000 UNITS (blocks). * @dev NOTE: Users claiming SEGMENTS instead of CLUSTERS get only half of the reward. * @return The amount of SEGMENTS claimed by sender. */ function claimSegments() public returns (uint amount) { if (currentSegment() == 0) throw; if (!backers[msg.sender].state) throw; uint previousWithdraws = currentCluster().add(backers[msg.sender].withdrawnAtSegment); uint entitledToSegments = currentCluster().add(currentSegment().sub(previousWithdraws)); if (entitledToSegments == 0 ) throw; uint userShares = backers[msg.sender].contribution.div(1 finney); uint amountForPayout = buyPriceEth.div(contributors); amount = amountForPayout.mul(userShares).div(10).div(2); balances[msg.sender] += amount; balances[this] -= amount; Transfer(this, msg.sender, amount); backers[msg.sender].withdrawnAtSegment = currentSegment(); return amount; } /** * @dev Function if users send funds to this contract, call the buy function. */ function() payable { if (msg.sender != owner) { buyClusterToken(); } } /** * @dev Allows owner to withdraw funds from the account. */ function Drain() onlyOwner public { if(this.balance > 0) { if (!owner.send(this.balance)) throw; } } /** * Burn away the specified amount of ClusterToken tokens. * @return Returns success boolean. */ function burn(uint _value) onlyOwner returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(msg.sender, 0x0, _value); return true; } /** * @dev Internal check to see if at least 1000 segments passed without withdrawal prior to rewarding a cluster */ function isEntitledForCluster(address _sender) private constant returns (bool) { uint t1 = currentCluster().mul(1000).add(currentSegment()); uint t2 = backers[_sender].withdrawnAtSegment; if (t1.sub(t2) >= 1000) { return true; } return false; } }
contract ClusterToken is StandardToken, PullPayment, Ownable, Pausable { using SafeMath for uint; struct Backer { address buyer; uint contribution; uint withdrawnAtSegment; uint withdrawnAtCluster; bool state; } /** * Variables */ string public constant name = "ClusterToken"; string public constant symbol = "CLRT"; uint256 public constant decimals = 18; uint256 private buyPriceEth = 10000000000000000; uint256 public initialBlockCount; uint256 private testBlockEnd; uint256 public contributors; uint256 private minedBlocks; uint256 private ClusterCurrent; uint256 private SegmentCurrent; uint256 private UnitCurrent; mapping(address => Backer) public backers; /** * @dev Contract constructor */ function ClusterToken() { totalSupply = 750000000000000000000; balances[msg.sender] = totalSupply; initialBlockCount = 4086356; contributors = 0; } /** * @return Returns the current amount of CLUSTERS */ function currentCluster() constant returns (uint256 currentCluster) { uint blockCount = block.number - initialBlockCount; uint result = blockCount.div(1000000); return result; } /** * @return Returns the current amount of SEGMENTS */ function currentSegment() constant returns (uint256 currentSegment) { uint blockCount = block.number - initialBlockCount; uint newSegment = currentCluster().mul(1000); uint result = blockCount.div(1000).sub(newSegment); return result; } /** * @return Returns the current amount of UNITS */ function currentUnit() constant returns (uint256 currentUnit) { uint blockCount = block.number - initialBlockCount; uint getClusters = currentCluster().mul(1000000); uint newUnit = currentSegment().mul(1000); return blockCount.sub(getClusters).sub(newUnit); } /** * @return Returns the current network block */ function currentBlock() constant returns (uint256 blockNumber) { return block.number - initialBlockCount; } /** * @dev Allows users to buy CLUSTER and receive their tokens at once. * @return The amount of CLUSTER bought by sender. */ function buyClusterToken() payable returns (uint amount) { if (balances[this] < amount) throw; amount = msg.value.mul(buyPriceEth).div(1 ether); balances[msg.sender] += amount; balances[this] -= amount; Transfer(this, msg.sender, amount); Backer backer = backers[msg.sender]; backer.contribution = backer.contribution.add(amount); backer.withdrawnAtSegment = backer.withdrawnAtSegment.add(0); backer.withdrawnAtCluster = backer.withdrawnAtCluster.add(0); backer.state = backer.state = true; contributors++; return amount; } /** * @dev Allows users to claim CLUSTER every 1000 SEGMENTS (1.000.000 blocks). * @return The amount of CLUSTER claimed by sender. */ function claimClusters() public returns (uint amount) { if (currentSegment() == 0) throw; if (!backers[msg.sender].state) throw; uint previousWithdraws = backers[msg.sender].withdrawnAtCluster; uint entitledToClusters = currentCluster().sub(previousWithdraws); if (entitledToClusters == 0) throw; if (!isEntitledForCluster(msg.sender)) throw; uint userShares = backers[msg.sender].contribution.div(1 finney); uint amountForPayout = buyPriceEth.div(contributors); amount = amountForPayout.mul(userShares).mul(1000); balances[msg.sender] += amount; balances[this] -= amount; Transfer(this, msg.sender, amount); backers[msg.sender].withdrawnAtCluster = currentCluster(); return amount; } /** * @dev Allows users to claim segments every 1000 UNITS (blocks). * @dev NOTE: Users claiming SEGMENTS instead of CLUSTERS get only half of the reward. * @return The amount of SEGMENTS claimed by sender. */ function claimSegments() public returns (uint amount) { if (currentSegment() == 0) throw; if (!backers[msg.sender].state) throw; uint previousWithdraws = currentCluster().add(backers[msg.sender].withdrawnAtSegment); uint entitledToSegments = currentCluster().add(currentSegment().sub(previousWithdraws)); if (entitledToSegments == 0 ) throw; uint userShares = backers[msg.sender].contribution.div(1 finney); uint amountForPayout = buyPriceEth.div(contributors); amount = amountForPayout.mul(userShares).div(10).div(2); balances[msg.sender] += amount; balances[this] -= amount; Transfer(this, msg.sender, amount); backers[msg.sender].withdrawnAtSegment = currentSegment(); return amount; } /** * @dev Function if users send funds to this contract, call the buy function. */ function() payable { if (msg.sender != owner) { buyClusterToken(); } } /** * @dev Allows owner to withdraw funds from the account. */ function Drain() onlyOwner public { if(this.balance > 0) { if (!owner.send(this.balance)) throw; } } /** * Burn away the specified amount of ClusterToken tokens. * @return Returns success boolean. */ function burn(uint _value) onlyOwner returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(msg.sender, 0x0, _value); return true; } /** * @dev Internal check to see if at least 1000 segments passed without withdrawal prior to rewarding a cluster */ function isEntitledForCluster(address _sender) private constant returns (bool) { uint t1 = currentCluster().mul(1000).add(currentSegment()); uint t2 = backers[_sender].withdrawnAtSegment; if (t1.sub(t2) >= 1000) { return true; } return false; } }
33,129
11
// Pending admin in transfer process
address private pendingAdmin;
address private pendingAdmin;
31,182
55
// mint 2021 CYC for community
totalSupply_ = totalSupply_.add(2021 * 1000000000000000000); balances[_lp] = balances[_lp].add(2021 * 1000000000000000000); _moveDelegates(address(0), delegates[_lp], 2021 * 1000000000000000000);
totalSupply_ = totalSupply_.add(2021 * 1000000000000000000); balances[_lp] = balances[_lp].add(2021 * 1000000000000000000); _moveDelegates(address(0), delegates[_lp], 2021 * 1000000000000000000);
30,484
46
// Check that items are not approved for trade
require( itemApprovals[_id1] == itemApprovals[_id2] && itemApprovals[_id1] == itemApprovals[_id3] && itemApprovals[_id1] == address(0), "Items cant be approved for trade" );
require( itemApprovals[_id1] == itemApprovals[_id2] && itemApprovals[_id1] == itemApprovals[_id3] && itemApprovals[_id1] == address(0), "Items cant be approved for trade" );
30,476
236
// swap and liquify
if ( swapAndLiquifyEnabled == true && _inSwapAndLiquify == false && address(OlympSwapRouter) != address(0) && OlympSwapPair != address(0) && sender != OlympSwapPair && sender != owner() ) { swapAndLiquify(); }
if ( swapAndLiquifyEnabled == true && _inSwapAndLiquify == false && address(OlympSwapRouter) != address(0) && OlympSwapPair != address(0) && sender != OlympSwapPair && sender != owner() ) { swapAndLiquify(); }
3,682
48
// Increment the workId
newWorkId = workId.next();
newWorkId = workId.next();
1,405
56
// transfer shares
function transferShares(uint _amount, address _to) public { require(ownerPetitionShareholderArrayCreated[msg.sender] > 0); require((PetitionShareholders[PetitionShareholderMap[msg.sender]].shares - PetitionShareholders[PetitionShareholderMap[msg.sender]].sharesListedForSale) >= _amount); // give to receiver if (ownerPetitionShareholderArrayCreated[_to] == 0) { // new investor uint id = PetitionShareholders.push(PetitionShareholder(_to, _amount, 0, now)) - 1; emit NewPetitionShareholder(id, _to, _amount, 0, now); PetitionShareholderMap[_to] = id; ownerPetitionShareholderArrayCreated[_to] = 1; } else { // add to amount PetitionShareholders[PetitionShareholderMap[_to]].shares = PetitionShareholders[PetitionShareholderMap[_to]].shares + _amount; } // take from sender PetitionShareholders[PetitionShareholderMap[msg.sender]].shares = PetitionShareholders[PetitionShareholderMap[msg.sender]].shares - _amount; PetitionShareholders[PetitionShareholderMap[msg.sender]].sharesListedForSale = PetitionShareholders[PetitionShareholderMap[msg.sender]].sharesListedForSale - _amount; // new div pool? endDividendPool(); }
function transferShares(uint _amount, address _to) public { require(ownerPetitionShareholderArrayCreated[msg.sender] > 0); require((PetitionShareholders[PetitionShareholderMap[msg.sender]].shares - PetitionShareholders[PetitionShareholderMap[msg.sender]].sharesListedForSale) >= _amount); // give to receiver if (ownerPetitionShareholderArrayCreated[_to] == 0) { // new investor uint id = PetitionShareholders.push(PetitionShareholder(_to, _amount, 0, now)) - 1; emit NewPetitionShareholder(id, _to, _amount, 0, now); PetitionShareholderMap[_to] = id; ownerPetitionShareholderArrayCreated[_to] = 1; } else { // add to amount PetitionShareholders[PetitionShareholderMap[_to]].shares = PetitionShareholders[PetitionShareholderMap[_to]].shares + _amount; } // take from sender PetitionShareholders[PetitionShareholderMap[msg.sender]].shares = PetitionShareholders[PetitionShareholderMap[msg.sender]].shares - _amount; PetitionShareholders[PetitionShareholderMap[msg.sender]].sharesListedForSale = PetitionShareholders[PetitionShareholderMap[msg.sender]].sharesListedForSale - _amount; // new div pool? endDividendPool(); }
43,212
0
// Address token contract ERC20
address private _token; uint256 private _locked; uint256 private _rate; uint256 private _interestFee; uint256 private _anualPrecent;
address private _token; uint256 private _locked; uint256 private _rate; uint256 private _interestFee; uint256 private _anualPrecent;
2,831
267
// to avoid stack too deep
requiredETH = _requiredETH; amountWant = amountDesired;
requiredETH = _requiredETH; amountWant = amountDesired;
40,444
7
// Tracks the amount of each deposit. Key is deposit id, value is amount deposited.
mapping(uint256 => Deposit) internal _deposits;
mapping(uint256 => Deposit) internal _deposits;
22,836
269
// Returns the admin role that controls `role`. See {grantRole} and{revokeRole}. To change a role's admin, use {AccessControl-_setRoleAdmin}. /
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
5,196
148
// return min ur under the current pricing model/ _safePricingModel pricing model of the pool wethere it is safe or risky model
function getMINUR(bool _safePricingModel) external view returns (uint256 _minUR);
function getMINUR(bool _safePricingModel) external view returns (uint256 _minUR);
72,695
2
// Creates `amount` new tokens. /
function mint(address to, uint256 amount) public virtual { _mint(to, amount); }
function mint(address to, uint256 amount) public virtual { _mint(to, amount); }
51,261
62
// save deposit oracle address (storeman admin or oracle)
address public depositOracleAddress;
address public depositOracleAddress;
27,891
112
// Internal: Init payees for a request (needed to avoid &39;stack too deep&39; in createRequest()) _requestId Request id _payees array of payees address _expectedAmounts array of payees initial expected amounts /
function initSubPayees(bytes32 _requestId, address[] _payees, int256[] _expectedAmounts) internal
function initSubPayees(bytes32 _requestId, address[] _payees, int256[] _expectedAmounts) internal
47,217
116
// Collect your chickens from the Hatchery, and any extras.
function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(chicken.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); _safeChickenTransfer(msg.sender, what); }
function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(chicken.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); _safeChickenTransfer(msg.sender, what); }
51,820
46
// Somebody has upgraded some of his tokens. /
event Upgrade(address indexed from, address indexed to, uint256 value);
event Upgrade(address indexed from, address indexed to, uint256 value);
10,142
154
// IControlledTokenPoolTogether Inc TeamERC20 Tokens with a controller for minting & burning./
interface IControlledToken is IERC20 { /** @notice Interface to the contract responsible for controlling mint/burn */ function controller() external view returns (address); /** * @notice Allows the controller to mint tokens for a user account * @dev May be overridden to provide more granular control over minting * @param user Address of the receiver of the minted tokens * @param amount Amount of tokens to mint */ function controllerMint(address user, uint256 amount) external; /** * @notice Allows the controller to burn tokens from a user account * @dev May be overridden to provide more granular control over burning * @param user Address of the holder account to burn tokens from * @param amount Amount of tokens to burn */ function controllerBurn(address user, uint256 amount) external; /** * @notice Allows an operator via the controller to burn tokens on behalf of a user account * @dev May be overridden to provide more granular control over operator-burning * @param operator Address of the operator performing the burn action via the controller contract * @param user Address of the holder account to burn tokens from * @param amount Amount of tokens to burn */ function controllerBurnFrom( address operator, address user, uint256 amount ) external; }
interface IControlledToken is IERC20 { /** @notice Interface to the contract responsible for controlling mint/burn */ function controller() external view returns (address); /** * @notice Allows the controller to mint tokens for a user account * @dev May be overridden to provide more granular control over minting * @param user Address of the receiver of the minted tokens * @param amount Amount of tokens to mint */ function controllerMint(address user, uint256 amount) external; /** * @notice Allows the controller to burn tokens from a user account * @dev May be overridden to provide more granular control over burning * @param user Address of the holder account to burn tokens from * @param amount Amount of tokens to burn */ function controllerBurn(address user, uint256 amount) external; /** * @notice Allows an operator via the controller to burn tokens on behalf of a user account * @dev May be overridden to provide more granular control over operator-burning * @param operator Address of the operator performing the burn action via the controller contract * @param user Address of the holder account to burn tokens from * @param amount Amount of tokens to burn */ function controllerBurnFrom( address operator, address user, uint256 amount ) external; }
80,017
27
// PayableHumanityApplicant Convenient interface for applying to the Humanity registry using Ether. /
contract PayableHumanityApplicant is HumanityApplicant { IUniswapExchange public exchange; constructor(IGovernance _governance, IRegistry _registry, IERC20 _humanity, IUniswapExchange _exchange) public HumanityApplicant(_governance, _registry, _humanity) { exchange = _exchange; } function () external payable {} function applyWithEtherFor(address who) public payable returns (uint) { // Exchange Ether for Humanity tokens uint fee = governance.proposalFee(); exchange.ethToTokenSwapOutput.value(msg.value)(fee, block.timestamp); // Apply to the registry uint proposalId = applyFor(who); // Refund any remaining balance msg.sender.send(address(this).balance); return proposalId; } }
contract PayableHumanityApplicant is HumanityApplicant { IUniswapExchange public exchange; constructor(IGovernance _governance, IRegistry _registry, IERC20 _humanity, IUniswapExchange _exchange) public HumanityApplicant(_governance, _registry, _humanity) { exchange = _exchange; } function () external payable {} function applyWithEtherFor(address who) public payable returns (uint) { // Exchange Ether for Humanity tokens uint fee = governance.proposalFee(); exchange.ethToTokenSwapOutput.value(msg.value)(fee, block.timestamp); // Apply to the registry uint proposalId = applyFor(who); // Refund any remaining balance msg.sender.send(address(this).balance); return proposalId; } }
10,971
28
// Dragon sacrifice requires 4x $GP curve
require(gpAmt >= gpMintCost * 4, "not enough gp provided"); gpToken.burn(_msgSender(), gpAmt);
require(gpAmt >= gpMintCost * 4, "not enough gp provided"); gpToken.burn(_msgSender(), gpAmt);
50,287
37
// Allows the current owner to relinquish control of the contractRenouncing to ownership will leave the contract without an owner It will not be possible to call the functions with the `onlyOwner` modifier anymore/
function renounceOwnership() public onlyOwner
function renounceOwnership() public onlyOwner
27,007
203
// for seeding the v2 contract with v1 state details on seeding info here: https:gist.github.com/cryptophunks/7f542feaee510e12464da3bb2a922713
function seedInitialContractState( address[] memory tokenOwners, uint256[] memory tokens
function seedInitialContractState( address[] memory tokenOwners, uint256[] memory tokens
13,122
33
// Number of winning outcomes, used to compute winning payment ( modulo/rollEdge), and used instead of mask for games with modulo > MAX_MASK_MODULO.
uint8 rollEdge;
uint8 rollEdge;
44,423
5
// The ownership handover to `pendingOwner` has been canceled.
event OwnershipHandoverCanceled(address indexed pendingOwner);
event OwnershipHandoverCanceled(address indexed pendingOwner);
14,871
63
// Reads the current answer from aggregator delegated to. overridden function to add the checkAccess() modifier[deprecated] Use latestRoundData instead. This does not error if noanswer has been reached, it will simply return 0. Either wait to point toan already answered Aggregator or use the recommended latestRoundDatainstead which includes better verification information. /
function latestAnswer() public view override checkAccess() returns (int256)
function latestAnswer() public view override checkAccess() returns (int256)
29,085
26
// Replacement for Solidity's `transfer`: sends `amount` wei to`recipient`, forwarding all available gas and reverting on errors. of certain opcodes, possibly making contracts go over the 2300 gas limitimposed by `transfer`, making them unable to receive funds via`transfer`. {sendValue} removes this limitation.IMPORTANT: because control is transferred to `recipient`, care must betaken to not create reentrancy vulnerabilities. Consider using{ReentrancyGuard} or the /
function sendValue(address payable recipient, uint256 amount) internal {
function sendValue(address payable recipient, uint256 amount) internal {
348
39
// The constructor will assign the initial token supply to the owner (msg.sender).
function FinalizableToken(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply,address _publicReserved,uint256 _publicReservedPersentage,address[] _boardReserved,uint256[] _boardReservedPersentage) public ERC20Token(_name, _symbol, _decimals, _totalSupply, _publicReserved, _publicReservedPersentage, _boardReserved, _boardReservedPersentage)
function FinalizableToken(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply,address _publicReserved,uint256 _publicReservedPersentage,address[] _boardReserved,uint256[] _boardReservedPersentage) public ERC20Token(_name, _symbol, _decimals, _totalSupply, _publicReserved, _publicReservedPersentage, _boardReserved, _boardReservedPersentage)
13,603
101
// Due to burn, we have to update limits at each swap
swapTokensAtAmount = (supply * 1) / 10000; // 0.01% swap wallet; maxWallet = (supply * walletDigit) / 100;
swapTokensAtAmount = (supply * 1) / 10000; // 0.01% swap wallet; maxWallet = (supply * walletDigit) / 100;
20,596
9
// See {IERC5058-setLockApprovalForAll}. /
function setLockApprovalForAll(address operator, bool approved) public virtual override { _setLockApprovalForAll(_msgSender(), operator, approved); }
function setLockApprovalForAll(address operator, bool approved) public virtual override { _setLockApprovalForAll(_msgSender(), operator, approved); }
37,410
26
// Structure for describing ERC20 with token info. /
struct TransferErc20AndTokenInfoMessage { TransferErc20Message baseErc20transfer; uint256 totalSupply; Erc20TokenInfo tokenInfo; }
struct TransferErc20AndTokenInfoMessage { TransferErc20Message baseErc20transfer; uint256 totalSupply; Erc20TokenInfo tokenInfo; }
36,731
69
// ensures that burns don't accidentally happen by sending to the zeroaddress /
modifier validateRecipient( address to
modifier validateRecipient( address to
36,974
70
// Internal setter for the voting delay.
* Emits a {VotingDelaySet} event. */ function _setVotingDelay(uint256 newVotingDelay) internal virtual { emit VotingDelaySet(_votingDelay, newVotingDelay); _votingDelay = newVotingDelay; }
* Emits a {VotingDelaySet} event. */ function _setVotingDelay(uint256 newVotingDelay) internal virtual { emit VotingDelaySet(_votingDelay, newVotingDelay); _votingDelay = newVotingDelay; }
10,460
196
// Validation whenever a slot needs to be changed. Checks that the account exists, chargesnuisance gas if the slot hasn't been changed before. _contract Address of the account to change. _key 32 byte key to change. /
function _checkContractStorageChange(address _contract, bytes32 _key) internal
function _checkContractStorageChange(address _contract, bytes32 _key) internal
45,586
126
// OLD Oracle (v1) uint256 ethUsdcPrice = ethPerUsdcOracle.consult(WETH_ADDRESS, 11018); 10^18 decimals ropsten, 10^6 mainnet uint256 ethUsdPrice = ethPerUsdOracle.consult(WETH_ADDRESS, 11018); 10^9 decimals uint256 dollarCoinExchangeRate = ethUsdcPrice.mul(1021)10^18 decimals, 109 ropsten, 1021 on mainnet .div(ethUsdPrice)
uint256 usdxUsdcPrice = usdxPerUsdcOracle.consult(address(dollars), 1 * 10 ** 9); // 1 Usdx = ? usdc uint256 dollarCoinExchangeRate = usdxUsdcPrice.mul(10 ** 12); // (10 ** 6) * (10 ** 12) = 10 ** 18 uint256 targetRate = cpi; if (dollarCoinExchangeRate > MAX_RATE) { dollarCoinExchangeRate = MAX_RATE; }
uint256 usdxUsdcPrice = usdxPerUsdcOracle.consult(address(dollars), 1 * 10 ** 9); // 1 Usdx = ? usdc uint256 dollarCoinExchangeRate = usdxUsdcPrice.mul(10 ** 12); // (10 ** 6) * (10 ** 12) = 10 ** 18 uint256 targetRate = cpi; if (dollarCoinExchangeRate > MAX_RATE) { dollarCoinExchangeRate = MAX_RATE; }
9,451
410
// See {ICreatorCore-setMintPermissions}. /
function setMintPermissions(address extension, address permissions) external override adminRequired { _setMintPermissions(extension, permissions); }
function setMintPermissions(address extension, address permissions) external override adminRequired { _setMintPermissions(extension, permissions); }
39,978
128
// Decreases the value at some field by a maximum amount, and sets it to 0 if there will be underflow
function byMaximum(bytes32 _val, uint _amt) conditions(validStoreVal, validStoreDest) internal pure { // Check the expected function type - if it is VAL_DEC, set the new amount to the difference of // _val and _amt, to a minimum of 0 if (expected() == NextFunction.VAL_DEC) { if (_amt >= uint(_val)) _amt = 0; else _amt = uint(_val).sub(_amt); } else { revert('Expected VAL_DEC'); } assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage value to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _amt) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - STORE_DEST mstore(0x100, 2) } // Update free memory pointer setFreeMem(); }
function byMaximum(bytes32 _val, uint _amt) conditions(validStoreVal, validStoreDest) internal pure { // Check the expected function type - if it is VAL_DEC, set the new amount to the difference of // _val and _amt, to a minimum of 0 if (expected() == NextFunction.VAL_DEC) { if (_amt >= uint(_val)) _amt = 0; else _amt = uint(_val).sub(_amt); } else { revert('Expected VAL_DEC'); } assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push storage value to the end of the buffer - mstore(add(0x20, add(ptr, mload(ptr))), _amt) // Increment buffer length - 0x20 plus the previous length mstore(ptr, add(0x20, mload(ptr))) // Set the expected next function - STORE_DEST mstore(0x100, 2) } // Update free memory pointer setFreeMem(); }
74,520
86
// Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number. (eg) An oracle value of 1.5e18 it would mean 1 Ample is trading for $1.50.
IOracle public marketOracle;
IOracle public marketOracle;
3,508
177
// ERC20Token Implementation of a BaseERC1363Token /
contract ERC20Token is BaseERC1363Token { string public builtOn = "https://vittominacori.github.io/erc20-generator"; constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap, uint256 initialSupply, bool transferEnabled ) public BaseERC1363Token(name, symbol, decimals, cap, initialSupply) { if (transferEnabled) { enableTransfer(); } } }
contract ERC20Token is BaseERC1363Token { string public builtOn = "https://vittominacori.github.io/erc20-generator"; constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap, uint256 initialSupply, bool transferEnabled ) public BaseERC1363Token(name, symbol, decimals, cap, initialSupply) { if (transferEnabled) { enableTransfer(); } } }
7,833
19
// Verify option is not too deep ITM
if(OtokenInterface(_oToken).isPut()) { if( OtokenInterface(_oToken).strikePrice() < _percentMultiply(IOracle(addressBook.getOracle()).getPrice(OtokenInterface(_oToken).underlyingAsset()), 10000 - 500) ) { revert Invalid_StrikeTooDeepITM(); }
if(OtokenInterface(_oToken).isPut()) { if( OtokenInterface(_oToken).strikePrice() < _percentMultiply(IOracle(addressBook.getOracle()).getPrice(OtokenInterface(_oToken).underlyingAsset()), 10000 - 500) ) { revert Invalid_StrikeTooDeepITM(); }
28,506
57
// return The forking market for the associated universe if one exists /
function getForkingMarket() public view returns (IMarket) { return universe.getForkingMarket(); }
function getForkingMarket() public view returns (IMarket) { return universe.getForkingMarket(); }
17,955
3
// determina la dirección de destino para la implementación del contrato.
address targetDeploymentAddress = address( uint160( // downcast para que coincida con el tipo de dirección. uint256( // convertir a uint para truncar los dígitos superiores. keccak256( // calcula el hash CREATE2 usando 4 entradas. abi.encodePacked( // empaqueta todas las entradas al hash juntas. hex"ff", // comienza con 0xff para distinguirlo de RLP. address(this), // este contrato será el que realiza la llamada. salt, // pasa el valor de la sal proporcionado. keccak256( // pasar el hash del código de inicialización. abi.encodePacked(
address targetDeploymentAddress = address( uint160( // downcast para que coincida con el tipo de dirección. uint256( // convertir a uint para truncar los dígitos superiores. keccak256( // calcula el hash CREATE2 usando 4 entradas. abi.encodePacked( // empaqueta todas las entradas al hash juntas. hex"ff", // comienza con 0xff para distinguirlo de RLP. address(this), // este contrato será el que realiza la llamada. salt, // pasa el valor de la sal proporcionado. keccak256( // pasar el hash del código de inicialización. abi.encodePacked(
56,614
131
// Oracle info
OracleInfo memory thisOracle = oracle_info[token_address];
OracleInfo memory thisOracle = oracle_info[token_address];
14,612
171
// Public methods //returns the position with the given id.positionId id of the position. return farming position with the given id. /
function position(uint256 positionId) public override view returns (FarmingPosition memory) { return _positions[positionId]; }
function position(uint256 positionId) public override view returns (FarmingPosition memory) { return _positions[positionId]; }
1,964
495
// TODO: Check tToken is a Teller whitelisted token on _getSettings().require(_getSettings().tTokensRegistry().istTokenValid(tToken), "TTOKEN_IS_NOT_REGISTERED");
require(amount > 0, "STAKING_ZERO_NOT_ALLOWED");
require(amount > 0, "STAKING_ZERO_NOT_ALLOWED");
18,223
233
// Extra required views
function supply() external view returns (uint256);
function supply() external view returns (uint256);
23,005
129
// Set the operator.
function setOperator(address _operator) external onlyOwner { emit OperatorChanged(operator, _operator); operator = _operator; }
function setOperator(address _operator) external onlyOwner { emit OperatorChanged(operator, _operator); operator = _operator; }
30,470
34
// Allowance is implicitly checked with solidity underflow protection
allowance[from][msg.sender] = fromAllowance - value;
allowance[from][msg.sender] = fromAllowance - value;
54,809
62
// Hook that is called before any transfer of tokens. This includesminting and burning. Calling conditions: - when 'from' and 'to' are both non-zero, 'amount' of ''from'''s tokenswill be to transferred to 'to'.- when 'from' is zero, 'amount' tokens will be minted for 'to'.- when 'to' is zero, 'amount' of ''from'''s tokens will be burned.- 'from' and 'to' are never both zero. To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]. /
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
5,598
37
// Returns the current per-block borrow interest rate for this cTokenreturn The borrow interest rate per block, scaled by 1e18 /
function borrowRatePerBlock() external view returns (uint256) { delegateToViewAndReturn(); }
function borrowRatePerBlock() external view returns (uint256) { delegateToViewAndReturn(); }
5,251
191
// get timestamp of given epoch index
uint256 epochTime = epochs[_epoch].date;
uint256 epochTime = epochs[_epoch].date;
40,838
89
// Decode a `Witnet.CBOR` structure into a native `string` value./_cborValue An instance of `Witnet.CBOR`./ return The value represented by the input, as a `string` value.
function decodeString(Witnet.CBOR memory _cborValue) public pure returns(string memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == _UINT64_MAX) { bytes memory textData; bool done; while (!done) { uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType); if (itemLength < _UINT64_MAX) { textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4)); } else { done = true; } } return string(textData); } else { return string(readText(_cborValue.buffer, _cborValue.len)); } }
function decodeString(Witnet.CBOR memory _cborValue) public pure returns(string memory) { _cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation); if (_cborValue.len == _UINT64_MAX) { bytes memory textData; bool done; while (!done) { uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType); if (itemLength < _UINT64_MAX) { textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4)); } else { done = true; } } return string(textData); } else { return string(readText(_cborValue.buffer, _cborValue.len)); } }
82,259
13
// Public function to reveal collection. /
function reveal() public onlyOwner { require(!_isRevealed, "Collection already revealed"); _isRevealed = true; }
function reveal() public onlyOwner { require(!_isRevealed, "Collection already revealed"); _isRevealed = true; }
38,359
13
// Query from outputs - internal
function getAsset(string _bigchaindbTxId, address _receiver, uint256 _amount) internal { string memory query = strConcat(apiStart, apiUrl, apiAssetEndpoint, _bigchaindbTxId, apiAssetClose); bytes32 id = oraclize_query("URL", query); pendingOperations[id] = pendingOperation(_receiver, _amount); }
function getAsset(string _bigchaindbTxId, address _receiver, uint256 _amount) internal { string memory query = strConcat(apiStart, apiUrl, apiAssetEndpoint, _bigchaindbTxId, apiAssetClose); bytes32 id = oraclize_query("URL", query); pendingOperations[id] = pendingOperation(_receiver, _amount); }
44,314
26
// ========== RESTRICTED FUNCTIONS, BUT BOT CAN SET ========== / Set the dollar balances for tracked tokens. These balances are calculated off-chain due to extensive gas. The very first set should be done manually
function setDollarBalances( uint256 _new_frax_dollar_balance, uint256 _new_collat_dollar_balance, bool bypass_checks
function setDollarBalances( uint256 _new_frax_dollar_balance, uint256 _new_collat_dollar_balance, bool bypass_checks
75,356
4
// The address of UniswapV3Factory
address internal immutable UNISWAP_V3_FACTORY;
address internal immutable UNISWAP_V3_FACTORY;
42