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
23
// 判斷提案是否為REJECTED狀態
modifier isProposalRejected(uint256 _proposalIndex){ require(proposals[_proposalIndex].proposalPhase == ProposalPhase.REJECTED, "not at REJECTED phase."); _; }
modifier isProposalRejected(uint256 _proposalIndex){ require(proposals[_proposalIndex].proposalPhase == ProposalPhase.REJECTED, "not at REJECTED phase."); _; }
15,029
41
// enable trading
tradingActive = true; swapEnabled = true;
tradingActive = true; swapEnabled = true;
28,840
311
// Internal utility function to initiate pve battle, assumes that all battle/requirements have been checked.
function _triggerPVEStart(uint256 _warriorId) internal { // Grab a reference to the warrior from storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Set warrior current action to pve battle warrior.action = uint16(PVE_BATTLE); // Set battle duration ...
function _triggerPVEStart(uint256 _warriorId) internal { // Grab a reference to the warrior from storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Set warrior current action to pve battle warrior.action = uint16(PVE_BATTLE); // Set battle duration ...
78,879
313
// burn staked tokens
(, address scAddress) = qd.getscAddressOfCover(coverId); uint tokenPrice = pool.getTokenPrice(asset);
(, address scAddress) = qd.getscAddressOfCover(coverId); uint tokenPrice = pool.getTokenPrice(asset);
54,580
1
// Address of soldier contract
address soldierContractAddress;
address soldierContractAddress;
45,416
23
// Unset all boosts for the staked team.
NTSUserManager.StakeTeam memory _inStakedteam = userStorage.getInStakedTeam(_staketeam); uint16[] memory _boostIds = _inStakedteam.boostIds; for(uint16 i = 0; i < _boostIds.length; i++) { uint16 _boostId = _boostIds[i]; if(momoToken.ownerOf(_boostId) == msg.sender) {
NTSUserManager.StakeTeam memory _inStakedteam = userStorage.getInStakedTeam(_staketeam); uint16[] memory _boostIds = _inStakedteam.boostIds; for(uint16 i = 0; i < _boostIds.length; i++) { uint16 _boostId = _boostIds[i]; if(momoToken.ownerOf(_boostId) == msg.sender) {
29,349
19
// Blacklist an extension /
function _blacklistExtension(address extension) internal { require(extension != address(this), "Cannot blacklist yourself"); if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } if (!_blacklistedE...
function _blacklistExtension(address extension) internal { require(extension != address(this), "Cannot blacklist yourself"); if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } if (!_blacklistedE...
21,028
25
// GlobalToken Interface
contract GlobalCryptoFund is Owned, GlobalToken { using SafeMath for uint256; /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public minter; /* This creates an array with all balances *...
contract GlobalCryptoFund is Owned, GlobalToken { using SafeMath for uint256; /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public minter; /* This creates an array with all balances *...
31,002
209
// setting initial roles
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(FREEZER_ROLE, _msgSender());
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(FREEZER_ROLE, _msgSender());
11,752
46
// Event emitted when comptroller is changed /
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
19,307
113
// Calculate prizes in CAKE for each bracket by starting from the highest one
for (uint32 i = 0; i < numbersCount; i++) { uint32 j = numbersCount - 1 - i; uint32 transformedWinningNumber = _bracketCalculator[j] + (finalNumber % (uint32(10)**(j + 1))); _lotteries[_lotteryId].countWinnersPerBracket[j] = _numberTicketsPerLotteryId[_lotter...
for (uint32 i = 0; i < numbersCount; i++) { uint32 j = numbersCount - 1 - i; uint32 transformedWinningNumber = _bracketCalculator[j] + (finalNumber % (uint32(10)**(j + 1))); _lotteries[_lotteryId].countWinnersPerBracket[j] = _numberTicketsPerLotteryId[_lotter...
46,672
58
// Only for the owner of the contract. Adds commission to the owner's pending withdrawals./
function addCommissionToPendingWithdrawals(uint32 _canvasId) external onlyOwner stateOwned(_canvasId)
function addCommissionToPendingWithdrawals(uint32 _canvasId) external onlyOwner stateOwned(_canvasId)
4,639
264
// Extension of the ERC721Enumerable contract that integrates a marketplace so that simple lazy-salesand auctions do not have to be done on another contract. This saves gas fees on secondary sales becausebuyers will not have to pay a gas fee to setApprovalForAll for another marketplace contract after buying. Easely wil...
abstract contract EaselyMarketplaceCollection is ERC721Enumerable, Ownable { using ECDSA for bytes32; using Strings for uint256; /** * @dev Auction structure that includes: * * @param address topBidder - Current top bidder who has already paid the price param below. Is * initial...
abstract contract EaselyMarketplaceCollection is ERC721Enumerable, Ownable { using ECDSA for bytes32; using Strings for uint256; /** * @dev Auction structure that includes: * * @param address topBidder - Current top bidder who has already paid the price param below. Is * initial...
37,309
22
// Attach retirement events to an NFT./tokenId The id of the NFT to attach events to./retirementEventIds An array of event ids to associate with the NFT.
function attachRetirementEvents( uint256 tokenId, uint256[] calldata retirementEventIds
function attachRetirementEvents( uint256 tokenId, uint256[] calldata retirementEventIds
21,727
51
// Transfers asset balance between holders wallets._fromId holder id to take from. _toId holder id to give to. _value amount to transfer. _symbol asset symbol. /
function _transferDirect(uint _fromId, uint _toId, uint _value, bytes32 _symbol) internal { assets[_symbol].wallets[_fromId].balance -= _value; assets[_symbol].wallets[_toId].balance += _value; }
function _transferDirect(uint _fromId, uint _toId, uint _value, bytes32 _symbol) internal { assets[_symbol].wallets[_fromId].balance -= _value; assets[_symbol].wallets[_toId].balance += _value; }
29,019
5
// only execute if there's an active season set
modifier requireActiveSeason() { require(seasons.length > 0, 'Series: No active season'); _; }
modifier requireActiveSeason() { require(seasons.length > 0, 'Series: No active season'); _; }
27,239
25
// execute a HTLC
function executeHTLC(uint256 htlcid, string memory hashkey) public { // getting htlc HTLC memory htlc = htlcs[htlcid]; // hashkey must be correct require(htlc.hashlock == sha256(abi.encodePacked(hashkey)), "password is wrong"); // timestamp must be in the future require(bl...
function executeHTLC(uint256 htlcid, string memory hashkey) public { // getting htlc HTLC memory htlc = htlcs[htlcid]; // hashkey must be correct require(htlc.hashlock == sha256(abi.encodePacked(hashkey)), "password is wrong"); // timestamp must be in the future require(bl...
43,548
30
// Increment the funds that can withdrawn for sustainability.
sustainabilityPool[w] = sustainabilityPool[w].add(sustainabilityAmount);
sustainabilityPool[w] = sustainabilityPool[w].add(sustainabilityAmount);
18,961
90
// SPDX-License-Identifier: MIT/ Wrappers over Solidity's arithmetic operations with added overflowchecks. note that this is a stripped down version of open zeppelin's safemath /
contract SafeMath { /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) in...
contract SafeMath { /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) in...
66,967
8
// Event emitted when point list is deployed.
event PointListDeployed(address indexed operator, address indexed addr, address pointList, address owner);
event PointListDeployed(address indexed operator, address indexed addr, address pointList, address owner);
25,300
25
// Updates the minimum and maximum number of validators that can be elected. min The minimum number of validators that can be elected. max The maximum number of validators that can be elected.return True upon success. /
function setElectableValidators(uint256 min, uint256 max) public onlyOwner returns (bool) { require(0 < min, "Minimum electable validators cannot be zero"); require(min <= max, "Maximum electable validators cannot be smaller than minimum"); require( min != electableValidators.min || max != electable...
function setElectableValidators(uint256 min, uint256 max) public onlyOwner returns (bool) { require(0 < min, "Minimum electable validators cannot be zero"); require(min <= max, "Maximum electable validators cannot be smaller than minimum"); require( min != electableValidators.min || max != electable...
16,888
4
// stores royalties for token contract, set in setRoyaltiesByToken() method
mapping(address => RoyaltiesSet) public royaltiesByToken;
mapping(address => RoyaltiesSet) public royaltiesByToken;
1,521
10
// --- Dependency setters ---
function setAddresses( address _priceAggregatorAddress, address _tellorCallerAddress ) external onlyOwner
function setAddresses( address _priceAggregatorAddress, address _tellorCallerAddress ) external onlyOwner
4,318
59
// Storage /
OMIToken public token; OMITokenLock public tokenLock;
OMIToken public token; OMITokenLock public tokenLock;
32,859
18
// If we're checking for an allowlist quantity restriction, ignore the general quantity restriction.
require( _quantity > 0 && (!verifyMaxQuantityPerTransaction || _quantity <= currentClaimPhase.quantityLimitPerTransaction), "invalid quantity." ); require( currentClaimPhase.supplyClaimed + _quantity <= currentClaimPhase.maxClaimableSupply, ...
require( _quantity > 0 && (!verifyMaxQuantityPerTransaction || _quantity <= currentClaimPhase.quantityLimitPerTransaction), "invalid quantity." ); require( currentClaimPhase.supplyClaimed + _quantity <= currentClaimPhase.maxClaimableSupply, ...
20,554
4
// Private Functions//Computes the secure counterpart to a key. _key Key to get a secure key from.return _secureKey Secure version of the key. /
function _getSecureKey(bytes memory _key) private pure returns (bytes memory _secureKey) { return abi.encodePacked(keccak256(_key)); }
function _getSecureKey(bytes memory _key) private pure returns (bytes memory _secureKey) { return abi.encodePacked(keccak256(_key)); }
28,769
383
// Calculate denominator for row 76: x - g^76z.
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x660))) mstore(add(productsPtr, 0x3c0), partialProduct) mstore(add(valuesPtr, 0x3c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x660))) mstore(add(productsPtr, 0x3c0), partialProduct) mstore(add(valuesPtr, 0x3c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
47,246
119
// Adds a new bundle to array/Can only be called by auth addresses if it's not open to public/Strategies need to have the same number of triggers and ids exists/_strategyIds Array of strategyIds that go into a bundle
function createBundle( uint64[] memory _strategyIds
function createBundle( uint64[] memory _strategyIds
41,058
78
// OPERATOR ONLY: Toggle whether anyone can call function, bypassing the callAllowlist _status Boolean indicating whether to allow anyone call /
function updateAnyoneCallable(bool _status) external onlyOperator { anyoneCallable = _status; emit AnyoneCallableUpdated(_status); }
function updateAnyoneCallable(bool _status) external onlyOperator { anyoneCallable = _status; emit AnyoneCallableUpdated(_status); }
11,016
192
// Reset the Rampp surcharge total to zero regardless of value on contract currently./
function resetRamppSurchargeBalance() public isRampp { ramppSurchargeBalance = 0 ether; }
function resetRamppSurchargeBalance() public isRampp { ramppSurchargeBalance = 0 ether; }
6,399
7
// basic info
contract Newuser { struct User { bytes32 name; } struct Message{ bytes32 content; address writtenBy; uint256 timestamp; } // Each address is linked to a user with name, occupation and bio mapping(address => User) public userInfo; // The m...
contract Newuser { struct User { bytes32 name; } struct Message{ bytes32 content; address writtenBy; uint256 timestamp; } // Each address is linked to a user with name, occupation and bio mapping(address => User) public userInfo; // The m...
19,760
1
// >>>>>>>>>>>>>>>>>>>>>>>STATE<<<<<<<<<<<<<<<<<<<<<<<<<< /
IQuantumKeyRing private _keyRing;
IQuantumKeyRing private _keyRing;
67,857
9
// Emitted when a new message is dispatched via Optics leafIndex Index of message's leaf in merkle tree destinationAndNonce Destination and destination-specificnonce combined in single field ((destination << 32) & nonce) messageHash Hash of message; the leaf inserted to the Merkle tree for the message committedRoot the...
event Dispatch( bytes32 indexed messageHash, uint256 indexed leafIndex, uint64 indexed destinationAndNonce, bytes32 committedRoot, bytes message );
event Dispatch( bytes32 indexed messageHash, uint256 indexed leafIndex, uint64 indexed destinationAndNonce, bytes32 committedRoot, bytes message );
4,766
1
// Simulate blockers action. /
function blockerAction() external onlyBlocker { BlockerAction = true; emit BlockerCalled(msg.sender, BlockerAction); }
function blockerAction() external onlyBlocker { BlockerAction = true; emit BlockerCalled(msg.sender, BlockerAction); }
45,814
108
// Withdraws the beneficiary's funds. /
function beneficiaryWithdraw() public { require(_state == State.Closed); _beneficiary.transfer(address(this).balance); }
function beneficiaryWithdraw() public { require(_state == State.Closed); _beneficiary.transfer(address(this).balance); }
33,406
85
// Contract address of the Token contract mints and sends out to compensate losses
IToken public outToken;
IToken public outToken;
25,403
53
// vSPYClaimE18 = ( msg.value /weiDebtCounterVault[_targetCounterVault])vSPYAssetCounterVaultE18[_targetCounterVault];
vSPYClaimE18 = msg.value.mul( vSPYAssetCounterVaultE18[_targetCounterVault] ).div( weiDebtCounterVault[_targetCounterVault] ); require(vSPYClaimE18 <= vSPYAssetCounterVaultE18[_targetCounterVault], "Code Error Branch 1 if you reached this point");
vSPYClaimE18 = msg.value.mul( vSPYAssetCounterVaultE18[_targetCounterVault] ).div( weiDebtCounterVault[_targetCounterVault] ); require(vSPYClaimE18 <= vSPYAssetCounterVaultE18[_targetCounterVault], "Code Error Branch 1 if you reached this point");
64,696
140
//
currentAveragePrices.cumulativeLast20Blocks = currentAveragePrices.cumulativeLast20Blocks.sub(currentAveragePrices.price[i]); currentAveragePrices.price[i] = outTokenFor1WETH; currentAveragePrices.cumulativeLast20Blocks = currentAveragePrices.cumulativeLast20Blocks.add(outTokenFor1WETH)...
currentAveragePrices.cumulativeLast20Blocks = currentAveragePrices.cumulativeLast20Blocks.sub(currentAveragePrices.price[i]); currentAveragePrices.price[i] = outTokenFor1WETH; currentAveragePrices.cumulativeLast20Blocks = currentAveragePrices.cumulativeLast20Blocks.add(outTokenFor1WETH)...
80,446
136
// Max amount that can be swapped based on amount of liquidityAsset in the Balancer Pool
uint256 maxSwapOut = tokenBalanceOut.mul(bPool.MAX_OUT_RATIO()).div(WAD); return tokenAmountOut <= maxSwapOut ? tokenAmountOut : maxSwapOut;
uint256 maxSwapOut = tokenBalanceOut.mul(bPool.MAX_OUT_RATIO()).div(WAD); return tokenAmountOut <= maxSwapOut ? tokenAmountOut : maxSwapOut;
6,011
1
// constants // Position of message bus in the storage. //Penalty in bounty amount percentage charged to staker on revert stake. /
uint8 constant REVOCATION_PENALTY = 150;
uint8 constant REVOCATION_PENALTY = 150;
49,903
3
// Checks if a borrow is allowed borrower Address of the borrower lenderVault Address of the lender vault generalQuoteInfo General quote info (see DataTypesPeerToPeer.sol) quoteTuple Quote tuple (see DataTypesPeerToPeer.sol)return _isAllowed Flag to indicate if the borrow is allowedreturn minNumOfSignersOverwrite Overw...
function isAllowed(
function isAllowed(
38,362
168
// PlaceBidLibrary Set Protocol Default implementation of Rebalancing Set Token placeBid function /
library PlaceBidLibrary { using SafeMath for uint256; /* ============ Internal Functions ============ */ /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @param _coreAddress ...
library PlaceBidLibrary { using SafeMath for uint256; /* ============ Internal Functions ============ */ /* * Place bid during rebalance auction. Can only be called by Core. * * @param _quantity The amount of currentSet to be rebalanced * @param _coreAddress ...
17,384
1
// This event emits when the metadata of a token is changed./ So that the third-party platforms such as NFT market could/ timely update the images and related attributes of the NFT.
event MetadataUpdate(uint256 _tokenId);
event MetadataUpdate(uint256 _tokenId);
1,864
29
// Check loan amount
require(_loanAmount > 0 && _expectedDurationQty > 0, "1");
require(_loanAmount > 0 && _expectedDurationQty > 0, "1");
40,414
85
// Grants `role` to `account`.
* If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()...
* If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()...
1,330
16
// Iterate through all frax pools and calculate all value of collateral in all pools globally
function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 = total...
function globalCollateralValue() public view returns (uint256) { uint256 total_collateral_value_d18 = 0; for (uint i = 0; i < frax_pools_array.length; i++){ // Exclude null addresses if (frax_pools_array[i] != address(0)){ total_collateral_value_d18 = total...
33,515
70
// Returns all tokens registered with the Allocator.return the tokens /
function tokens() external view override returns (IERC20[] memory) { return _tokens; }
function tokens() external view override returns (IERC20[] memory) { return _tokens; }
8,978
126
// Gets previous block in which a randomness request was posted before the given one./_block Block number from which the search will start./ return First block found before the given one, or `0` otherwise.
function getRandomnessPrevBlock(uint256 _block) external view returns (uint256);
function getRandomnessPrevBlock(uint256 _block) external view returns (uint256);
19,734
57
// Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}by `operator` from `from`, this function is called. It must return its Solidity selector to confirm the token transfer.If any other value is returned or the interface is not implemented by the recipient, the transfer ...
function onERC721Received( address operator, address from, uint256 tokenId,
function onERC721Received( address operator, address from, uint256 tokenId,
1,238
114
// Safely mints `tokenId` and transfers it to `to`. Requirements: - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); }
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); }
1,682
19
// If we find an issue with people trying to join games that are in progress, we can change the logic to not allow this and they can only join before a game starts
allowInPlayJoining = !allowInPlayJoining;
allowInPlayJoining = !allowInPlayJoining;
22,567
72
// Allow the contract to approve the mint restart(Voting will be essential in these actions)
function restartMinting() onlyContract cantMint public returns (bool) { mintingFinished = false; MintRestarted(); // Notify the blockchain that the coin minting was restarted return true; }
function restartMinting() onlyContract cantMint public returns (bool) { mintingFinished = false; MintRestarted(); // Notify the blockchain that the coin minting was restarted return true; }
52,849
228
// ========== EVENTS ==========
event PynthExchange( address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress ); bytes32 internal constant PYNTHEXCHANGE_SIG = keccak256("PynthExchange(address,bytes32,uint256,byte...
event PynthExchange( address indexed account, bytes32 fromCurrencyKey, uint256 fromAmount, bytes32 toCurrencyKey, uint256 toAmount, address toAddress ); bytes32 internal constant PYNTHEXCHANGE_SIG = keccak256("PynthExchange(address,bytes32,uint256,byte...
15,990
88
// |/ Will emit default URI log event for corresponding token _id _tokenIDs Array of IDs of tokens to log default URI /
function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } ...
function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } ...
11,546
26
// : Peggy : Peg zone contract for testing one-way transfers from Ethereum to Cosmos, facilitated by a trusted relayer. This contract is NOT intended to be used in production and users are empowered to withdraw their locked funds at any time. /
contract Peggy is Processor { bool public active; address public relayer; mapping(bytes32 => bool) public ids; event LogLock( bytes32 _id, address _from, bytes _to, address _token, uint256 _value, uint256 _nonce ); event LogUnlock( bytes...
contract Peggy is Processor { bool public active; address public relayer; mapping(bytes32 => bool) public ids; event LogLock( bytes32 _id, address _from, bytes _to, address _token, uint256 _value, uint256 _nonce ); event LogUnlock( bytes...
44,490
167
// set price update for current hourly bucket l storage layout struct timestamp timestamp to update price64x64 64x64 fixed point representation of price /
function setPriceUpdate( Layout storage l, uint256 timestamp, int128 price64x64
function setPriceUpdate( Layout storage l, uint256 timestamp, int128 price64x64
23,344
23
// A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } }
library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } }
4,855
22
// Accept ownership of another contract by this contractownable The address of the contract that is getting it's ownership transferred
function acceptOwnership(address ownable) external onlyAdmin { IOwnable(ownable).acceptOwnership(); }
function acceptOwnership(address ownable) external onlyAdmin { IOwnable(ownable).acceptOwnership(); }
24,131
2
// Checks whether a given address (possibleOwner) owns a given token by given contract addresses and the token id itself.This method can only check contracts implementing the ERC721 standard and in addition the CryptoPunks contract(with a custom implementation because it does not implement the ERC721 standard).Does not...
function ownsTokenOfContracts(address possibleOwner, address[] calldata contractAddresses, uint256 tokenId) public view returns (bool[] memory) { bool[] memory result = new bool[](contractAddresses.length); for (uint256 i = 0; i < contractAddresses.length; i++) { result[i] = ownsTokenO...
function ownsTokenOfContracts(address possibleOwner, address[] calldata contractAddresses, uint256 tokenId) public view returns (bool[] memory) { bool[] memory result = new bool[](contractAddresses.length); for (uint256 i = 0; i < contractAddresses.length; i++) { result[i] = ownsTokenO...
33,762
21
// Prepares this contract to validate a signature./hash The hash./dataType The data type associated with the hash./action Action to take./signatureHash keccak256 of the expected signature data.
function prepare( bytes32 hash, DataType dataType, ValidatorAction action, bytes32 signatureHash ) external
function prepare( bytes32 hash, DataType dataType, ValidatorAction action, bytes32 signatureHash ) external
30,488
2
// 62%
winAmount[msg.sender] += 0 ether; return "LOST TURN";
winAmount[msg.sender] += 0 ether; return "LOST TURN";
19,671
190
// enable
_autoSwapAndLiquifyEnabled = true; setTaxLiquify(taxLiquify_, taxLiquifyDecimals_); emit EnabledAutoSwapAndLiquify();
_autoSwapAndLiquifyEnabled = true; setTaxLiquify(taxLiquify_, taxLiquifyDecimals_); emit EnabledAutoSwapAndLiquify();
20,828
495
// All that remains is storing the new Pool balances.
PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { _setTwoTokenPoolCashBalances(poolId, tokens[0], finalBalances[0], tokens[1], finalBalances[1]); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO)...
PoolSpecialization specialization = _getPoolSpecialization(poolId); if (specialization == PoolSpecialization.TWO_TOKEN) { _setTwoTokenPoolCashBalances(poolId, tokens[0], finalBalances[0], tokens[1], finalBalances[1]); } else if (specialization == PoolSpecialization.MINIMAL_SWAP_INFO)...
82,094
37
// setCost() periodically sets the cost of calling the contract
function setCost(uint _cost) public onlyAdmin(msg.sender) returns(bool) { // check for gas cost changes gas = updateGasPrice(); // no need to check for price change...just update and notifiy gas_price = gas; PriceChange(_cost, gas_price); // fire event to notify price has change cost = _cost; // change the...
function setCost(uint _cost) public onlyAdmin(msg.sender) returns(bool) { // check for gas cost changes gas = updateGasPrice(); // no need to check for price change...just update and notifiy gas_price = gas; PriceChange(_cost, gas_price); // fire event to notify price has change cost = _cost; // change the...
54,868
576
// NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney, and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() statement in the Tournament constructor). The result of this function is always guaranteed to be <= _currentBank.
return _currentBank * _incentiveCut / 10000;
return _currentBank * _incentiveCut / 10000;
41,052
5
// Returns the multiplication of two unsigned integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements:- Multiplication cannot overflow. /
function mul(uint a, uint b) internal pure returns (uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { retu...
function mul(uint a, uint b) internal pure returns (uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { retu...
15,620
212
// Function get value by provied key hash. Keys hashes can be found in Sync event emitted by Registry.sol contract. keyHash The key to query the value of. tokenId The token id to set.return Key and value. /
function getByHash(uint256 keyHash, uint256 tokenId) public view whenResolver(tokenId) returns (string memory key, string memory value) { key = hashToKey(keyHash); value = get(key, tokenId); }
function getByHash(uint256 keyHash, uint256 tokenId) public view whenResolver(tokenId) returns (string memory key, string memory value) { key = hashToKey(keyHash); value = get(key, tokenId); }
30,290
69
// safeApprove should only be called when setting an initial allowance,or when resetting it to zero. To increase and decrease it, use'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value));
require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value));
19,748
101
// -----------------------------------------------------------------------------/LockToken contract/defines token locking and unlocking functionality.-----------------------------------------------------------------------------
contract LockToken is BurnToken { //------------------------------------------------------------------------- /// @dev Emits when PLAY tokens become locked for any number of years by /// any mechanism. //------------------------------------------------------------------------- event Lock (address i...
contract LockToken is BurnToken { //------------------------------------------------------------------------- /// @dev Emits when PLAY tokens become locked for any number of years by /// any mechanism. //------------------------------------------------------------------------- event Lock (address i...
14,379
121
// Token information tokenId % 1,000,000 = index of token (i.e. how many were minted before this token) (tokenId / 1,000,000) % 100 = week in which sacrificed occured (from game start) (tokenId / 100,000,000) = number of cultists remaining after sacrifice
let countdown := mod(div(tokenId, 1000000), 100)
let countdown := mod(div(tokenId, 1000000), 100)
17,599
117
// we can accept 0 as minimum because this is called only by a trusted role
uint256 minimum = 0; uint256[4] memory coinAmounts = wrapCoinAmount(yBalance); ICurveFi(curve).add_liquidity( coinAmounts, minimum );
uint256 minimum = 0; uint256[4] memory coinAmounts = wrapCoinAmount(yBalance); ICurveFi(curve).add_liquidity( coinAmounts, minimum );
9,466
113
// Transitively inherit reflection over the same ancestor.
c.reflectOver = midline.reflectOver; circles[nextCircle].reflectOver = midline.reflectOver;
c.reflectOver = midline.reflectOver; circles[nextCircle].reflectOver = midline.reflectOver;
39,189
2
// Hash table size. - Size should be prime for a good average distribution. - Space is preallocated, for efficiency. - Specific value was selected based on gas and averageof collisions.
uint256 constant HASH_TABLE_SIZE = 313;
uint256 constant HASH_TABLE_SIZE = 313;
40,626
5
// Allowances structureWallet addr1 allows addr2 to transfer until 10 tokens[addr1][addr2] = 10 /
mapping( address => mapping(address => uint256) ) private _allowances;
mapping( address => mapping(address => uint256) ) private _allowances;
21,273
132
// The timestamp on and after which the transfer restriction must be lifted.
uint256 public immutable TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN;
uint256 public immutable TRANSFER_RESTRICTION_LIFTED_NO_LATER_THAN;
65,993
64
// The superior Distributor contract /
Distributor public superior;
Distributor public superior;
53,209
6
// Factory for deploying BlacklistManager module /
contract BlacklistTransferManagerFactory is ModuleFactory { /** * @notice Constructor * @param _polyAddress Address of the polytoken * @param _setupCost Setup cost of the module * @param _usageCost Usage cost of the module * @param _subscriptionCost Subscription cost of the module */ ...
contract BlacklistTransferManagerFactory is ModuleFactory { /** * @notice Constructor * @param _polyAddress Address of the polytoken * @param _setupCost Setup cost of the module * @param _usageCost Usage cost of the module * @param _subscriptionCost Subscription cost of the module */ ...
26,243
256
// Make as much capital as possible "free" for the Vault to take. Some slippageis allowed, since when this method is called the strategist is no longer receivingtheir performance fee. The goal is for the strategy to divest as quickly as possiblewhile not suffering exorbitant losses. This function is used during emergen...
function exitPosition() internal virtual returns (uint256 _loss, uint256 _debtPayment);
function exitPosition() internal virtual returns (uint256 _loss, uint256 _debtPayment);
42,673
0
// Creates `_amount` token to `_to`. Must only be called by the owner (WanSwapFarm).
function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); }
function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); }
10,532
360
// Updates user's fees reward
function _updateFeesReward(address account) internal { uint liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity == 0) return; // we can't poke when liquidity is zero (uint256 collect0, uint256 collect1) = _earnFees(); token0PerShareStored = _toke...
function _updateFeesReward(address account) internal { uint liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity == 0) return; // we can't poke when liquidity is zero (uint256 collect0, uint256 collect1) = _earnFees(); token0PerShareStored = _toke...
32,787
181
// Private function to invoke {IERC721Receiver-onERC721Received} on a target contract. `from` - Previous owner of the given token ID.`to` - Target address that will receive the token.`tokenId` - Token ID to be transferred.`_data` - Optional data to send along with the call. Returns whether the call correctly returned t...
function _checkContractOnERC721Received(
function _checkContractOnERC721Received(
8,746
22
// struct for exchange data /
struct linkedBook { uint256 amount; address nextUser; }
struct linkedBook { uint256 amount; address nextUser; }
24,359
14
// Emitted when a studio badge holder claimstheir Age of Valor tokens /
event AgeOfValorClaimedByStudioBadge(
event AgeOfValorClaimedByStudioBadge(
23,746
109
// Transfers all fees or slippage collected by the router to the treasury address/token The address of the token we want to transfer from the router
function sweep(address token) external onlyOwner { if (token == NATIVE_TOKEN) { // transfer native token out of contract (bool success, ) = feeTreasury.call{value: address(this).balance}( "" ); require(success, "transfer failed in sweep"); ...
function sweep(address token) external onlyOwner { if (token == NATIVE_TOKEN) { // transfer native token out of contract (bool success, ) = feeTreasury.call{value: address(this).balance}( "" ); require(success, "transfer failed in sweep"); ...
21,897
11
// See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan intomultiple smaller scans if the collection is large enough to causean out-of-gas error (10K pfp collections should be fine). /
function tokensOfOwner(address owner) external view returns (uint256[] memory) { unchecked { uint256 tokenIdsIdx; address currOwnershipAddr; uint256 tokenIdsLength = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenIdsLength); Token...
function tokensOfOwner(address owner) external view returns (uint256[] memory) { unchecked { uint256 tokenIdsIdx; address currOwnershipAddr; uint256 tokenIdsLength = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenIdsLength); Token...
39,385
175
// Checks for a valid signature authorizing the migration of an account to a new address. This is shared by both the FNDNFT721 and FNDNFTMarket, and the same signature authorizes both. /
abstract contract AccountMigration is FoundationOperatorRole { // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/utils/cryptography function _isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) private view returns (bool) { if (Address.isC...
abstract contract AccountMigration is FoundationOperatorRole { // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/utils/cryptography function _isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) private view returns (bool) { if (Address.isC...
78,385
40
// ███████╗████████╗ █████╗ ████████╗███████╗ ██╔════╝╚══██╔══╝██╔══██╗╚══██╔══╝██╔════╝ ███████╗ ██║ ███████║ ██║ █████╗ ╚════██║ ██║ ██╔══██║ ██║ ██╔══╝ ███████║ ██║ ██║██║ ██║ ███████╗ ╚══════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚══════╝ amount of raised money in wei
uint public weiRaised;
uint public weiRaised;
78,916
7
// to add a new user to the contract to make guesses
function makeUser() public{ users[msg.sender].userAddress = msg.sender; users[msg.sender].tokensBought = 0; userAddresses.push(msg.sender); }
function makeUser() public{ users[msg.sender].userAddress = msg.sender; users[msg.sender].tokensBought = 0; userAddresses.push(msg.sender); }
46,589
1
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> FILE STORAGE: IPFS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ S T A T E @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@...
address private contractOwner;
address private contractOwner;
1,837
25
// Update the total ownership and ensure it's valid
totalOwnership += founderPct;
totalOwnership += founderPct;
14,744
119
// call notifyRewardAmount for all staking tokens.
function notifyRewardAmounts() public { require( stakingTokens.length > 0, "StakingRewardsFactory::notifyRewardAmounts: called before any deploys" ); for (uint256 i = 0; i < stakingTokens.length; i++) { notifyRewardAmount(stakingTokens[i]); } }...
function notifyRewardAmounts() public { require( stakingTokens.length > 0, "StakingRewardsFactory::notifyRewardAmounts: called before any deploys" ); for (uint256 i = 0; i < stakingTokens.length; i++) { notifyRewardAmount(stakingTokens[i]); } }...
28,611
20
// Increment token count
tokenCount++;
tokenCount++;
6,839
131
// @nonce Returns provider's share in WBTC account Provider's addressreturn Provider's share in WBTC /
function shareOf(address user) external view returns (uint256 share) { uint supply = totalSupply(); if (supply > 0) share = totalBalance().mul(balanceOf(user)).div(supply); else share = 0; }
function shareOf(address user) external view returns (uint256 share) { uint supply = totalSupply(); if (supply > 0) share = totalBalance().mul(balanceOf(user)).div(supply); else share = 0; }
12,668
40
// mustWithdraw (wrapper) tries to subtracts any deposited collateral token from the contract and reverts on failure.
function mustWithdraw(address _token, uint256 _amount) public nonReentrant { // make the attempt uint256 result = _withdraw(_token, _amount); // check zero amount condition require(result != ERR_ZERO_AMOUNT, "non-zero amount expected"); // check low balance condition ...
function mustWithdraw(address _token, uint256 _amount) public nonReentrant { // make the attempt uint256 result = _withdraw(_token, _amount); // check zero amount condition require(result != ERR_ZERO_AMOUNT, "non-zero amount expected"); // check low balance condition ...
29,520
5
// Claimable Methods Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations.@custom:a w3box.com /
contract Claimable is Context { using SafeERC20 for IERC20; /** * @dev Withdraws the erc20 tokens or native coins from this contract. * Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()). * @param _token address of the cla...
contract Claimable is Context { using SafeERC20 for IERC20; /** * @dev Withdraws the erc20 tokens or native coins from this contract. * Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()). * @param _token address of the cla...
10,169
17
// push values to flat-arrays
coordinates.push(coordinate); rgba.push(_rgba); prices.push(msg.value); owners.push(msg.sender);
coordinates.push(coordinate); rgba.push(_rgba); prices.push(msg.value); owners.push(msg.sender);
9,500
1
// wraps tokens _amount amount of unwrapped tokens to wrap /
function wrap(uint256 _amount) external;
function wrap(uint256 _amount) external;
5,674
1
// Events
event LogMigrationEnabled( address target );
event LogMigrationEnabled( address target );
20,087
167
// Returns difference over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256)
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256)
6,803
12
// returns all tokens that can mint this SY /
function getTokensIn() external view returns (address[] memory res);
function getTokensIn() external view returns (address[] memory res);
35,401