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
28
// if(!token.transferFrom(receiver,address(this),levelPrice[level])){ revert();}
if (!address(uint160(receiver)).send(levelPrice[level])) { return address(uint160(receiver)).transfer(address(this).balance); }
if (!address(uint160(receiver)).send(levelPrice[level])) { return address(uint160(receiver)).transfer(address(this).balance); }
12,023
5
// Body [1]
'" /><ellipse rx="115.865" ry="220.031" transform="matrix(.933 0 0 0.837977 245.544 567.625)" fill="',
'" /><ellipse rx="115.865" ry="220.031" transform="matrix(.933 0 0 0.837977 245.544 567.625)" fill="',
42,929
455
// A loan offering was canceled before it was used. Any amount less than thetotal for the loan offering can be canceled. /
event LoanOfferingCanceled(
event LoanOfferingCanceled(
72,383
62
// if there is a lockingPeriod, add tokens to record mapping
else _transferLock(_msgSender(),to, tokens); _addRecord(to, tokens, lockingPeriod); return true;
else _transferLock(_msgSender(),to, tokens); _addRecord(to, tokens, lockingPeriod); return true;
77,759
49
// Load the share balance of the vault before withdrawing [gas note - both the smart contract and share value is warmed so this is actually quite a cheap lookup]
uint256 shareBalanceBefore = position.balanceOf(address(this));
uint256 shareBalanceBefore = position.balanceOf(address(this));
11,989
11
// Payment value is larger than the 'price'
require(msg.value >= price, "GCC : INCORRECT PRICE!");
require(msg.value >= price, "GCC : INCORRECT PRICE!");
17,217
8
// only token holders can burn theirtokens
function burn(uint256 amount) external { require(tokenLocked == false, "token locked"); _burn(msg.sender, amount); }
function burn(uint256 amount) external { require(tokenLocked == false, "token locked"); _burn(msg.sender, amount); }
24,150
2
// keccak256("ERC777TokensRecipient")
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
15,730
424
// Create a new stake _amount stake token amount _tier stake tier to stake in /
function newStake(uint256 _amount, uint256 _tier) private nonReentrant whenNotPaused
function newStake(uint256 _amount, uint256 _tier) private nonReentrant whenNotPaused
32,872
2
// Token mint count
uint256 public _mintedTokens;
uint256 public _mintedTokens;
25,961
252
// Any C-level can fix how many seconds per blocks are currently observed.
function setSecondsPerBlock(uint256 secs) external onlyAuthorized { secondsPerBlock = secs; }
function setSecondsPerBlock(uint256 secs) external onlyAuthorized { secondsPerBlock = secs; }
24,075
17
// overrides transfer function to meet tokenomics of TMGO
function _transfer( address sender, address recipient, uint256 amount
function _transfer( address sender, address recipient, uint256 amount
23,968
131
// Thisfunction is called when the sender or receiver is from Pancakerouter address, /
function _transferBothrewardExcludedPCS(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount,uint256 rTransferAmount , uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity) = _getValues(tAmount); uint256 treasuryamount = tAmount .mul(_blackC...
function _transferBothrewardExcludedPCS(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount,uint256 rTransferAmount , uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity) = _getValues(tAmount); uint256 treasuryamount = tAmount .mul(_blackC...
4,549
241
// Put the deed into escrow, thereby taking ownership of it./_deedId The identifier of the deed to place into escrow.
function _escrow(uint256 _deedId) internal { // Throws if the transfer fails deedContract.takeOwnership(_deedId); }
function _escrow(uint256 _deedId) internal { // Throws if the transfer fails deedContract.takeOwnership(_deedId); }
13,379
234
// The total Fei currently boosting Vaults.
uint256 public totalBoosted;
uint256 public totalBoosted;
34,852
8
// mapping to user levels
mapping(address => uint8) public level;
mapping(address => uint8) public level;
8,629
263
// Sets flag on challenge being processed
challenges[challengeID].resolved = true;
challenges[challengeID].resolved = true;
41,212
5
// Admin /
function mintTo(uint256 _phaseId, address[] calldata _accounts) external onlyOwner { PhaseInfo storage phase = phases[_phaseId]; require(phase.seeded, "Need VRF seed"); require(phase.boundary >= _accounts.length, "Out of bound"); for (uint256 i = 0; i < _accounts.length; i++) { address to = _ac...
function mintTo(uint256 _phaseId, address[] calldata _accounts) external onlyOwner { PhaseInfo storage phase = phases[_phaseId]; require(phase.seeded, "Need VRF seed"); require(phase.boundary >= _accounts.length, "Out of bound"); for (uint256 i = 0; i < _accounts.length; i++) { address to = _ac...
22,398
69
// Claim Accrued AAVE. Claim Accrued AAVE Token rewards. amount The amount of rewards to claim. uint(-1) for max. getId ID to retrieve amount. setId ID stores the amount of tokens claimed./
function claim( uint256 amount, uint256 getId, uint256 setId
function claim( uint256 amount, uint256 getId, uint256 setId
4,737
420
// 3. use managerBaseURI with id or not
if (!_managerBaseURIIdentical[manager]) { return string(abi.encodePacked(_managerBaseURI[manager], tokenId.toString())); } else {
if (!_managerBaseURIIdentical[manager]) { return string(abi.encodePacked(_managerBaseURI[manager], tokenId.toString())); } else {
56,295
185
// check if a address is on the whitelist
function isWhitelisted(address toCheck, bytes32[] calldata proof) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(toCheck)); return MerkleProof.verify(proof, _allowedRoot, leaf); }
function isWhitelisted(address toCheck, bytes32[] calldata proof) public view returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(toCheck)); return MerkleProof.verify(proof, _allowedRoot, leaf); }
47,031
46
// local variables for each iteration's repayments and collateral
uint256 repayments; uint256 collateral;
uint256 repayments; uint256 collateral;
2,653
151
// StakingRewards Originally: Synthetix (forked from /Synthetixio/synthetix/contracts/StakingRewards.sol)Changes by: Stability Labs Pty. Ltd. Rewards stakers of a given LP token (a.k.a StakingToken) with RewardsToken, on a pro-rata basisUses an ever increasing 'rewardPerTokenStored' variable to distribute rewardseach t...
contract fZAC is StakingTokenWrapper, RewardsDistributionRecipient { using StableMath for uint256; IERC20 public rewardsToken; uint256 public constant DURATION = 7 days; // Timestamp for current period finish uint256 public periodFinish = 0; // RewardRate for the rest of the PERIOD uint2...
contract fZAC is StakingTokenWrapper, RewardsDistributionRecipient { using StableMath for uint256; IERC20 public rewardsToken; uint256 public constant DURATION = 7 days; // Timestamp for current period finish uint256 public periodFinish = 0; // RewardRate for the rest of the PERIOD uint2...
27,848
50
// Get the approved address for a single NFTThrows if `_tokenId` is not a valid NFT._tokenId The NFT to find the approved address for return Will always return address(this)/
function getApproved(uint256 _tokenId) public view returns (address) { return badges[_tokenId].approval; }
function getApproved(uint256 _tokenId) public view returns (address) { return badges[_tokenId].approval; }
33,939
43
// Swap on 1Split: give _toToken, receive _fromToken
_oneSplitSwap(_toToken, _fromToken, _toAmount, _1SplitMinReturn, _1SplitDistribution);
_oneSplitSwap(_toToken, _fromToken, _toAmount, _1SplitMinReturn, _1SplitDistribution);
9,568
112
// Returns true if the value is in the set. O(1). /
function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); }
function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); }
34,822
33
// Buy Tokens by commiting approved ERC20 tokens to this contract address. _amount Amount of tokens to commit. /
function commitTokens( uint256 _amount, bool readAndAgreedToMarketParticipationAgreement
function commitTokens( uint256 _amount, bool readAndAgreedToMarketParticipationAgreement
60,401
23
// hash the _beneficiary address and the uniqueOfferId to generate the id for struct interest
bytes32 hashCheck = keccak256(abi.encodePacked(_beneficiary,_offerId)); require (interest[hashCheck].provider == address(0),'interest already active'); interest[hashCheck].provider = msg.sender; return hashCheck;
bytes32 hashCheck = keccak256(abi.encodePacked(_beneficiary,_offerId)); require (interest[hashCheck].provider == address(0),'interest already active'); interest[hashCheck].provider = msg.sender; return hashCheck;
12,353
76
// otherwise, fallback to the contract-level payment splitter settings
calculateRevenueSplit( balance, _fallbackPaymentSplitterSettings );
calculateRevenueSplit( balance, _fallbackPaymentSplitterSettings );
28,912
0
// https:github.com/makerdao/dss/blob/master/src/vat.sol
interface VatAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function can(address, address) external view returns (uint256); function hope(address) external; function nope(address) external; function ilks(b...
interface VatAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function can(address, address) external view returns (uint256); function hope(address) external; function nope(address) external; function ilks(b...
39,725
9
// require(msg.value <= monto); uint256 _monto = 1 ether;
require(_target > _amountCollected, "Required Amount Fullfilled"); require(msg.value > 0, "Donacion minima 1 ETH"); _amountCollected += msg.value; donatorsWallets.push(msg.sender); donacion[msg.sender] = msg.value; emit donated(msg.sender, msg.value, block.timestamp);
require(_target > _amountCollected, "Required Amount Fullfilled"); require(msg.value > 0, "Donacion minima 1 ETH"); _amountCollected += msg.value; donatorsWallets.push(msg.sender); donacion[msg.sender] = msg.value; emit donated(msg.sender, msg.value, block.timestamp);
9,103
7
// Clears reverse nametag for owner. /
function clearReverseNametag(string calldata nametag) external { (address _contract, uint256 tokenId) = _resolveNametag(nametag); require(_contract != address(0), "NametagWallet: Nametag not found"); address owner = INametag(_contract).ownerOf(tokenId); require(owner == _msgSender...
function clearReverseNametag(string calldata nametag) external { (address _contract, uint256 tokenId) = _resolveNametag(nametag); require(_contract != address(0), "NametagWallet: Nametag not found"); address owner = INametag(_contract).ownerOf(tokenId); require(owner == _msgSender...
18,331
10
// _calculateOwed calculates and updates the total amount that is owed to an user and updates the user's multiplier to the current value it automatically attempts to pull the token from the source and acknowledge the funds
function _calculateOwed(address user) internal { _pullToken(); ackFunds(); uint256 reward = _userPendingReward(user); owed[user] = owed[user].add(reward); userMultiplier[user] = currentMultiplier; }
function _calculateOwed(address user) internal { _pullToken(); ackFunds(); uint256 reward = _userPendingReward(user); owed[user] = owed[user].add(reward); userMultiplier[user] = currentMultiplier; }
19,079
572
// Initialize a reserve token entity with the given parameters _token The reserve token _gdSupply Initial supply of GD to set the price _tokenSupply Initial supply of reserve token to set the price _reserveRatio The starting reserve ratio _lastExpansion Last time reserve ratio was expanded /
function initializeToken( ERC20 _token, uint256 _gdSupply, uint256 _tokenSupply, uint32 _reserveRatio, uint256 _lastExpansion
function initializeToken( ERC20 _token, uint256 _gdSupply, uint256 _tokenSupply, uint32 _reserveRatio, uint256 _lastExpansion
38,865
185
// Creates a new token type and assigns _initialSupply to an address _maxSupply max supply allowed _initialSupply Optional amount to supply the first owner _uri Optional URI for this token type _data Optional data to pass if receiver is contractreturn tokenId The newly created token ID /
function create( uint256 _maxSupply, uint256 _initialSupply, string calldata _uri, bytes calldata _data
function create( uint256 _maxSupply, uint256 _initialSupply, string calldata _uri, bytes calldata _data
51,630
245
// The controller of this contract can move tokens around at will,this is important to recognize! Confirm that you trust thecontroller of this contract, which in most situations should beanother open source smart contract or 0x0
if (msg.sender != controller) { require(transfersEnabled);
if (msg.sender != controller) { require(transfersEnabled);
46,407
33
// Register a vote with a given support and voting weight. Note: Support is generic and can represent various things depending on the voting system used. /
function _countVote( uint256 proposalId, address account, uint8 support, uint256 weight ) internal virtual;
function _countVote( uint256 proposalId, address account, uint8 support, uint256 weight ) internal virtual;
10,436
141
// Constant for various precisions
uint256 internal constant MULTIPLIER_PRECISION = 1e18;
uint256 internal constant MULTIPLIER_PRECISION = 1e18;
9,638
104
// crowdsale period has finished
block.timestamp >= endTimestamp &&
block.timestamp >= endTimestamp &&
32,911
212
// borrow token to repay flash loan
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0, "Borrow failed");
require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0, "Borrow failed");
82,127
9
// Checks if two users are already friends or not
function checkAlreadyFriends(address pubkey1, address pubkey2) internal view returns(bool) { if(userList[pubkey1].friendList.length > userList[pubkey2].friendList.length) { address tmp = pubkey1; pubkey1 = pubkey2; pubkey2 = tmp; } for(uint i=0; ...
function checkAlreadyFriends(address pubkey1, address pubkey2) internal view returns(bool) { if(userList[pubkey1].friendList.length > userList[pubkey2].friendList.length) { address tmp = pubkey1; pubkey1 = pubkey2; pubkey2 = tmp; } for(uint i=0; ...
4,158
17
// our proposal key will be a hash of our function name + our contracts addressby adding our contracts address to this, we prevent anyone trying to circumvent the proposal&39;s security via external calls.
bytes32 _whatProposal = whatProposal(_whatFunction);
bytes32 _whatProposal = whatProposal(_whatFunction);
2,692
166
// create multiple collectibles minted using erc20 tokens.each collectible has specified uri and casting value. Requirements: senders need to sets the sum of `_values` as the allowance to this contractin ERC20 token in advance./
function mintByERC20Custom(address _addr, string[] memory _uris, uint256[] memory _values,uint256 _burnTime) external returns (uint256[] memory) { require(_uris.length == _values.length, "Inconsistent length"); uint256 totalValue; for (uint256 i = 0; i < _values.length; i++) { re...
function mintByERC20Custom(address _addr, string[] memory _uris, uint256[] memory _values,uint256 _burnTime) external returns (uint256[] memory) { require(_uris.length == _values.length, "Inconsistent length"); uint256 totalValue; for (uint256 i = 0; i < _values.length; i++) { re...
56,343
231
// Synthetix protocol sends SNX staking rewards to a escrow contract that keeps them 52 weeks, until they vest each time we claim the SNX rewards, a VestingEntry is created in the escrow contract for the amount that was owed we need to keep track of those VestingEntries to know when they vest and claim them after they ...
if (entryIDs.length == 0) { return; }
if (entryIDs.length == 0) { return; }
70,690
91
// The oracle will have given you an ID for the VRF keypair they have committed to (let's call it keyHash), and have told you the minimum LINK price for VRF service. Make sure your contract has sufficient LINK, and call requestRandomness(keyHash, fee, seed), where seed is the input you want to generate randomness from....
abstract contract VRFConsumerBase is VRFRequestIDBase { using SafeMath for uint256; /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. * * @dev The VRFCoordinator expects a calling contract to have a method with * @dev this signature, and will trigg...
abstract contract VRFConsumerBase is VRFRequestIDBase { using SafeMath for uint256; /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. * * @dev The VRFCoordinator expects a calling contract to have a method with * @dev this signature, and will trigg...
45,308
92
// TODO keyreturn/
function compressMCPubKey(bytes memory key) internal pure returns (bytes memory newkey) { require(key.length >= 67, "key lenggh is too short"); newkey = slice(key, 0, 35); if (uint8(key[66]) % 2 == 0){ newkey[2] = byte(0x02); } else { newkey[2] = byte(0x...
function compressMCPubKey(bytes memory key) internal pure returns (bytes memory newkey) { require(key.length >= 67, "key lenggh is too short"); newkey = slice(key, 0, 35); if (uint8(key[66]) % 2 == 0){ newkey[2] = byte(0x02); } else { newkey[2] = byte(0x...
16,959
179
// Off-chain whitelist
address private signerAddress; mapping(bytes => bool) private _nonceUsed; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, address _newOwner, address _signerAddress, address ogCollection
address private signerAddress; mapping(bytes => bool) private _nonceUsed; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, address _newOwner, address _signerAddress, address ogCollection
53,380
104
// Interface of the ERC20 standard as defined in the EIP. /
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function symbol() external view returns (string memory); function balanceOf(address account) external view returns (uint256); fu...
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function symbol() external view returns (string memory); function balanceOf(address account) external view returns (uint256); fu...
4,702
41
// Substract `amount` tokens from the specified account's balanceaccountId An account idamount number of tokens /
function balanceSub(uint accountId, uint64 amount) internal validId(accountId)
function balanceSub(uint accountId, uint64 amount) internal validId(accountId)
29,541
2
// Raised when attempting to change/freeze the baseUri after it has been frozen.
error BaseUriFrozen();
error BaseUriFrozen();
6,002
14
// if token is not activated then calculated initial prices based on predefined collateral price and incremental factor. This includes 10% deduction of system fees.
else{ uint tokenPrice = SafeMath.add(100000000000, 10000000000) ; uint divident = SafeMath.div(SafeMath.mul(tokenPrice,10),100); uint taxedPrice = SafeMath.add(tokenPrice, divident); return taxedPrice ; }
else{ uint tokenPrice = SafeMath.add(100000000000, 10000000000) ; uint divident = SafeMath.div(SafeMath.mul(tokenPrice,10),100); uint taxedPrice = SafeMath.add(tokenPrice, divident); return taxedPrice ; }
2,755
33
// Modifiers Allows execution by the contract manager only
modifier managerOnly { require(msg.sender == Manager); _; }
modifier managerOnly { require(msg.sender == Manager); _; }
64,467
1
// whether deposits and withdrawals are paused
bool public paused; uint256 private _lockedProfit;
bool public paused; uint256 private _lockedProfit;
24,081
155
// Returns the number of the first codepoint in the slice. self The slice to operate on.return The number of the first codepoint in the slice. /
function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint...
function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint...
12,607
14
// Returns the amount of cUSD the pool has to invest return uint Amount of cUSD the pool has available/
function getAvailableFunds() public view override returns (uint) { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); return IERC20(stableCoinAddress).balanceOf(address(this)); }
function getAvailableFunds() public view override returns (uint) { address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings"); address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress(); return IERC20(stableCoinAddress).balanceOf(address(this)); }
14,381
187
// No check out of bound because free mint would used up before minting ends./
if(publicGiveAwayCount > 0 && numberMinted(msg.sender) == 0){ ++actualMintCount; --publicGiveAwayCount; }
if(publicGiveAwayCount > 0 && numberMinted(msg.sender) == 0){ ++actualMintCount; --publicGiveAwayCount; }
4,172
28
// Emitted when `value` tokens are moved from one account (`from`) toanother (`to`). Note that `value` may be zero. /
function transfer(address recipient, uint256 amount) public virtual override returns (bool)
function transfer(address recipient, uint256 amount) public virtual override returns (bool)
1,167
502
// calculaate diffrence
uint256 diff = pendingz.sub(depositedWaTokens[toTransmute]);
uint256 diff = pendingz.sub(depositedWaTokens[toTransmute]);
14,699
339
// Creates a new Turbo Safe which supports a specific asset./asset The ERC20 token that the Safe should accept./ return safe The newly deployed Turbo Safe which accepts the provided asset.
function createSafe(ERC20 asset) external requiresAuth returns (TurboSafe safe, uint256 id) { // Create a new Safe using the default authority and provided asset. safe = new TurboSafe(msg.sender, defaultSafeAuthority, asset); // Add the safe to the list of Safes. safes.push(safe); ...
function createSafe(ERC20 asset) external requiresAuth returns (TurboSafe safe, uint256 id) { // Create a new Safe using the default authority and provided asset. safe = new TurboSafe(msg.sender, defaultSafeAuthority, asset); // Add the safe to the list of Safes. safes.push(safe); ...
30,350
10
// notice salt includes stable as well, 3 parameters
bytes32 salt = keccak256(abi.encodePacked(token0, token1, stable)); (_temp0, _temp1, _temp) = (token0, token1, stable);
bytes32 salt = keccak256(abi.encodePacked(token0, token1, stable)); (_temp0, _temp1, _temp) = (token0, token1, stable);
18,970
49
// If tokens are already locked, the functions extendLock or increaseLockAmount should be used to make any changesrequire(tokensLocked(_of, _reason, block.timestamp) == 0);
require(_amount <= transferableBalanceOf(_of)); if (locked[_of][_reason].amount == 0) lockReason[_of].push(_reason); if(tokensLocked(_of, _reason, block.timestamp) == 0){ locked[_of][_reason] = lockToken(_amount, validUntil); }else{
require(_amount <= transferableBalanceOf(_of)); if (locked[_of][_reason].amount == 0) lockReason[_of].push(_reason); if(tokensLocked(_of, _reason, block.timestamp) == 0){ locked[_of][_reason] = lockToken(_amount, validUntil); }else{
15,942
136
// TODO partial close - find out how much
uint256 totalStaked = getTokenStaked(); require(amount <= totalStaked, "too much"); a3_token_to_withdraw = amount.mul(balance_a3).div(totalStaked);
uint256 totalStaked = getTokenStaked(); require(amount <= totalStaked, "too much"); a3_token_to_withdraw = amount.mul(balance_a3).div(totalStaked);
55,681
140
// parses the passed in action arguments to get the arguments for a withdraw action _args general action arguments structurereturn arguments for a withdraw action /
function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) { require( (_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral), "A10" ); require(_args.owner != address(0), "A11"); ...
function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) { require( (_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral), "A10" ); require(_args.owner != address(0), "A11"); ...
63,450
36
// The oracle will have given you an ID for the VRF keypair they have committed to (let's call it keyHash), and have told you the minimum LINK price for VRF service. Make sure your contract has sufficient LINK, and call requestRandomness(keyHash, fee, seed), where seed is the input you want to generate randomness from....
abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. ...
abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. ...
1,007
73
// LGE
lgeEndTime = now.add(3 minutes); lpUnlockTime = now.add(3 minutes); devAddr = _msgSender(); paused = false; emit Transfer(address(0), _msgSender(), _tTotal);
lgeEndTime = now.add(3 minutes); lpUnlockTime = now.add(3 minutes); devAddr = _msgSender(); paused = false; emit Transfer(address(0), _msgSender(), _tTotal);
200
2
// The top bit is a flag to tell if this is a NFI.
uint256 constant TYPE_NF_BIT = 1 << 255; mapping (uint256 => address) nfOwners;
uint256 constant TYPE_NF_BIT = 1 << 255; mapping (uint256 => address) nfOwners;
12,534
135
// it will throw if transfer fails
_nonFungibleContract.transfer(_receiver, _tokenId);
_nonFungibleContract.transfer(_receiver, _tokenId);
49,222
275
// mint options to user
OptionToken option = isLongToken ? longTokens[strikeIndex] : shortTokens[strikeIndex]; option.mint(msg.sender, optionsOut);
OptionToken option = isLongToken ? longTokens[strikeIndex] : shortTokens[strikeIndex]; option.mint(msg.sender, optionsOut);
19,031
8
// this return avoids eg. additional checks on withdraw, when user did not borrow any asset
if (EasyMath.sum(totalBorrowAmounts) == 0) return (0, 0); IPriceProvidersRepository priceProvidersRepository = _params.siloRepository.priceProvidersRepository(); uint256[] memory borrowValues = convertAmountsToValues( priceProvidersRepository, _params.assets, ...
if (EasyMath.sum(totalBorrowAmounts) == 0) return (0, 0); IPriceProvidersRepository priceProvidersRepository = _params.siloRepository.priceProvidersRepository(); uint256[] memory borrowValues = convertAmountsToValues( priceProvidersRepository, _params.assets, ...
26,921
40
// - ERC223 special callback function. callable from another contract. _sender address that sent tokens _origin ERC223 contract address _value amount of transferred tokens. /
function tokenFallback(address _sender, address _origin, uint _value) public returns (bool ok) { // in contract._origin was transfer(_sender, this, _value); // to send all we can // 1. create contract._origin // 2. transfer from this to special address _value tokens. // 3. do...
function tokenFallback(address _sender, address _origin, uint _value) public returns (bool ok) { // in contract._origin was transfer(_sender, this, _value); // to send all we can // 1. create contract._origin // 2. transfer from this to special address _value tokens. // 3. do...
44,952
5
// Verifies that a burn request is signed by a specific account req The payload / burn request.signature The signature produced by an account signing the burn request.returns (success, signer) Result of verification and the recovered address. /
function verify(BurnRequest calldata req, bytes calldata signature) external view returns (bool success, address signer);
function verify(BurnRequest calldata req, bytes calldata signature) external view returns (bool success, address signer);
11,043
9
// Constrctor function
function YourMomTokenCrowdsale(string contractName, address ifSuccessfulSendTo, uint durationInDays, uint howManyTokensAnEtherCanBuy, address addressOfTokenUsedAsReward, address adressOfTokenHolder, uint crowdsaleStartTimeTimestamp, uint ifInFailSafeTimeInDaysAfterDeadlineToReclaimForgottenEther) public { name = con...
function YourMomTokenCrowdsale(string contractName, address ifSuccessfulSendTo, uint durationInDays, uint howManyTokensAnEtherCanBuy, address addressOfTokenUsedAsReward, address adressOfTokenHolder, uint crowdsaleStartTimeTimestamp, uint ifInFailSafeTimeInDaysAfterDeadlineToReclaimForgottenEther) public { name = con...
5,812
58
// =======MaxTransaction=======
mapping(address => bool) private _isExcludedFromMaxTxLimit; bool public maxTransactionLimitEnabled = true; uint256 public maxTransactionAmountBuy; uint256 public maxTransactionAmountSell;
mapping(address => bool) private _isExcludedFromMaxTxLimit; bool public maxTransactionLimitEnabled = true; uint256 public maxTransactionAmountBuy; uint256 public maxTransactionAmountSell;
19,322
4
// Approves a spender [ERC20].Note that using the approve/transferFrom presents a possiblesecurity vulnerability described in:Use transferAndCall to mitigate. db Token storage to operate on. caller Address of the caller passed through the frontend. spender The address of the future spender. amount The allowance of the ...
function approve(TokenStorage db, address caller, address spender, uint amount) public returns (bool success)
function approve(TokenStorage db, address caller, address spender, uint amount) public returns (bool success)
24,146
114
// Function for the frontend to dynamically retrieve the price scaling of sell orders. /
function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256)
function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256)
29,630
6
// FIXME
function approveOwnershipTransfer(address _newOwner) public onlyStatus(Status.PENDING) only(currentBOL)
function approveOwnershipTransfer(address _newOwner) public onlyStatus(Status.PENDING) only(currentBOL)
37,783
60
// This method is used to settle a bet that was mined into an uncle block. At this point the player was shown some bet outcome, but the blockhash at placeBet height is different because of Ethereum chain reorg. We supply a full merkle proof of the placeBet transaction receipt to provide untamperable evidence that uncle...
function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that can...
function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier { // "commit" for bet settlement can only be obtained by hashing a "reveal". uint commit = uint(keccak256(abi.encodePacked(reveal))); Bet storage bet = bets[commit]; // Check that can...
21,624
6
// funding payment checkpoints
int256 sumALastX128; int256 sumBInsideLastX128; int256 sumFpInsideLastX128;
int256 sumALastX128; int256 sumBInsideLastX128; int256 sumFpInsideLastX128;
33,422
9
// for set min burn time /
function setMinBurnTime(uint256 minBurnTime) public onlyGovernance { _minBurnTime = minBurnTime; }
function setMinBurnTime(uint256 minBurnTime) public onlyGovernance { _minBurnTime = minBurnTime; }
34,468
165
// Ok, transfer the Synths to our funds wallet. These do not go in the deposit queue as they aren't for sale as such unless they're sent back in from the funds wallet.
synthdUSD().transferFrom(msg.sender, fundsWallet, synthAmount);
synthdUSD().transferFrom(msg.sender, fundsWallet, synthAmount);
41,213
16
// ------------------------------------------------------------------------ Transfer ownership to another user ------------------------------------------------------------------------
function transferOwnership(address payable _newOwner) public onlyOwner { potentialNewOwner = _newOwner; }
function transferOwnership(address payable _newOwner) public onlyOwner { potentialNewOwner = _newOwner; }
17,136
231
// The default authority to be used by created Safes.
Authority public defaultSafeAuthority;
Authority public defaultSafeAuthority;
36,134
16
// Updates the implementation address for a many-to-oneproxy relationship.implementationID Identifier for the implementation. implementation Address with the runtime code the proxiesshould use. /
function setImplementationAddressManyToOne( bytes32 implementationID, address implementation ) external _owner_
function setImplementationAddressManyToOne( bytes32 implementationID, address implementation ) external _owner_
249
85
// CardGame Betting token for Card Game /
contract CardGame is Ownable, ERC20 { IUniswapV2Router02 public router; IUniswapV2Factory public factory; IUniswapV2Pair public pair; uint private constant INITIAL_SUPPLY = 10_000_000 * 10**8; // Percent of the initial supply that will go to the LP uint constant LP_BPS = 9500; // Percent...
contract CardGame is Ownable, ERC20 { IUniswapV2Router02 public router; IUniswapV2Factory public factory; IUniswapV2Pair public pair; uint private constant INITIAL_SUPPLY = 10_000_000 * 10**8; // Percent of the initial supply that will go to the LP uint constant LP_BPS = 9500; // Percent...
4,491
109
// If fund is running, stop the fund after AUM is returned
if(fundStatus == 4) fundStatus = 5;
if(fundStatus == 4) fundStatus = 5;
33,904
400
// reference to Traits
ITraits public traits;
ITraits public traits;
12,737
2
// using SafeMath for uint256;
address public creator;
address public creator;
3,228
71
// Utility view function that allows clients to query whether a signer's smart wallet can be deployed or has already been owner Signer address /
function canDeploy(address owner) public view returns (bool inexistent) { address wallet = getCreate2Address(owner); assembly { inexistent := eq(extcodesize(wallet), 0) } }
function canDeploy(address owner) public view returns (bool inexistent) { address wallet = getCreate2Address(owner); assembly { inexistent := eq(extcodesize(wallet), 0) } }
7,668
8
// Calculate how many tokens left in this round
uint256 _tokensRemaining = (100000 * SCALAR).sub(tokensSold);
uint256 _tokensRemaining = (100000 * SCALAR).sub(tokensSold);
35,953
216
// Public interface /
function deposit(uint amount) public { checkForStateUpdate(); require(currentState == State.Pooling, "Pooling is already over"); uint poolShares = calculatePoolShares(amount); Participation memory participation = Participation({ startAuctionCount: isDepositTokenTurn() ? ...
function deposit(uint amount) public { checkForStateUpdate(); require(currentState == State.Pooling, "Pooling is already over"); uint poolShares = calculatePoolShares(amount); Participation memory participation = Participation({ startAuctionCount: isDepositTokenTurn() ? ...
24,365
480
// Add a `governance` and a `pendingGovernance` role to the contract, and implements a 2-phased nominatiom process to change the governance./ Also provides a modifier to allow controlling access to functions of the contract.
contract Governable is Context, GovernableInternal { constructor(address _governance) GovernableInternal() { __Governable_init_unchained(_governance); } function _getMsgSender() internal view override returns (address) { return _msgSender(); } }
contract Governable is Context, GovernableInternal { constructor(address _governance) GovernableInternal() { __Governable_init_unchained(_governance); } function _getMsgSender() internal view override returns (address) { return _msgSender(); } }
69,655
25
// Get the XY protocol fee setting of `_token` on chain `_toChainId`/_toChainId Chain Id of the periphery chain/_token YPool token
function _getFeeStructure(uint32 _toChainId, address _token) private view returns (FeeStructure memory) { bytes32 universalTokenId = keccak256(abi.encodePacked(_toChainId, _token)); return feeStructures[universalTokenId]; }
function _getFeeStructure(uint32 _toChainId, address _token) private view returns (FeeStructure memory) { bytes32 universalTokenId = keccak256(abi.encodePacked(_toChainId, _token)); return feeStructures[universalTokenId]; }
35,464
14
// set max debt for address _address address _limit uint256 /
function setDebtLimit(address _address, uint256 _limit) external onlyGovernor { debtLimit[_address] = _limit; }
function setDebtLimit(address _address, uint256 _limit) external onlyGovernor { debtLimit[_address] = _limit; }
21,025
711
// Store the forced withdrawal request data
S.pendingForcedWithdrawals[accountID][tokenID] = ExchangeData.ForcedWithdrawal({ owner: owner, timestamp: uint64(block.timestamp) });
S.pendingForcedWithdrawals[accountID][tokenID] = ExchangeData.ForcedWithdrawal({ owner: owner, timestamp: uint64(block.timestamp) });
19,894
176
// Emits an {AssetAccepted} event. tokenId ID of the token for which to accept the pending asset index Index of the asset in the pending array to accept assetId ID of the asset that is being accepted /
function acceptAsset( uint256 tokenId, uint256 index, uint64 assetId ) public virtual onlyApprovedForAssetsOrOwner(tokenId) { _acceptAsset(tokenId, index, assetId); }
function acceptAsset( uint256 tokenId, uint256 index, uint64 assetId ) public virtual onlyApprovedForAssetsOrOwner(tokenId) { _acceptAsset(tokenId, index, assetId); }
13,043
7
// Merges two NFTs by moving one attribute from one NFTto the other. After the merge, the `_from` NFT is destroyedand its metadata is replaced with an image denoting that. Wecannot burn the NFTs since the creator of the Moon boyz NFTcontract did not add such functionalityWe do not perform any checks on the `_attribute`...
function merge(uint256 _from, uint256 _to, string memory _attribute) public { // Ensure user owns both tokens require(erc721.ownerOf(_from) == msg.sender, "not owner of _from token"); require(erc721.ownerOf(_to) == msg.sender, "not owner of _to token"); // Destroy token by sending it to the burn addr...
function merge(uint256 _from, uint256 _to, string memory _attribute) public { // Ensure user owns both tokens require(erc721.ownerOf(_from) == msg.sender, "not owner of _from token"); require(erc721.ownerOf(_to) == msg.sender, "not owner of _to token"); // Destroy token by sending it to the burn addr...
42,557
191
// collateralToken Collateral token we query borrowing rate for./ return The current borrowing rate.
function getBorrowingRate(IERC20 collateralToken) external view returns (uint256);
function getBorrowingRate(IERC20 collateralToken) external view returns (uint256);
35,869
38
// Contract ownership transfer functions
address public pendingOwner; uint256 public ownerChangeTimeout;
address public pendingOwner; uint256 public ownerChangeTimeout;
35,561
15
// ------------------------------------------------------------------------ Transfer tokens from the from account to the to accountThe calling account must already have sufficient tokens approve(...)-d for spending from the from account and - From account must have sufficient balance to transfer - Spender must have suf...
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from...
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from...
24,282
42
// Token distribution amount
uint256 public _presaleAmount; uint256 public _stakingAmount; uint256 public _cexReseveredAmount; uint256 public _teamAmount; uint256 public _incentiveAmount; uint256 public _dexAmount; uint256 public _airdropAmount;
uint256 public _presaleAmount; uint256 public _stakingAmount; uint256 public _cexReseveredAmount; uint256 public _teamAmount; uint256 public _incentiveAmount; uint256 public _dexAmount; uint256 public _airdropAmount;
30,115