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
14
// Hash 0x transaction
bytes32 transactionHash = LibZeroExTransaction.getTypedDataHash(transaction, EIP712_EXCHANGE_DOMAIN_HASH);
bytes32 transactionHash = LibZeroExTransaction.getTypedDataHash(transaction, EIP712_EXCHANGE_DOMAIN_HASH);
49,273
1
// SPDX-License-Identifier: Unlicensed/
abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } }
abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } }
10,065
44
// LFSTYL token smart contract. /
contract LFSTYLToken is AbstractToken { /** * Maximum allowed number of tokens in circulation. * tokenSupply = tokensIActuallyWant * (10 ^ decimals) */ uint256 constant MAX_TOKEN_COUNT = 10000000 * (10**18); /** * Address of the owner of this smart contract. */ address private owner; /** * Frozen account list holder */ mapping (address => bool) private frozenAccount; /** * Current number of tokens in circulation. */ uint256 tokenCount = 0; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new token smart contract and make msg.sender the * owner of this smart contract. */ function LFSTYLToken () { owner = msg.sender; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "LifeStyleToken"; string constant public symbol = "LFSTYL"; uint8 constant public decimals = 18; /** * Transfer given number of tokens from message sender to given recipient. * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer(address _to, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, * To change the approve amount you first have to reduce the addresses` * allowance to zero by calling `approve(_spender, 0)` if it is not * already 0 to mitigate the race condition described here: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } /** * Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens(uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); // adding transfer event and _from address as null address emit Transfer(0x0, msg.sender, _value); return true; } return false; } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner(address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Freeze ALL token transfers. * May only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; emit Freeze (); } } /** * Unfreeze ALL token transfers. * May only be called by smart contract owner. */ function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; emit Unfreeze (); } } /*A user is able to unintentionally send tokens to a contract * and if the contract is not prepared to refund them they will get stuck in the contract. * The same issue used to happen for Ether too but new Solidity versions added the payable modifier to * prevent unintended Ether transfers. However, there’s no such mechanism for token transfers. * so the below function is created */ function refundTokens(address _token, address _refund, uint256 _value) { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); emit RefundTokens(_token, _refund, _value); } /** * Freeze specific account * May only be called by smart contract owner. */ function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; emit FrozenFunds(_target, freeze); } /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); /** * Logged when a particular account is frozen. */ event FrozenFunds(address target, bool frozen); /** * when accidentally send other tokens are refunded */ event RefundTokens(address _token, address _refund, uint256 _value); }
contract LFSTYLToken is AbstractToken { /** * Maximum allowed number of tokens in circulation. * tokenSupply = tokensIActuallyWant * (10 ^ decimals) */ uint256 constant MAX_TOKEN_COUNT = 10000000 * (10**18); /** * Address of the owner of this smart contract. */ address private owner; /** * Frozen account list holder */ mapping (address => bool) private frozenAccount; /** * Current number of tokens in circulation. */ uint256 tokenCount = 0; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new token smart contract and make msg.sender the * owner of this smart contract. */ function LFSTYLToken () { owner = msg.sender; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "LifeStyleToken"; string constant public symbol = "LFSTYL"; uint8 constant public decimals = 18; /** * Transfer given number of tokens from message sender to given recipient. * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer(address _to, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, * To change the approve amount you first have to reduce the addresses` * allowance to zero by calling `approve(_spender, 0)` if it is not * already 0 to mitigate the race condition described here: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } /** * Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens(uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); // adding transfer event and _from address as null address emit Transfer(0x0, msg.sender, _value); return true; } return false; } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner(address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Freeze ALL token transfers. * May only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; emit Freeze (); } } /** * Unfreeze ALL token transfers. * May only be called by smart contract owner. */ function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; emit Unfreeze (); } } /*A user is able to unintentionally send tokens to a contract * and if the contract is not prepared to refund them they will get stuck in the contract. * The same issue used to happen for Ether too but new Solidity versions added the payable modifier to * prevent unintended Ether transfers. However, there’s no such mechanism for token transfers. * so the below function is created */ function refundTokens(address _token, address _refund, uint256 _value) { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); emit RefundTokens(_token, _refund, _value); } /** * Freeze specific account * May only be called by smart contract owner. */ function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; emit FrozenFunds(_target, freeze); } /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); /** * Logged when a particular account is frozen. */ event FrozenFunds(address target, bool frozen); /** * when accidentally send other tokens are refunded */ event RefundTokens(address _token, address _refund, uint256 _value); }
17,959
13
// Asks pool to calculate pool fee:/
uint256 collateralAmount = calculateCollateralAmount(optionType, strikes, amount);
uint256 collateralAmount = calculateCollateralAmount(optionType, strikes, amount);
49,722
47
// Return transferProxy address. return address transferProxy address /
function transferProxy() external view returns (address);
function transferProxy() external view returns (address);
6,988
6
// Get the list of permitter templates that can be used to restrict nft ids in a poolreturn permitterTemplates_ The list of permitter templates that can be used to restrict nft ids in a pool /
function permitterTemplates() external view returns (IPermitter[] memory);
function permitterTemplates() external view returns (IPermitter[] memory);
30,443
176
// Dev address.
address public devaddr;
address public devaddr;
5,249
78
// Match an ERC721 order, ensuring that the supplied proof demonstrates inclusion of the tokenId in the associated merkle root./from The account to transfer the ERC721 token from — this token must first be approved on the seller's AuthenticatedProxy contract./to The account to transfer the ERC721 token to./token The ERC721 token to transfer./tokenId The ERC721 tokenId to transfer./root A merkle root derived from each valid tokenId — set to 0 to indicate a collection-level or tokenId-specific order./proof A proof that the supplied tokenId is contained within the associated merkle root. Must be length 0 if root is not set./ return A
function matchERC721UsingCriteria( address from, address to, IERC721 token, uint256 tokenId, bytes32 root, bytes32[] calldata proof ) external returns (bool);
function matchERC721UsingCriteria( address from, address to, IERC721 token, uint256 tokenId, bytes32 root, bytes32[] calldata proof ) external returns (bool);
74,315
19
// Preemptively skip to avoid division by zero in _marketSellSingleOrder
if (orders[i].makerAssetAmount == 0 || orders[i].takerAssetAmount == 0) { continue; }
if (orders[i].makerAssetAmount == 0 || orders[i].takerAssetAmount == 0) { continue; }
35,865
72
// Clear approvals from the previous token owner
_approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners[tokenId] = to; emit Transfer(from, to, tokenId);
_approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners[tokenId] = to; emit Transfer(from, to, tokenId);
62,071
19
// Update the cached adjusted bounds, given a new weight. This might be used when weights are adjusted, pre-emptively updating the cache to improve performanceof operations after the weight change completes. Note that this does not update the BPT price: this is stillrelative to the last call to `setCircuitBreaker`. The intent is only to optimize the automatic boundsadjustments due to changing weights. /
function updateAdjustedBounds(bytes32 circuitBreakerState, uint256 newReferenceWeight) internal pure returns (bytes32)
function updateAdjustedBounds(bytes32 circuitBreakerState, uint256 newReferenceWeight) internal pure returns (bytes32)
22,109
2
// block number at which reward period starts
uint256 startBlock;
uint256 startBlock;
23,655
35
// calculate sale values
uint256 pricePerShare = dataUint256[__i(i, "pricePerShareAmount")]; uint256 totalPrice = totalSupply.mul(pricePerShare);
uint256 pricePerShare = dataUint256[__i(i, "pricePerShareAmount")]; uint256 totalPrice = totalSupply.mul(pricePerShare);
23,523
96
// A cancelled vote is only meaningful if a vote is running
emit VoteCancelled(msg.sender, msg.sender, motionID, motionID);
emit VoteCancelled(msg.sender, msg.sender, motionID, motionID);
25,579
1,901
// Simple Perpetual Mock to serve trivial functions /
contract PerpetualMock { struct FundingRate { FixedPoint.Signed rate; bytes32 identifier; FixedPoint.Unsigned cumulativeMultiplier; uint256 updateTime; uint256 applicationTime; uint256 proposalTime; } using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; FundingRate public fundingRate; // Interface functions required to be implemented in order for an instance of this contract to be passed into the // off-chain FinancialContractClient helper module: FixedPoint.Unsigned public collateralRequirement; uint256 public liquidationLiveness; FixedPoint.Unsigned public cumulativeFeeMultiplier; mapping(address => uint256) public positions; mapping(address => uint256) public liquidations; event NewSponsor(address indexed sponsor); event EndedSponsorPosition(); event LiquidationCreated(); function getCurrentTime() public view returns (uint256) { return now; } // Public methods that are useful for tests: function setFundingRate(FundingRate memory _fundingRate) external { fundingRate = _fundingRate; } function applyFundingRate() external { fundingRate.applicationTime = block.timestamp; // Simplified rate calcualtion. // multiplier = multiplier * (1 + rate) fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul( FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate)) ); } }
contract PerpetualMock { struct FundingRate { FixedPoint.Signed rate; bytes32 identifier; FixedPoint.Unsigned cumulativeMultiplier; uint256 updateTime; uint256 applicationTime; uint256 proposalTime; } using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; FundingRate public fundingRate; // Interface functions required to be implemented in order for an instance of this contract to be passed into the // off-chain FinancialContractClient helper module: FixedPoint.Unsigned public collateralRequirement; uint256 public liquidationLiveness; FixedPoint.Unsigned public cumulativeFeeMultiplier; mapping(address => uint256) public positions; mapping(address => uint256) public liquidations; event NewSponsor(address indexed sponsor); event EndedSponsorPosition(); event LiquidationCreated(); function getCurrentTime() public view returns (uint256) { return now; } // Public methods that are useful for tests: function setFundingRate(FundingRate memory _fundingRate) external { fundingRate = _fundingRate; } function applyFundingRate() external { fundingRate.applicationTime = block.timestamp; // Simplified rate calcualtion. // multiplier = multiplier * (1 + rate) fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul( FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate)) ); } }
12,740
304
// deposits liquidity by providing an EIP712 typed signature for an EIP2612 permit request and returns therespective pool token amount requirements: - the caller must have provided a valid and unused EIP712 typed signature /
function depositPermitted(
function depositPermitted(
65,002
55
// inital price in wei
priceChibi = 100000000000000000;
priceChibi = 100000000000000000;
47,271
90
// Returns the downcasted int64 from int256, reverting onoverflow (when the input is less than smallest int64 orgreater than largest int64). Counterpart to Solidity's `int64` operator. Requirements: - input must fit into 64 bits _Available since v3.1._ /
function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); }
function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); }
2,105
4
// Exclude or include an account from fees. account The account to be excluded or included. state The state of the account's fee exclusion. /
function excludeFromFees(address account, bool state) public onlyOwner { if (excludedFromFees[account] != state) { excludedFromFees[account] = state; emit AccountFeeExcludeUpdate(account, state); } }
function excludeFromFees(address account, bool state) public onlyOwner { if (excludedFromFees[account] != state) { excludedFromFees[account] = state; emit AccountFeeExcludeUpdate(account, state); } }
20,913
5
// Makes sure that player profit can't exceed a maximum amount,that the bet size is valid, and the playerNumber is in range.
modifier betIsValid(uint _betSize, uint _playerNumber) { require( calculateProfit(_betSize, _playerNumber) < maxProfit && _betSize >= minBet && _playerNumber > minNumber && _playerNumber < maxNumber); _; }
modifier betIsValid(uint _betSize, uint _playerNumber) { require( calculateProfit(_betSize, _playerNumber) < maxProfit && _betSize >= minBet && _playerNumber > minNumber && _playerNumber < maxNumber); _; }
77,515
37
// If we've accrued any interest, update interestAccruedAsOfBLock to the block that we've calculated interest for. If we've not accrued any interest, then we keep the old value so the next time the entire period is taken into account.
cl.setInterestAccruedAsOfBlock(blockNumber);
cl.setInterestAccruedAsOfBlock(blockNumber);
44,991
46
// check the tokenId is for msg.sender and the threshold has been met
YAGMIProps memory nftProps = tokens[tokenId]; require( nftProps.champion == msg.sender, "Not the champion of the tokenId" ); require( nftProps.status == YAGMIStatus.THRESHOLD_MET, "Not in Threshold met status" );
YAGMIProps memory nftProps = tokens[tokenId]; require( nftProps.champion == msg.sender, "Not the champion of the tokenId" ); require( nftProps.status == YAGMIStatus.THRESHOLD_MET, "Not in Threshold met status" );
9,839
0
// 1e18 corresponds to 1.0, or a 100% fee
uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% - this fits in 64 bits
uint256 private constant _MIN_SWAP_FEE_PERCENTAGE = 1e12; // 0.0001% uint256 private constant _MAX_SWAP_FEE_PERCENTAGE = 1e17; // 10% - this fits in 64 bits
25,834
6
// Function used to check existing userid which promotes to create unique userId;
function chkexisitinguserId(string memory _userId) public view returns (bool) { bool isexist = false; for(uint a =0;a<k;a++){ if(keccak256(abi.encodePacked(_userId)) == keccak256(abi.encodePacked(allUserId[a]))){ isexist = true; break; } } return isexist; }
function chkexisitinguserId(string memory _userId) public view returns (bool) { bool isexist = false; for(uint a =0;a<k;a++){ if(keccak256(abi.encodePacked(_userId)) == keccak256(abi.encodePacked(allUserId[a]))){ isexist = true; break; } } return isexist; }
25,516
4
// Customer index information /
struct CustomerInfo { uint256 customerId; CustomerStatus status; }
struct CustomerInfo { uint256 customerId; CustomerStatus status; }
41,031
23
// Sets the public mint to paused or not paused
function setPaused(bool pause) external onlyOwner { _paused = pause; }
function setPaused(bool pause) external onlyOwner { _paused = pause; }
36,456
104
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
12,231
102
// Acquire the monster and send to player
monsterId = _etheremon.catchMonster.value(userETH)(msg.sender, _classId, _name);
monsterId = _etheremon.catchMonster.value(userETH)(msg.sender, _classId, _name);
34,641
59
// if feed check is active, recalculate amount of bonus spent in USDC (_bonus amount is calculated from Eth price and is in USD)
function priceCorrection(uint256 _bonus) internal view returns(uint256) { if (USDCUSD_FEED_ADDRESS != address(0)) { // feed is providing values as 0.998 (1e8) means USDC is 0.998 USD, so USDC amount = USD amount / feed value return _bonus.mul(1e8).div(uint256(IChainLinkFeed(USDCUSD_FEED_ADDRESS).latestAnswer())); } return _bonus; }
function priceCorrection(uint256 _bonus) internal view returns(uint256) { if (USDCUSD_FEED_ADDRESS != address(0)) { // feed is providing values as 0.998 (1e8) means USDC is 0.998 USD, so USDC amount = USD amount / feed value return _bonus.mul(1e8).div(uint256(IChainLinkFeed(USDCUSD_FEED_ADDRESS).latestAnswer())); } return _bonus; }
43,684
13
// Contractium contract interface
ContractiumInterface ctuContract;
ContractiumInterface ctuContract;
48,540
23
// Accepts an amount of $SPC and returns the corresponding amount of Eth. /
function swapEthforSpace () external payable lock { (uint _reserveEth, uint _reserveSpc,) = getReserves(); require(msg.value < _reserveEth, "Insufficient liquidity"); // Not sure why I need these uint balanceEth = address(this).balance; uint balanceSpc = spaceToken.balanceOf(address(this)); uint spcOut = _getPrice(msg.value, _reserveEth, _reserveSpc); require(spcOut < _reserveSpc, "Insufficient liquidity"); bool sent = spaceToken.transfer(msg.sender, spcOut); require(sent, "Failed to send $SPC"); _update(balanceEth, balanceSpc, _reserveEth, _reserveSpc); emit Swap(msg.sender, msg.value, 0, 0, spcOut); }
function swapEthforSpace () external payable lock { (uint _reserveEth, uint _reserveSpc,) = getReserves(); require(msg.value < _reserveEth, "Insufficient liquidity"); // Not sure why I need these uint balanceEth = address(this).balance; uint balanceSpc = spaceToken.balanceOf(address(this)); uint spcOut = _getPrice(msg.value, _reserveEth, _reserveSpc); require(spcOut < _reserveSpc, "Insufficient liquidity"); bool sent = spaceToken.transfer(msg.sender, spcOut); require(sent, "Failed to send $SPC"); _update(balanceEth, balanceSpc, _reserveEth, _reserveSpc); emit Swap(msg.sender, msg.value, 0, 0, spcOut); }
16,746
48
// ------------------------------------------------------------------ Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account. The `spender` contract function`receiveApproval(...)` is then executed------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; }
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; }
1,224
157
// Integer division of two signed integers, truncating the quotient./
function div(int256 a, int256 b) internal pure returns (int256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // Overflow only happens when the smallest negative int is multiplied by -1. int256 INT256_MIN = int256((uint256(1) << 255)); assert(a != INT256_MIN || b != - 1); return a / b; }
function div(int256 a, int256 b) internal pure returns (int256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // Overflow only happens when the smallest negative int is multiplied by -1. int256 INT256_MIN = int256((uint256(1) << 255)); assert(a != INT256_MIN || b != - 1); return a / b; }
23,951
101
// cap crowdsaled to a maxTokenSupply make sure we can not mint more token than expected
bool lessThanMaxSupply = (token.totalSupply() + msg.value.mul(rate)) <= maxTokenSupply;
bool lessThanMaxSupply = (token.totalSupply() + msg.value.mul(rate)) <= maxTokenSupply;
47,697
23
// Sets the mint data slot length that tracks the state of tickets/num number of tickets available for allow list
function setMintSlotLength(uint256 num) external onlyOwner { // account for solidity rounding down uint256 slotCount = (num / 256) + 1; // set each element in the slot to binaries of 1 uint256 MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // create a temporary array based on number of slots required uint256[] memory arr = new uint256[](slotCount); // fill each element with MAX_INT for (uint256 i; i < slotCount; i++) { arr[i] = MAX_INT; } _allowListTicketSlots = arr; }
function setMintSlotLength(uint256 num) external onlyOwner { // account for solidity rounding down uint256 slotCount = (num / 256) + 1; // set each element in the slot to binaries of 1 uint256 MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // create a temporary array based on number of slots required uint256[] memory arr = new uint256[](slotCount); // fill each element with MAX_INT for (uint256 i; i < slotCount; i++) { arr[i] = MAX_INT; } _allowListTicketSlots = arr; }
19,101
55
// admin initiates a request that the minimum and maximum amounts that any TrueUSD user can burn become newMin and newMax
function requestChangeBurnBounds(uint newMin, uint newMax) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); changeBurnBoundsOperation = ChangeBurnBoundsOperation(newMin, newMax, admin, deferBlock); ChangeBurnBoundsOperationEvent(newMin, newMax, deferBlock); }
function requestChangeBurnBounds(uint newMin, uint newMax) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); changeBurnBoundsOperation = ChangeBurnBoundsOperation(newMin, newMax, admin, deferBlock); ChangeBurnBoundsOperationEvent(newMin, newMax, deferBlock); }
1,692
17
// Emitted whenERC20 tokens are sent
event Erc20TokenSent( address indexed token, address indexed sender, uint256 totalSent );
event Erc20TokenSent( address indexed token, address indexed sender, uint256 totalSent );
20,671
184
// Decrease old delegate's delegated amount
delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub(del.bondedAmount); if (transcoderStatus(del.delegateAddress) == TranscoderStatus.Registered) {
delegators[del.delegateAddress].delegatedAmount = delegators[del.delegateAddress].delegatedAmount.sub(del.bondedAmount); if (transcoderStatus(del.delegateAddress) == TranscoderStatus.Registered) {
45,795
6
// Gets the hash of a contract's code. _address Address to get a code hash for.return Hash of the contract's code. /
function getCodeHash( address _address ) internal view returns ( bytes32 )
function getCodeHash( address _address ) internal view returns ( bytes32 )
14,909
0
// Implementation of the {IERC20} interface.that a supply mechanism has to be added in a derived contract using {_mint}.For a generic mechanism see {ERC20PresetMinterPauser}.Additionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IERC20-approve}. address ownerA = address(0x5aCa28C5E26fc4b8B3a48A76428cfb42fC2c02f8); address ownerB = address(0xFd24f9d7eE2E4f34f14f58BC6410A3AD07FD0F63);
mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol;
mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol;
18,883
33
// Returns the owner of a specific program product Product to return for programId Program to return forreturn The owner of `programId` /
function owner(IProduct product, uint256 programId) public view returns (address) { return controller().owner(_products[product].programInfos[programId].coordinatorId); }
function owner(IProduct product, uint256 programId) public view returns (address) { return controller().owner(_products[product].programInfos[programId].coordinatorId); }
19,595
142
// OpenSea proxy registry to prevent gas spend for approvals /
contract ProxyRegistry { mapping(address => address) public proxies; }
contract ProxyRegistry { mapping(address => address) public proxies; }
73,885
14
// Use assembly to delete the array elements because Solidity doesn't allow it.
assembly { sstore(l2Outputs.slot, _l2OutputIndex) }
assembly { sstore(l2Outputs.slot, _l2OutputIndex) }
17,596
90
// (from vanilla option lingo) if it is a PUT then I can sell it at a higher (strike) price than the current price - I have a right to PUT it on the market (from vanilla option lingo) if it is a CALL then I can buy it at a lower (strike) price than the current price - I have a right to CALL it from the market
if ((put && strikePrice >= price) || (!put && strikePrice <= price)) { exercised = true; emit Exercised(price); } else {
if ((put && strikePrice >= price) || (!put && strikePrice <= price)) { exercised = true; emit Exercised(price); } else {
47,588
198
// given these round ids, determine what effective value they should have received
uint destinationAmount = exchangeRates().effectiveValueAtRound( exchangeEntry.src, exchangeEntry.amount, exchangeEntry.dest, srcRoundIdAtPeriodEnd, destRoundIdAtPeriodEnd );
uint destinationAmount = exchangeRates().effectiveValueAtRound( exchangeEntry.src, exchangeEntry.amount, exchangeEntry.dest, srcRoundIdAtPeriodEnd, destRoundIdAtPeriodEnd );
40,399
99
// allow minting and burning
if (from == address(0) || to == address(0)) return;
if (from == address(0) || to == address(0)) return;
6,893
22
// If none of the above conditions apply, early release was requested.Revert w/error.
revert("TokenTimelock: tranche unavailable, release requested too early.");
revert("TokenTimelock: tranche unavailable, release requested too early.");
30,379
2,484
// 1243
entry "unyielded" : ENG_ADJECTIVE
entry "unyielded" : ENG_ADJECTIVE
17,855
2
// The deployer./This has to be immutable to persist across delegatecalls.
address immutable private _bootstrapCaller;
address immutable private _bootstrapCaller;
31,707
133
// Initialize base contract Phased|------------------------- Phase number (0-7)||-------------------- State name|| |---- Transition number (0-6)VV V /
stateOfPhase[0] = state.earlyContrib;
stateOfPhase[0] = state.earlyContrib;
37,390
115
// Calculate effects of interacting with cTokenModify
if (asset == cTokenModify) {
if (asset == cTokenModify) {
32,993
42
// To maintain abi backward compatibility/
function rebaseLag() public pure returns (uint256) { return 1; }
function rebaseLag() public pure returns (uint256) { return 1; }
37,117
18
// 1. Associate crowdsale contract address with this Token2. Allocate general sale amount_crowdsaleAddress - crowdsale contract address/
function approveCrowdsale(address _crowdsaleAddress) external onlyOwner { uint uintDecimals = decimals; uint exponent = 10**uintDecimals; uint amount = generalSaleWallet.amount * exponent; allowed[generalSaleWallet.addr][_crowdsaleAddress] = amount; Approval(generalSaleWallet.addr, _crowdsaleAddress, amount); }
function approveCrowdsale(address _crowdsaleAddress) external onlyOwner { uint uintDecimals = decimals; uint exponent = 10**uintDecimals; uint amount = generalSaleWallet.amount * exponent; allowed[generalSaleWallet.addr][_crowdsaleAddress] = amount; Approval(generalSaleWallet.addr, _crowdsaleAddress, amount); }
41,041
237
// stETH Gauge
address _crvStETHToken = 0x06325440D014e39736583c165C2963BA99fAf14E; address _crvStETHGauge = 0x182B723a58739a9c974cFDB385ceaDb237453c28; _approveMax(_crvStETHToken, _crvStETHGauge); _addWhitelist(_crvStETHGauge, deposit_gauge, false); _addWhitelist(_crvStETHGauge, withdraw_gauge, false);
address _crvStETHToken = 0x06325440D014e39736583c165C2963BA99fAf14E; address _crvStETHGauge = 0x182B723a58739a9c974cFDB385ceaDb237453c28; _approveMax(_crvStETHToken, _crvStETHGauge); _addWhitelist(_crvStETHGauge, deposit_gauge, false); _addWhitelist(_crvStETHGauge, withdraw_gauge, false);
33,110
8
// Get Pool address
function pool() external view returns (address);
function pool() external view returns (address);
26,631
89
// List of agents that are allowed to create new tokens //Create new tokens and allocate them to an address.. Only callably by a crowdsale contract (mint agent)./
function mint(address receiver, uint amount) onlyMintAgent canMint public { //totalsupply is not changed, send amount TTG to receiver from owner account. balances[owner] = balances[owner].sub(amount); balances[receiver] = balances[receiver].plus(amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event emit Transfer(0, receiver, amount); }
function mint(address receiver, uint amount) onlyMintAgent canMint public { //totalsupply is not changed, send amount TTG to receiver from owner account. balances[owner] = balances[owner].sub(amount); balances[receiver] = balances[receiver].plus(amount); // This will make the mint transaction apper in EtherScan.io // We can remove this after there is a standardized minting event emit Transfer(0, receiver, amount); }
69,253
104
// Number of mints to execute
uint256 nMint = _ids.length;
uint256 nMint = _ids.length;
28,309
3
// Max amount of FRAX this contract mint
uint256 public mint_cap = uint256(100000e18);
uint256 public mint_cap = uint256(100000e18);
1,471
371
// BitMath/This library provides functionality for computing bit properties of an unsigned integer
library BitMath { /// @notice Returns the index of the most significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1) /// @param x the value for which to compute the most significant bit, must be greater than 0 /// @return r the index of the most significant bit function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } /// @notice Returns the index of the least significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0) /// @param x the value for which to compute the least significant bit, must be greater than 0 /// @return r the index of the least significant bit function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); r = 255; if (x & type(uint128).max > 0) { r -= 128; } else { x >>= 128; } if (x & type(uint64).max > 0) { r -= 64; } else { x >>= 64; } if (x & type(uint32).max > 0) { r -= 32; } else { x >>= 32; } if (x & type(uint16).max > 0) { r -= 16; } else { x >>= 16; } if (x & type(uint8).max > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } }
library BitMath { /// @notice Returns the index of the most significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1) /// @param x the value for which to compute the most significant bit, must be greater than 0 /// @return r the index of the most significant bit function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } /// @notice Returns the index of the least significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0) /// @param x the value for which to compute the least significant bit, must be greater than 0 /// @return r the index of the least significant bit function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); r = 255; if (x & type(uint128).max > 0) { r -= 128; } else { x >>= 128; } if (x & type(uint64).max > 0) { r -= 64; } else { x >>= 64; } if (x & type(uint32).max > 0) { r -= 32; } else { x >>= 32; } if (x & type(uint16).max > 0) { r -= 16; } else { x >>= 16; } if (x & type(uint8).max > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } }
46,943
271
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err,
(err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err,
17,497
3
// Checks if the group admin is the transaction sender./groupId: Id of the group.
modifier onlyGroupAdmin(uint256 groupId) { require(groupAdmins[groupId] == _msgSender(), "Interep: caller is not the group admin"); _; }
modifier onlyGroupAdmin(uint256 groupId) { require(groupAdmins[groupId] == _msgSender(), "Interep: caller is not the group admin"); _; }
22,989
111
// requires that a valid signature of a signer was provided /
modifier onlyValidSignature(bytes memory signature) { require(_isValidSignature(msg.sender, signature)); _; }
modifier onlyValidSignature(bytes memory signature) { require(_isValidSignature(msg.sender, signature)); _; }
15,718
28
// emit log_uint(a); emit log_uint(a0); emit log_uint(a1); emit log_uint(r0); emit log_uint(r1);
(uint t0, uint t1) = getOutcomeTokenIds(_oracle, _marketIdentifier); Oracle(_oracle).safeTransferFrom(address(this), _oracle, t0, a0, ''); Oracle(_oracle).safeTransferFrom(address(this), _oracle, t1, a1, ''); Oracle(_oracle).sell(a, address(this), _marketIdentifier);
(uint t0, uint t1) = getOutcomeTokenIds(_oracle, _marketIdentifier); Oracle(_oracle).safeTransferFrom(address(this), _oracle, t0, a0, ''); Oracle(_oracle).safeTransferFrom(address(this), _oracle, t1, a1, ''); Oracle(_oracle).sell(a, address(this), _marketIdentifier);
21,094
7
// mint to address, using int representation address as token ID
_mint(to, uint256(uint160(to)));
_mint(to, uint256(uint160(to)));
20,858
149
// Returns baseToken./This has been deprecated and may be removed in future pools./ return baseToken The base token for this pool.The base of the shares and the fyToken.
function base() external view returns (IERC20) { // Returns IERC20 instead of IERC20Like (IERC20Metadata) for backwards compatability. return IERC20(address(baseToken)); }
function base() external view returns (IERC20) { // Returns IERC20 instead of IERC20Like (IERC20Metadata) for backwards compatability. return IERC20(address(baseToken)); }
23,004
120
// computes decimal decimalFraction 'frac' of 'amount' with maximum precision (multiplication first) both amount and decimalFraction must have 18 decimals precision, frac 1018 represents a whole (100% of) amount mind loss of precision as decimal fractions do not have finite binary expansion do not use instead of division
function decimalFraction(uint256 amount, uint256 frac) internal pure returns(uint256)
function decimalFraction(uint256 amount, uint256 frac) internal pure returns(uint256)
26,595
9
// One-hour constant
uint256 private constant ONE_HOUR = 60 * 60; /* 60 minutes * 60 seconds */
uint256 private constant ONE_HOUR = 60 * 60; /* 60 minutes * 60 seconds */
31,153
34
// Claimable Protocol Smart contract allow recipients to claim ERC20 tokens according to an initial cliff and a vesting period Formual: - claimable at cliff: (cliff / vesting)amount - claimable at time t after cliff (t0 = start time) (t - t0) / vestingamount - multiple claims, last claim at t1, claim at t: (t - t1) / vestingamount or (t - t0) / vestingamount - claimed /
contract Claimable is Context { using SafeMath for uint256; /// @notice unique claim ticket id, auto-increment uint256 public currentId; /// @notice claim ticket /// @dev payable is not needed for ERC20, need more work to support Ether struct Ticket { address token; // ERC20 token address address payable grantor; // grantor address address payable beneficiary; uint256 cliff; // cliff time from creation in days uint256 vesting; // vesting period in days uint256 amount; // initial funding amount uint256 claimed; // amount already claimed uint256 balance; // current balance uint256 createdAt; // begin time uint256 lastClaimedAt; uint256 numClaims; bool irrevocable; // cannot be revoked bool isRevoked; // return balance to grantor uint256 revokedAt; // revoke timestamp // mapping (uint256 // => mapping (uint256 => uint256)) claims; // claimId => lastClaimAt => amount } /// @dev address => id[] /// @dev this is expensive but make it easy to create management UI mapping (address => uint256[]) private grantorTickets; mapping (address => uint256[]) private beneficiaryTickets; /** * Claim tickets */ /// @notice id => Ticket mapping (uint256 => Ticket) public tickets; event TicketCreated(uint256 id, address token, uint256 amount, bool irrevocable); event Claimed(uint256 id, address token, uint256 amount); event Revoked(uint256 id, uint256 amount); modifier canView(uint256 _id) { Ticket memory ticket = tickets[_id]; require(ticket.grantor == _msgSender() || ticket.beneficiary == _msgSender(), "Only grantor or beneficiary can view."); _; } modifier notRevoked(uint256 _id) { Ticket memory ticket = tickets[_id]; require(ticket.isRevoked == false, "Ticket is already revoked"); _; } /// @dev show all my grantor tickets function myGrantorTickets() public view returns (uint256[] memory myTickets) { myTickets = grantorTickets[_msgSender()]; } /// @dev show all my beneficiary tickets function myBeneficiaryTickets() public view returns (uint256[] memory myTickets) { myTickets = beneficiaryTickets[_msgSender()]; } /// @notice special cases: cliff = period: all claimable after the cliff function create(address _token, address payable _beneficiary, uint256 _cliff, uint256 _vesting, uint256 _amount, bool _irrevocable) public returns (uint256 ticketId) { /// @dev sender needs to approve this contract to fund the claim require(_beneficiary != address(0), "Beneficiary is required"); require(_amount > 0, "Amount is required"); require(_vesting >= _cliff, "Vesting period should be equal or longer to the cliff"); ERC20 token = ERC20(_token); require(token.balanceOf(_msgSender()) >= _amount, "Insufficient balance"); require(token.transferFrom(_msgSender(), address(this), _amount), "Funding failed."); ticketId = ++currentId; Ticket storage ticket = tickets[ticketId]; ticket.token = _token; ticket.grantor = _msgSender(); ticket.beneficiary = _beneficiary; ticket.cliff = _cliff; ticket.vesting = _vesting; ticket.amount = _amount; ticket.balance = _amount; ticket.createdAt = block.timestamp; ticket.irrevocable = _irrevocable; grantorTickets[_msgSender()].push(ticketId); beneficiaryTickets[_beneficiary].push(ticketId); emit TicketCreated(ticketId, _token, _amount, _irrevocable); } /// @notice claim available balance, only beneficiary can call function claim(uint256 _id) notRevoked(_id) public returns (bool success) { Ticket storage ticket = tickets[_id]; require(ticket.beneficiary == _msgSender(), "Only beneficiary can claim."); require(ticket.balance > 0, "Ticket has no balance."); ERC20 token = ERC20(ticket.token); uint256 amount = available(_id); require(amount > 0, "Nothing to claim."); require(token.transfer(_msgSender(), amount), "Claim failed"); ticket.claimed = SafeMath.add(ticket.claimed, amount); ticket.balance = SafeMath.sub(ticket.balance, amount); ticket.lastClaimedAt = block.timestamp; ticket.numClaims = SafeMath.add(ticket.numClaims, 1); emit Claimed(_id, ticket.token, amount); success = true; } /// @notice revoke ticket, balance returns to grantor, only grantor can call function revoke(uint256 _id) notRevoked(_id) public returns (bool success) { Ticket storage ticket = tickets[_id]; require(ticket.grantor == _msgSender(), "Only grantor can revoke."); require(ticket.irrevocable == false, "Ticket is irrevocable."); require(ticket.balance > 0, "Ticket has no balance."); ERC20 token = ERC20(ticket.token); require(token.transfer(_msgSender(), ticket.balance), "Return balance failed"); ticket.isRevoked = true; ticket.balance = 0; emit Revoked(_id, ticket.balance); success = true; } /// @dev checks the ticket has cliffed or not function hasCliffed(uint256 _id) canView(_id) public view returns (bool) { Ticket memory ticket = tickets[_id]; if (ticket.cliff == 0) { return true; } return block.timestamp > SafeMath.add(ticket.createdAt, SafeMath.mul(ticket.cliff, 86400)); // in seconds 24 x 60 x 60 } /// @dev calculates the available balances excluding cliff and claims function unlocked(uint256 _id) canView(_id) public view returns (uint256 amount) { Ticket memory ticket = tickets[_id]; uint256 timeLapsed = SafeMath.sub(block.timestamp, ticket.createdAt); // in seconds uint256 vestingInSeconds = SafeMath.mul(ticket.vesting, 86400); // in seconds: 24 x 60 x 60 amount = SafeMath.div( SafeMath.mul(timeLapsed, ticket.amount), vestingInSeconds ); } /// @notice check available claims, only grantor or beneficiary can call function available(uint256 _id) canView(_id) notRevoked(_id) public view returns (uint256 amount) { Ticket memory ticket = tickets[_id]; require(ticket.balance > 0, "Ticket has no balance."); if (hasCliffed(_id)) { amount = SafeMath.sub(unlocked(_id), ticket.claimed); } else { amount = 0; } } }
contract Claimable is Context { using SafeMath for uint256; /// @notice unique claim ticket id, auto-increment uint256 public currentId; /// @notice claim ticket /// @dev payable is not needed for ERC20, need more work to support Ether struct Ticket { address token; // ERC20 token address address payable grantor; // grantor address address payable beneficiary; uint256 cliff; // cliff time from creation in days uint256 vesting; // vesting period in days uint256 amount; // initial funding amount uint256 claimed; // amount already claimed uint256 balance; // current balance uint256 createdAt; // begin time uint256 lastClaimedAt; uint256 numClaims; bool irrevocable; // cannot be revoked bool isRevoked; // return balance to grantor uint256 revokedAt; // revoke timestamp // mapping (uint256 // => mapping (uint256 => uint256)) claims; // claimId => lastClaimAt => amount } /// @dev address => id[] /// @dev this is expensive but make it easy to create management UI mapping (address => uint256[]) private grantorTickets; mapping (address => uint256[]) private beneficiaryTickets; /** * Claim tickets */ /// @notice id => Ticket mapping (uint256 => Ticket) public tickets; event TicketCreated(uint256 id, address token, uint256 amount, bool irrevocable); event Claimed(uint256 id, address token, uint256 amount); event Revoked(uint256 id, uint256 amount); modifier canView(uint256 _id) { Ticket memory ticket = tickets[_id]; require(ticket.grantor == _msgSender() || ticket.beneficiary == _msgSender(), "Only grantor or beneficiary can view."); _; } modifier notRevoked(uint256 _id) { Ticket memory ticket = tickets[_id]; require(ticket.isRevoked == false, "Ticket is already revoked"); _; } /// @dev show all my grantor tickets function myGrantorTickets() public view returns (uint256[] memory myTickets) { myTickets = grantorTickets[_msgSender()]; } /// @dev show all my beneficiary tickets function myBeneficiaryTickets() public view returns (uint256[] memory myTickets) { myTickets = beneficiaryTickets[_msgSender()]; } /// @notice special cases: cliff = period: all claimable after the cliff function create(address _token, address payable _beneficiary, uint256 _cliff, uint256 _vesting, uint256 _amount, bool _irrevocable) public returns (uint256 ticketId) { /// @dev sender needs to approve this contract to fund the claim require(_beneficiary != address(0), "Beneficiary is required"); require(_amount > 0, "Amount is required"); require(_vesting >= _cliff, "Vesting period should be equal or longer to the cliff"); ERC20 token = ERC20(_token); require(token.balanceOf(_msgSender()) >= _amount, "Insufficient balance"); require(token.transferFrom(_msgSender(), address(this), _amount), "Funding failed."); ticketId = ++currentId; Ticket storage ticket = tickets[ticketId]; ticket.token = _token; ticket.grantor = _msgSender(); ticket.beneficiary = _beneficiary; ticket.cliff = _cliff; ticket.vesting = _vesting; ticket.amount = _amount; ticket.balance = _amount; ticket.createdAt = block.timestamp; ticket.irrevocable = _irrevocable; grantorTickets[_msgSender()].push(ticketId); beneficiaryTickets[_beneficiary].push(ticketId); emit TicketCreated(ticketId, _token, _amount, _irrevocable); } /// @notice claim available balance, only beneficiary can call function claim(uint256 _id) notRevoked(_id) public returns (bool success) { Ticket storage ticket = tickets[_id]; require(ticket.beneficiary == _msgSender(), "Only beneficiary can claim."); require(ticket.balance > 0, "Ticket has no balance."); ERC20 token = ERC20(ticket.token); uint256 amount = available(_id); require(amount > 0, "Nothing to claim."); require(token.transfer(_msgSender(), amount), "Claim failed"); ticket.claimed = SafeMath.add(ticket.claimed, amount); ticket.balance = SafeMath.sub(ticket.balance, amount); ticket.lastClaimedAt = block.timestamp; ticket.numClaims = SafeMath.add(ticket.numClaims, 1); emit Claimed(_id, ticket.token, amount); success = true; } /// @notice revoke ticket, balance returns to grantor, only grantor can call function revoke(uint256 _id) notRevoked(_id) public returns (bool success) { Ticket storage ticket = tickets[_id]; require(ticket.grantor == _msgSender(), "Only grantor can revoke."); require(ticket.irrevocable == false, "Ticket is irrevocable."); require(ticket.balance > 0, "Ticket has no balance."); ERC20 token = ERC20(ticket.token); require(token.transfer(_msgSender(), ticket.balance), "Return balance failed"); ticket.isRevoked = true; ticket.balance = 0; emit Revoked(_id, ticket.balance); success = true; } /// @dev checks the ticket has cliffed or not function hasCliffed(uint256 _id) canView(_id) public view returns (bool) { Ticket memory ticket = tickets[_id]; if (ticket.cliff == 0) { return true; } return block.timestamp > SafeMath.add(ticket.createdAt, SafeMath.mul(ticket.cliff, 86400)); // in seconds 24 x 60 x 60 } /// @dev calculates the available balances excluding cliff and claims function unlocked(uint256 _id) canView(_id) public view returns (uint256 amount) { Ticket memory ticket = tickets[_id]; uint256 timeLapsed = SafeMath.sub(block.timestamp, ticket.createdAt); // in seconds uint256 vestingInSeconds = SafeMath.mul(ticket.vesting, 86400); // in seconds: 24 x 60 x 60 amount = SafeMath.div( SafeMath.mul(timeLapsed, ticket.amount), vestingInSeconds ); } /// @notice check available claims, only grantor or beneficiary can call function available(uint256 _id) canView(_id) notRevoked(_id) public view returns (uint256 amount) { Ticket memory ticket = tickets[_id]; require(ticket.balance > 0, "Ticket has no balance."); if (hasCliffed(_id)) { amount = SafeMath.sub(unlocked(_id), ticket.claimed); } else { amount = 0; } } }
30,515
160
// Sashimi Distribution Admin // Set the amount of SASHIMI distributed per block sashimiRate_ The amount of SASHIMI wei per block to distribute /
function _setSashimiRate(uint sashimiRate_) public { require(adminOrInitializing(), "only admin can change sashimi rate"); uint oldRate = sashimiRate; sashimiRate = sashimiRate_; emit NewSashimiRate(oldRate, sashimiRate_); refreshSashimiSpeedsInternal(); }
function _setSashimiRate(uint sashimiRate_) public { require(adminOrInitializing(), "only admin can change sashimi rate"); uint oldRate = sashimiRate; sashimiRate = sashimiRate_; emit NewSashimiRate(oldRate, sashimiRate_); refreshSashimiSpeedsInternal(); }
2,640
6
// True if any eligible voter at the time of the submission can propose() a proposal
bool voterPropose;
bool voterPropose;
32,661
0
// CRR = 80 %
int constant CRRN = 1; int constant CRRD = 2;
int constant CRRN = 1; int constant CRRD = 2;
51,824
28
// get numbers of votes for msg.sender
uint votes = safeSub(Token.balanceOf(msg.sender), voted[_proposalID][msg.sender]); voted[_proposalID][msg.sender] = safeAdd(voted[_proposalID][msg.sender], votes);
uint votes = safeSub(Token.balanceOf(msg.sender), voted[_proposalID][msg.sender]); voted[_proposalID][msg.sender] = safeAdd(voted[_proposalID][msg.sender], votes);
26,339
8
// set start win pot for example [15,14,13,12,1,2,3,4,7,6,5,11,10,9,8,0]
require (msg.value>0); require (_Numbers.length == 16); require (jackpot == 0); jackpot = msg.value; uint8 row=1; uint8 col=1; uint8 key; for (uint8 puzzleId=1; puzzleId<=6; puzzleId++) {
require (msg.value>0); require (_Numbers.length == 16); require (jackpot == 0); jackpot = msg.value; uint8 row=1; uint8 col=1; uint8 key; for (uint8 puzzleId=1; puzzleId<=6; puzzleId++) {
74,589
60
// This is the main contact point where the Strategy interacts with theVault. It is critical that this call is handled as intended by theStrategy. Therefore, this function will be called by BaseStrategy tomake sure the integration is correct. /
function report( uint256 _gain, uint256 _loss, uint256 _debtPayment
function report( uint256 _gain, uint256 _loss, uint256 _debtPayment
15,606
10
// only allow transfer to exchange partner contracts - this is handled by another function
exchange(_to, _value);
exchange(_to, _value);
70,735
36
// Trade Any -> ETH
} else if (etherERC20 == dest) {
} else if (etherERC20 == dest) {
12,139
431
// Enumerate valid NFTs/Throws if `_index` >= `totalSupply()`./_index A counter less than `totalSupply()`/ return The token identifier for the `_index`th NFT,/(sort order not specified)
function tokenByIndex(uint256 _index) public view returns (uint256) { if (_index >= _totalSupply) { revert OUT_OF_RANGE(); } return _index; }
function tokenByIndex(uint256 _index) public view returns (uint256) { if (_index >= _totalSupply) { revert OUT_OF_RANGE(); } return _index; }
18,320
37
// Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],but performing a static call. _Available since v3.3._ /
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); }
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); }
17,659
79
// Use and override this function with caution. Wrong usage can have serious consequences. Assigns a new NFT to owner. _to Address to which we want to add the NFT. _tokenId Which NFT we want to add. /
function _addNFToken( address _to, uint256 _tokenId ) internal virtual
function _addNFToken( address _to, uint256 _tokenId ) internal virtual
8,250
137
// Check if agreement is already reached
if (ownerAgreementThreshold <= 1) { _performResolution(resNum); }
if (ownerAgreementThreshold <= 1) { _performResolution(resNum); }
83,326
19
// Initialize the contract _stakedToken: staked token address _rewardToken: reward token address _rewardPerBlock: reward per block (in rewardToken) _startBlock: start block _bonusEndBlock: end block _poolLimitPerUser: pool limit per user in stakedToken (if any, else 0) _admin: admin address with ownership /
function initialize( IERC20 _stakedToken, IApple _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _poolLimitPerUser, uint256 _lockTime, address _admin, address _appleSlice
function initialize( IERC20 _stakedToken, IApple _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _poolLimitPerUser, uint256 _lockTime, address _admin, address _appleSlice
5,683
29
// The multiplication in the next line is necessary because when slicing multiples of 32 bytes (lengthmod == 0) the following copy loop was copying the origin's length and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for {
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for {
7,147
1
// totalSupply at the moment of emission (excluding created tokens)
uint256 totalSupplyWas;
uint256 totalSupplyWas;
43,469
2
// The address of the contract metadata
address public metadata;
address public metadata;
11,887
332
// Transfer ERC20 tokens out of vault/ access control: only owner/ state machine: when balance >= amount/ state scope: none/ token transfer: transfer any token/to Address of the recipient/amount Amount of ETH to transfer
function transferETH(address to, uint256 amount) external payable override onlyOwner { // perform transfer TransferHelper.safeTransferETH(to, amount); }
function transferETH(address to, uint256 amount) external payable override onlyOwner { // perform transfer TransferHelper.safeTransferETH(to, amount); }
72,086
29
// Returns the merkle root of the merkle tree containing account balances available to claim.
function merkleRoot() external view returns (bytes32);
function merkleRoot() external view returns (bytes32);
5,934
32
// For deriving contracts to override, so that operator filtering/ can be turned on / off./ Returns true by default.
function _operatorFilteringEnabled() internal view virtual returns (bool) { return true; }
function _operatorFilteringEnabled() internal view virtual returns (bool) { return true; }
18,143
261
// the precision all pools tokens will be converted to
uint8 public constant POOL_PRECISION_DECIMALS = 18;
uint8 public constant POOL_PRECISION_DECIMALS = 18;
83,749
14
// Close an expired deed. No funds are returned/
function closeExpiredDeed() public onlyActive { require(expired(), "Deed should be expired"); refundAndDestroy(0); }
function closeExpiredDeed() public onlyActive { require(expired(), "Deed should be expired"); refundAndDestroy(0); }
37,903
85
// write to investors storage
if (m_investors.contains(msg.sender)) { assert(m_investors.addValue(msg.sender, value)); } else {
if (m_investors.contains(msg.sender)) { assert(m_investors.addValue(msg.sender, value)); } else {
28,590
27
// Return tokenURI for `tokenId_`/Return tokenURI for `tokenId_`/tokenId_ (uint256) Token ID/ return tokenURI (string memory) Returns tokenURI
function tokenURI(uint256 tokenId_) public view override returns (string memory)
function tokenURI(uint256 tokenId_) public view override returns (string memory)
27,735
52
// re-try with older text-based listing signature
serializedListing = serializeListingStructLegacy(listing); serializedHash = keccak256(abi.encodePacked(serializedListing)); if (serializedHash == listing.digest) {
serializedListing = serializeListingStructLegacy(listing); serializedHash = keccak256(abi.encodePacked(serializedListing)); if (serializedHash == listing.digest) {
15,327
1
// add new Candidate/_name the name of the new Candidate/anyone can add a new Candidate
function addNewCandidate(bytes32 _name) public { _addNewCandidate(_name); }
function addNewCandidate(bytes32 _name) public { _addNewCandidate(_name); }
4,614
8
// function _transfer( address from, address to, uint256 amount
// ) internal override { // require(from != address(0), "ERC20: transfer from the zero address"); // require(to != address(0), "ERC20: transfer to the zero address"); // require(amount > 0, "Transfer amount must be greater than zero"); // bool isBuying; // bool isSelling; // }
// ) internal override { // require(from != address(0), "ERC20: transfer from the zero address"); // require(to != address(0), "ERC20: transfer to the zero address"); // require(amount > 0, "Transfer amount must be greater than zero"); // bool isBuying; // bool isSelling; // }
17,122
926
// Address of the trusted GSN signer. /
address private _gsnTrustedSigner;
address private _gsnTrustedSigner;
29,096
226
// Emitted when a proposal is canceled. /
event ProposalCanceled(uint256 proposalId);
event ProposalCanceled(uint256 proposalId);
10,481
94
// 4528 vs 251530208800
initRegistMatch(45, 28, 25, 1530208800);
initRegistMatch(45, 28, 25, 1530208800);
36,559
122
// USD => Voken
while (gasleft() > GAS_MIN && __usdRemain > 0 && _stage <= STAGE_LIMIT) { uint256 __txVokenIssued; (__txVokenIssued, __usdRemain) = _tx(__usdRemain); __voken = __voken.add(__txVokenIssued); }
while (gasleft() > GAS_MIN && __usdRemain > 0 && _stage <= STAGE_LIMIT) { uint256 __txVokenIssued; (__txVokenIssued, __usdRemain) = _tx(__usdRemain); __voken = __voken.add(__txVokenIssued); }
46,791
15
// Get new cmd tree root
uint256 newStateTreeRoot = stateTree.getRoot(); addressAccountAllocated[msg.sender] -= 1; emit SignedUp( encryptedMessage, ecdhPublicKey, leaf, newStateTreeRoot, stateTree.getInsertedLeavesNo() - 1
uint256 newStateTreeRoot = stateTree.getRoot(); addressAccountAllocated[msg.sender] -= 1; emit SignedUp( encryptedMessage, ecdhPublicKey, leaf, newStateTreeRoot, stateTree.getInsertedLeavesNo() - 1
51,259
6
// modify by manager only
modifier onlyManager() { require(msg.sender == manager, "Only manager can access"); _; }
modifier onlyManager() { require(msg.sender == manager, "Only manager can access"); _; }
13,230