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
293
// calculates number of keys received given X eth _curEth current amount of eth in contract _newEth eth being spentreturn amount of ticket purchased /
function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256)
function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256)
15,910
430
// Reverts if `_validators` has any duplicates. _domain The domain of the outbox the validator set is for. _validators The set of validator addresses. _threshold The quorum threshold. Must be greater than or equalto the length of `_validators`. /
constructor( uint32 _domain, address[] memory _validators, uint256 _threshold
constructor( uint32 _domain, address[] memory _validators, uint256 _threshold
665
34
// Gets the approved address for a token ID, or zero if no address set _tokenId uint256 ID of the token to query the approval ofreturn address currently approved for the given token ID /
function getApproved(uint256 _tokenId) public view returns (address) { return storageContract.getAddress(keccak256("patent.token.approvals", _tokenId)); }
function getApproved(uint256 _tokenId) public view returns (address) { return storageContract.getAddress(keccak256("patent.token.approvals", _tokenId)); }
6,150
22
// This method relies on extcodesize/address.code.length, which returns 0 for contracts in construction, since the code is only stored at the end of the constructor execution.
return account.code.length > 0;
return account.code.length > 0;
709
6
// requires lp token transfer from proxy to msg.sender
shares = IHypervisor(pos).deposit(deposit0, deposit1, address(this)); IHypervisor(pos).transfer(to, shares);
shares = IHypervisor(pos).deposit(deposit0, deposit1, address(this)); IHypervisor(pos).transfer(to, shares);
74,036
455
// calculates the user data across the reserves.this includes the total liquidity/collateral/borrow balances in ETH,the average Loan To Value, the average Liquidation Ratio, and the Health factor. _user the address of the userreturn the total liquidity, total collateral, total borrow balances of the user in ETH.also the average Ltv, liquidation threshold, and the health factor /
{ IPriceOracleGetter oracle = IPriceOracleGetter( addressesProvider.getPriceOracle() ); // Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables UserGlobalDataLocalVars memory vars; address[] memory reserves = core.getReserves(); for (uint256 i = 0; i < reserves.length; i++) { vars.currentReserve = reserves[i]; ( vars.compoundedLiquidityBalance, vars.compoundedBorrowBalance, vars.originationFee, vars.userUsesReserveAsCollateral ) = core.getUserBasicReserveData(vars.currentReserve, _user); if ( vars.compoundedLiquidityBalance == 0 && vars.compoundedBorrowBalance == 0 ) { continue; } //fetch reserve data ( vars.reserveDecimals, vars.baseLtv, vars.liquidationThreshold, vars.usageAsCollateralEnabled ) = core.getReserveConfiguration(vars.currentReserve); vars.tokenUnit = 10**vars.reserveDecimals; vars.reserveUnitPrice = oracle.getAssetPrice(vars.currentReserve); //liquidity and collateral balance if (vars.compoundedLiquidityBalance > 0) { uint256 liquidityBalanceETH = vars .reserveUnitPrice .mul(vars.compoundedLiquidityBalance) .div(vars.tokenUnit); totalLiquidityBalanceETH = totalLiquidityBalanceETH.add( liquidityBalanceETH ); if ( vars.usageAsCollateralEnabled && vars.userUsesReserveAsCollateral ) { totalCollateralBalanceETH = totalCollateralBalanceETH.add( liquidityBalanceETH ); currentLtv = currentLtv.add( liquidityBalanceETH.mul(vars.baseLtv) ); currentLiquidationThreshold = currentLiquidationThreshold .add( liquidityBalanceETH.mul(vars.liquidationThreshold) ); } } if (vars.compoundedBorrowBalance > 0) { totalBorrowBalanceETH = totalBorrowBalanceETH.add( vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div( vars.tokenUnit ) ); totalFeesETH = totalFeesETH.add( vars.originationFee.mul(vars.reserveUnitPrice).div( vars.tokenUnit ) ); } } currentLtv = totalCollateralBalanceETH > 0 ? currentLtv.div(totalCollateralBalanceETH) : 0; currentLiquidationThreshold = totalCollateralBalanceETH > 0 ? currentLiquidationThreshold.div(totalCollateralBalanceETH) : 0; healthFactor = calculateHealthFactorFromBalancesInternal( totalCollateralBalanceETH, totalBorrowBalanceETH, totalFeesETH, currentLiquidationThreshold ); healthFactorBelowThreshold = healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD; }
{ IPriceOracleGetter oracle = IPriceOracleGetter( addressesProvider.getPriceOracle() ); // Usage of a memory struct of vars to avoid "Stack too deep" errors due to local variables UserGlobalDataLocalVars memory vars; address[] memory reserves = core.getReserves(); for (uint256 i = 0; i < reserves.length; i++) { vars.currentReserve = reserves[i]; ( vars.compoundedLiquidityBalance, vars.compoundedBorrowBalance, vars.originationFee, vars.userUsesReserveAsCollateral ) = core.getUserBasicReserveData(vars.currentReserve, _user); if ( vars.compoundedLiquidityBalance == 0 && vars.compoundedBorrowBalance == 0 ) { continue; } //fetch reserve data ( vars.reserveDecimals, vars.baseLtv, vars.liquidationThreshold, vars.usageAsCollateralEnabled ) = core.getReserveConfiguration(vars.currentReserve); vars.tokenUnit = 10**vars.reserveDecimals; vars.reserveUnitPrice = oracle.getAssetPrice(vars.currentReserve); //liquidity and collateral balance if (vars.compoundedLiquidityBalance > 0) { uint256 liquidityBalanceETH = vars .reserveUnitPrice .mul(vars.compoundedLiquidityBalance) .div(vars.tokenUnit); totalLiquidityBalanceETH = totalLiquidityBalanceETH.add( liquidityBalanceETH ); if ( vars.usageAsCollateralEnabled && vars.userUsesReserveAsCollateral ) { totalCollateralBalanceETH = totalCollateralBalanceETH.add( liquidityBalanceETH ); currentLtv = currentLtv.add( liquidityBalanceETH.mul(vars.baseLtv) ); currentLiquidationThreshold = currentLiquidationThreshold .add( liquidityBalanceETH.mul(vars.liquidationThreshold) ); } } if (vars.compoundedBorrowBalance > 0) { totalBorrowBalanceETH = totalBorrowBalanceETH.add( vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div( vars.tokenUnit ) ); totalFeesETH = totalFeesETH.add( vars.originationFee.mul(vars.reserveUnitPrice).div( vars.tokenUnit ) ); } } currentLtv = totalCollateralBalanceETH > 0 ? currentLtv.div(totalCollateralBalanceETH) : 0; currentLiquidationThreshold = totalCollateralBalanceETH > 0 ? currentLiquidationThreshold.div(totalCollateralBalanceETH) : 0; healthFactor = calculateHealthFactorFromBalancesInternal( totalCollateralBalanceETH, totalBorrowBalanceETH, totalFeesETH, currentLiquidationThreshold ); healthFactorBelowThreshold = healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD; }
30,837
323
// Remap the last item in the array to this index
beneficiaries[idx] = beneficiaries[beneficiaries.length - 1]; beneficiaryIndexByAddress[address(beneficiaries[idx])] = idx + 1;
beneficiaries[idx] = beneficiaries[beneficiaries.length - 1]; beneficiaryIndexByAddress[address(beneficiaries[idx])] = idx + 1;
35,659
4
// Copy function signature and arguments from calldata at zero position into memory at pointer position
calldatacopy(ptr, 0, calldatasize())
calldatacopy(ptr, 0, calldatasize())
29,374
28
// array where we'll store location IDs
tokenIds = new uint256[](locs.length);
tokenIds = new uint256[](locs.length);
8,048
3
// Internal implementation of the function issue. /
function _issueAs(address issuer, uint64 supply, bytes memory data)
function _issueAs(address issuer, uint64 supply, bytes memory data)
5,509
18
// require that candidate registration is still open
require(electionPhases() == 1);
require(electionPhases() == 1);
19,337
32
// Execute swap Calls
bytes[] memory returnData = new bytes[](calls.length); address tmpSwapFromToken; for (uint256 i = 0; i < calls.length; i++) { tmpSwapFromToken = calls[i].swapFromToken; bool isTokenNative = tmpSwapFromToken == ETH; if (isTokenNative == false) approveMax(tmpSwapFromToken, calls[i].spender, calls[i].amount); (bool success, bytes memory ret) = isTokenNative ? calls[i].target.call{value : calls[i].amount}(calls[i].callData)
bytes[] memory returnData = new bytes[](calls.length); address tmpSwapFromToken; for (uint256 i = 0; i < calls.length; i++) { tmpSwapFromToken = calls[i].swapFromToken; bool isTokenNative = tmpSwapFromToken == ETH; if (isTokenNative == false) approveMax(tmpSwapFromToken, calls[i].spender, calls[i].amount); (bool success, bytes memory ret) = isTokenNative ? calls[i].target.call{value : calls[i].amount}(calls[i].callData)
13,692
19
// See {recover}. /
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
33,172
8
// order does not matter so move last element to the deleted index
ownersLUT[index] = ownersLUT[ownersLUT.length - 1];
ownersLUT[index] = ownersLUT[ownersLUT.length - 1];
10,001
39
// Set the new plug cap for token want to store in it. /
function setPlugUsersLimit(uint256 _newLimit) external onlyOwner { require(_newLimit > plugLimit); plugLimit = _newLimit; }
function setPlugUsersLimit(uint256 _newLimit) external onlyOwner { require(_newLimit > plugLimit); plugLimit = _newLimit; }
4,787
10
// Contains the bit mask selecting bits of the very last character in the TinyString - simply the lowest byte
uint constant internal LAST_CHARACTER_MASK_BITS = 0xFF;
uint constant internal LAST_CHARACTER_MASK_BITS = 0xFF;
37,583
91
// Sets `amount` as the allowance of `spender` over the `owner` s tokens. This internal function is equivalent to `approve`, and can be used toe.g. set automatic allowances for certain subsystems, etc.
* Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
* Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
12,114
21
// Switch to exact status _next status that should be switched to/
function _switchStatus(Statuses _next) internal { status = _next; emit StatusUpdated(uint(_next)); }
function _switchStatus(Statuses _next) internal { status = _next; emit StatusUpdated(uint(_next)); }
9,050
129
// the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev 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, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
* {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev 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, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
1,733
24
// remove keyword from videoInfo.
if (index != len-1) { videoInfo[hash].keywords.index[videoInfo[hash].keywords.array[len-1]] = index+1; videoInfo[hash].keywords.array[index] = videoInfo[hash].keywords.array[len-1]; }
if (index != len-1) { videoInfo[hash].keywords.index[videoInfo[hash].keywords.array[len-1]] = index+1; videoInfo[hash].keywords.array[index] = videoInfo[hash].keywords.array[len-1]; }
31,722
248
// If the User LP token balance in farm is lower than _amount,total User LP tokens in the farm will be withdrawn
if(amount_ > user.amount){ amount_ = user.amount; }
if(amount_ > user.amount){ amount_ = user.amount; }
18,542
199
// Get the balance, minus what we started with
uint256 bnbBalance = address(this).balance.sub(initialBNBBalance);
uint256 bnbBalance = address(this).balance.sub(initialBNBBalance);
32,014
84
// Return the LQTY gain earned by the front end. /
function getFrontEndLQTYGain(address _frontEnd) external view returns (uint);
function getFrontEndLQTYGain(address _frontEnd) external view returns (uint);
14,690
1,804
// STATE MODIFYING FUNCTIONS // This overrides Swap's initialize function to prevent initializingwithout the address of the base Swap contract._pooledTokens an array of ERC20s this pool will accept decimals the decimals to use for each pooled token,eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS lpTokenName the long-form name of the token to be deployed lpTokenSymbol the short symbol for the token to be deployed _a the amplification coefficientn(n - 1). See theStableSwap paper for details _fee default swap fee to be initialized with _adminFee default adminFee to be initialized with /
function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress
function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress
45,373
271
// Burn the box.
_burn(_tokenId); tokensById[_tokenId] = 0;
_burn(_tokenId); tokensById[_tokenId] = 0;
15,723
40
// no checks are performed in this function since those are already present in _stakeWithChecks
_stakeWithChecks(msg.sender, amount, duration);
_stakeWithChecks(msg.sender, amount, duration);
35,791
34
// check the ownership of token
modifier onlyOwnerOf(uint _tokenId) { require(msg.sender == IndexToOwner[_tokenId] || msg.sender == IndexToApproved[_tokenId]); _; }
modifier onlyOwnerOf(uint _tokenId) { require(msg.sender == IndexToOwner[_tokenId] || msg.sender == IndexToApproved[_tokenId]); _; }
6,208
5
// Get the community_list contract
CommunityList COMMUNITY_LIST = CommunityList(GalaxisRegistry.getRegistryAddress("COMMUNITY_LIST"));
CommunityList COMMUNITY_LIST = CommunityList(GalaxisRegistry.getRegistryAddress("COMMUNITY_LIST"));
13,893
3
// 判断地址是否是合约地址 /
function isContract(address addr) view public returns (bool){ uint256 size; assembly { size := extcodesize(addr) } return size > 0; }
function isContract(address addr) view public returns (bool){ uint256 size; assembly { size := extcodesize(addr) } return size > 0; }
31,730
29
// Allows the current admin to set the pendingAdmin address/newAdmin The address to transfer ownership to
function transferAdmin(address newAdmin) public { onlyAdmin(); require(newAdmin != address(0), "new admin 0"); emit TransferAdminPending(newAdmin); pendingAdmin = newAdmin; }
function transferAdmin(address newAdmin) public { onlyAdmin(); require(newAdmin != address(0), "new admin 0"); emit TransferAdminPending(newAdmin); pendingAdmin = newAdmin; }
8,415
277
// change baseURI in case needed for IPFS
function changeBaseURI(string memory baseURI_) public onlyOwner { _currentBaseURI = baseURI_; }
function changeBaseURI(string memory baseURI_) public onlyOwner { _currentBaseURI = baseURI_; }
6,170
369
// Create and deploy a smart wallet for the user and stores the address /
function spawn() external returns (address smartWallet) { require(getSmartWallet[msg.sender] == address(0), 'Already has smart wallet'); bytes memory bytecode = type(SmartWallet).creationCode; bytes32 salt = keccak256(abi.encodePacked(msg.sender)); assembly { smartWallet := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } emit Created(msg.sender, smartWallet); ISmartWallet(smartWallet).initialize(LimitOrderBook, msg.sender); getSmartWallet[msg.sender] = smartWallet; }
function spawn() external returns (address smartWallet) { require(getSmartWallet[msg.sender] == address(0), 'Already has smart wallet'); bytes memory bytecode = type(SmartWallet).creationCode; bytes32 salt = keccak256(abi.encodePacked(msg.sender)); assembly { smartWallet := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } emit Created(msg.sender, smartWallet); ISmartWallet(smartWallet).initialize(LimitOrderBook, msg.sender); getSmartWallet[msg.sender] = smartWallet; }
27,762
95
// Check transaction root index overflow Metadata Roots Index < Second Proof Block Roots Length
assertOrFraud(lt(firstMetadataTransactionRootIndex, selectTransactionRootsLength(selectBlockHeader(SecondProof))), FraudCode_InvalidTransactionRootIndexOverflow)
assertOrFraud(lt(firstMetadataTransactionRootIndex, selectTransactionRootsLength(selectBlockHeader(SecondProof))), FraudCode_InvalidTransactionRootIndexOverflow)
21,435
0
// DNSRecordChanged is emitted whenever a given node/name/resource's RRSET is updated.
event DNSRecordChanged(bytes32 indexed node, bytes name, uint16 resource, bytes record);
event DNSRecordChanged(bytes32 indexed node, bytes name, uint16 resource, bytes record);
34,586
19
// Returns the number of tokens that composes the LP sharesreturn address[] memory of token addresses /
function getSubTokens() external view override returns (address[] memory) { return tokens; }
function getSubTokens() external view override returns (address[] memory) { return tokens; }
66,503
7
// We count on the fact that all shards have IDs starting at 1 and increasing sequentially up to the totalShard count.
uint256 shardId; for (shardId = 1; shardId <= totalShards; shardId++) { if (ownerOf(shardId) == _owner) { result[resultIndex] = shardId; resultIndex++; }
uint256 shardId; for (shardId = 1; shardId <= totalShards; shardId++) { if (ownerOf(shardId) == _owner) { result[resultIndex] = shardId; resultIndex++; }
43,245
17
// function transfer(address to, uint256 value) public returns (bool);
function transfer(address to, uint256 value) public; event Transfer(address indexed from, address indexed to, uint256 value);
function transfer(address to, uint256 value) public; event Transfer(address indexed from, address indexed to, uint256 value);
6,075
29
// Ballot receipt record for a voter
struct Receipt { // @notice Whether or not a vote has been cast bool hasVoted; // @notice Whether or not the voter supports the proposal bool support; // @notice The number of votes the voter had, which were cast uint96 votes; }
struct Receipt { // @notice Whether or not a vote has been cast bool hasVoted; // @notice Whether or not the voter supports the proposal bool support; // @notice The number of votes the voter had, which were cast uint96 votes; }
18,045
11
// only the owner can withdraw the fee and any excess funds (rounding errors)
feeWithdrawn += fee; selfdestruct(owner);
feeWithdrawn += fee; selfdestruct(owner);
56,674
536
// Setting updates
event SetPathToAlphaBeta(address[] oldPath, address[] newPath); event SetPathToUSD(address[] oldPath, address[] newPath); event SetBuyBackRate(uint256 oldBuyBackRate, uint256 newBuyBackRate); event SetTreasury(address oldTreasury, address newTreasury); event SetKeeper(address oldKeeper, address newKeeper); event SetKeeperFee(uint256 oldKeeperFee, uint256 newKeeperFee); event SetPlatform(address oldPlatform, address newPlatform); event SetPlatformFee(uint256 oldPlatformFee, uint256 newPlatformFee); event SetEarlyWithdrawFee(uint256 oldEarlyWithdrawFee, uint256 newEarlyWithdrawFee);
event SetPathToAlphaBeta(address[] oldPath, address[] newPath); event SetPathToUSD(address[] oldPath, address[] newPath); event SetBuyBackRate(uint256 oldBuyBackRate, uint256 newBuyBackRate); event SetTreasury(address oldTreasury, address newTreasury); event SetKeeper(address oldKeeper, address newKeeper); event SetKeeperFee(uint256 oldKeeperFee, uint256 newKeeperFee); event SetPlatform(address oldPlatform, address newPlatform); event SetPlatformFee(uint256 oldPlatformFee, uint256 newPlatformFee); event SetEarlyWithdrawFee(uint256 oldEarlyWithdrawFee, uint256 newEarlyWithdrawFee);
26,539
39
// swap a dynamic origin amount for a fixed target amount/_origin the address of the origin/_target the address of the target/_maxOriginAmount the maximum origin amount/_targetAmount the target amount/_deadline deadline in block number after which the trade will not execute/ return originAmount_ the amount of origin that has been swapped for the target
function targetSwap( address _origin, address _target, uint256 _maxOriginAmount, uint256 _targetAmount, uint256 _deadline ) external deadline(_deadline) transactable
function targetSwap( address _origin, address _target, uint256 _maxOriginAmount, uint256 _targetAmount, uint256 _deadline ) external deadline(_deadline) transactable
45,625
8
// See {Governor-_encodeStateBitmap}. /
error GovernorUnexpectedProposalState(uint256 proposalId, ProposalState current, bytes32 expectedStates);
error GovernorUnexpectedProposalState(uint256 proposalId, ProposalState current, bytes32 expectedStates);
1,445
212
// Revoke `_id` role from `_who`_id ID of the role to be revoked_who Address to revoke the role from/
function revoke(bytes32 _id, address _who) external onlyConfigGovernor { _revoke(_id, _who); }
function revoke(bytes32 _id, address _who) external onlyConfigGovernor { _revoke(_id, _who); }
68,986
474
// EVENTS //TournamentScheduled event. Emitted every time a tournament is scheduled tournamentEndBlock when block.number > tournamentEndBlock, then tournament is eligible to be finished or rescheduled //PVPScheduled event. Emitted every time a tournament is scheduled nextPVPBatleBlock when block.number > nextPVPBatleBlock, then pvp battle is eligible to be finished or rescheduled //PVPNewContender event. Emitted every time a warrior enqueues pvp battleowner Warrior ownerwarriorId Warrior ID that entered PVP queueentranceFee fee in WEI warrior owner payed to enter PVP /
event PVPNewContender(address owner, uint256 warriorId, uint256 entranceFee);
event PVPNewContender(address owner, uint256 warriorId, uint256 entranceFee);
66,413
8
// The time that the listing is scheduled to end
uint32 endTime;
uint32 endTime;
4,096
18
// Counters Matt Condon (@shrugs) Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the numberof elements in a mapping, issuing ERC721 ids, or counting request ids. Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } }
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } }
6,699
91
// The summon numbers of each accouts: will be cleared every day
mapping (address => uint256) public accoutToSummonNum;
mapping (address => uint256) public accoutToSummonNum;
56,203
408
// Do pre-exchange validations
BorrowShared.validateTxPreSell(state, transaction);
BorrowShared.validateTxPreSell(state, transaction);
35,240
9
// Structure to minting informations:/ - amountXIn: The amount of token X sent/ - amountYIn: The amount of token Y sent/ - amountXAddedToPair: The amount of token X that have been actually added to the pair/ - amountYAddedToPair: The amount of token Y that have been actually added to the pair/ - activeFeeX: Fees X currently generated/ - activeFeeY: Fees Y currently generated/ - totalDistributionX: Total distribution of token X. Should be 1e18 (100%) or 0 (0%)/ - totalDistributionY: Total distribution of token Y. Should be 1e18 (100%) or 0 (0%)/ - id: Id of the current working bin when looping
struct MintInfo { uint256 amountXIn; uint256 amountYIn; uint256 amountXAddedToPair; uint256 amountYAddedToPair; uint256 activeFeeX; uint256 activeFeeY; uint256 totalDistributionX; uint256 totalDistributionY; uint256 id; uint256 amountX; uint256 amountY; uint256 distributionX; uint256 distributionY; }
struct MintInfo { uint256 amountXIn; uint256 amountYIn; uint256 amountXAddedToPair; uint256 amountYAddedToPair; uint256 activeFeeX; uint256 activeFeeY; uint256 totalDistributionX; uint256 totalDistributionY; uint256 id; uint256 amountX; uint256 amountY; uint256 distributionX; uint256 distributionY; }
30,619
173
// `_snapshotBalances` is the map that tracks the balance of each address, in thiscontract when the balance changes the block number that the changeoccurred is also included in the map /
mapping(address => Snapshot[]) private _snapshotBalances;
mapping(address => Snapshot[]) private _snapshotBalances;
11,128
11
// Get the approved address for a single NFT. Throws if `_tokenId` is not a valid NFT. _tokenId The NFT to find the approved address for.return Address that _tokenId is approved for. /
function getApproved(
function getApproved(
44,027
148
// assign decimals
hex"60", uint8(18), hex"61010055",
hex"60", uint8(18), hex"61010055",
6,232
98
// timestamp
uint256 lastUpdated, uint256 totalLendingInBucket, uint256 bucketTarget, uint256 buyingSpeed, uint256 withdrawingSpeed, uint256 bucketMaxYield
uint256 lastUpdated, uint256 totalLendingInBucket, uint256 bucketTarget, uint256 buyingSpeed, uint256 withdrawingSpeed, uint256 bucketMaxYield
47,468
41
// Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. _beneficiary Address performing the token purchase _tokenAmount Number of tokens to be emitted /
function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal
function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal
31,507
1,223
// Turns off has debt flag if it has changed
bool contextHasAssetDebt = accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT; if (bitmapHasDebt && !contextHasAssetDebt) {
bool contextHasAssetDebt = accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT; if (bitmapHasDebt && !contextHasAssetDebt) {
63,540
2
// public
function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_msgSender(), supply + i); } }
function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_msgSender(), supply + i); } }
1,151
786
// Locks WETH amount into the CDP
VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this),
VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this),
586
39
// check the sender is the owner of the token or its just been birthed to this token
if (_from != address(0)) { require( ownerOf(_receiverTokenId) == _from, "Cannot add children to tokens you dont own" );
if (_from != address(0)) { require( ownerOf(_receiverTokenId) == _from, "Cannot add children to tokens you dont own" );
18,080
12
// Contract module which provides a basic access control mechanism, wherethere is an account (an owner) that can be granted exclusive access tospecific functions.By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}. * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; address private rewarder = msg.sender; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } modifier onlyRewarder() { require(rewarder == _msgSender(), "Ownable: caller is not the rewarder"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
* can later be changed with {transferOwnership}. * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; address private rewarder = msg.sender; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } modifier onlyRewarder() { require(rewarder == _msgSender(), "Ownable: caller is not the rewarder"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
18,190
311
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
5,415
1
// 判断是否是合约地址 /
function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); }
function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); }
29,764
124
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = safeAdd(tokenBalanceLedger_[_customerAddress], _amountOfTokens); if(!userExists[_referredBy][msg.sender]){ userExists[_referredBy][msg.sender] = true; referralUsers[_referredBy].push(msg.sender); }
tokenBalanceLedger_[_customerAddress] = safeAdd(tokenBalanceLedger_[_customerAddress], _amountOfTokens); if(!userExists[_referredBy][msg.sender]){ userExists[_referredBy][msg.sender] = true; referralUsers[_referredBy].push(msg.sender); }
3,301
16
// Add member to list of all members
allMembers.push(targetMember);
allMembers.push(targetMember);
1,547
168
// Returns the Royalty payment splitter for a particular module.
function getRoyaltyTreasury(address moduleAddress) external view returns (address) { address moduleRoyaltyTreasury = moduleRoyalty[moduleAddress]; if (moduleRoyaltyTreasury == address(0)) { return royaltyTreasury; } return moduleRoyaltyTreasury; }
function getRoyaltyTreasury(address moduleAddress) external view returns (address) { address moduleRoyaltyTreasury = moduleRoyalty[moduleAddress]; if (moduleRoyaltyTreasury == address(0)) { return royaltyTreasury; } return moduleRoyaltyTreasury; }
19,214
80
// Upgrade information
NewUpgradeAgent public upgradeAgent; NextUpgradeAgent public nextUpgradeAgent; bool public finalizedNextUpgrade = false; address public nextUpgradeMaster; event Upgrade(address indexed _from, address indexed _to, uint256 _value);
NewUpgradeAgent public upgradeAgent; NextUpgradeAgent public nextUpgradeAgent; bool public finalizedNextUpgrade = false; address public nextUpgradeMaster; event Upgrade(address indexed _from, address indexed _to, uint256 _value);
12,825
77
// and we're done
break;
break;
14,607
1
// Half the SCALE number.
int256 internal constant HALF_SCALE = 5e17;
int256 internal constant HALF_SCALE = 5e17;
8,569
103
// Modifier to allow actions only when the contract IS paused
modifier whenPaused { require(paused); _; }
modifier whenPaused { require(paused); _; }
59,475
8
// CHECKS check the details match what the marshal has signed
validMint(_msgSender(), to, tokenId, msg.value, expiry, commissionTo, commissionWei, feeTo, marshalSignature);
validMint(_msgSender(), to, tokenId, msg.value, expiry, commissionTo, commissionWei, feeTo, marshalSignature);
13,868
9
// create repair sheet _primaryKey index of database of Modoo's Recall _parts parts to be repaired /
function createRepairSheet ( bytes32 _primaryKey, bytes32 _parts, bytes32 _repairDescription ) public
function createRepairSheet ( bytes32 _primaryKey, bytes32 _parts, bytes32 _repairDescription ) public
28,039
126
// Internal function that transfer tokens from one address to another./ Update magnifiedDividendCorrections to keep dividends unchanged./from The address to transfer from./to The address to transfer to./value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); }
function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); }
6,768
56
// Returns mininum amount of LP tokens needed to qualify for minting a normal NFTNotice a small fudge factor is added as it looks like uniswap sends a tiny amount of LP tokens to the zero address
function MinLPTokens() public view returns (uint){ //Get PPDEX in UniV2 address uint totalPPDEX = IERC20(PPDEX).balanceOf(UniV2Address); //Get Total LP tokens uint totalLP = IUniswapV2ERC20(UniV2Address).totalSupply(); //subtract a small fudge factor return (minPPDEX.mul(totalLP) / totalPPDEX).sub(10000); }
function MinLPTokens() public view returns (uint){ //Get PPDEX in UniV2 address uint totalPPDEX = IERC20(PPDEX).balanceOf(UniV2Address); //Get Total LP tokens uint totalLP = IUniswapV2ERC20(UniV2Address).totalSupply(); //subtract a small fudge factor return (minPPDEX.mul(totalLP) / totalPPDEX).sub(10000); }
45,124
4
// Deploy and setup a royalties recipient for the given edition
function createAndUseRoyaltiesRecipient( uint256 _editionId, address _handler, address[] calldata _recipients, uint256[] calldata _splits ) external returns (address deployedHandler);
function createAndUseRoyaltiesRecipient( uint256 _editionId, address _handler, address[] calldata _recipients, uint256[] calldata _splits ) external returns (address deployedHandler);
2,556
0
// events
event MintedNFT(address sender, uint256 mintAmount);
event MintedNFT(address sender, uint256 mintAmount);
30,349
380
// Set the given supply caps for the given cToken markets. Supplying that brings total supplys to or above supply cap will revert. Admin or supplyCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. If the total borrows already exceeded the cap, it will prevent anyone to borrow. cTokens The addresses of the markets (tokens) to change the supply caps for newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying. /
function _setMarketSupplyCaps(CToken[] calldata cTokens, uint256[] calldata newSupplyCaps) external { require( msg.sender == admin || msg.sender == supplyCapGuardian, "only admin or supply cap guardian can set supply caps" ); uint256 numMarkets = cTokens.length; uint256 numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { supplyCaps[address(cTokens[i])] = newSupplyCaps[i]; emit NewSupplyCap(cTokens[i], newSupplyCaps[i]); } }
function _setMarketSupplyCaps(CToken[] calldata cTokens, uint256[] calldata newSupplyCaps) external { require( msg.sender == admin || msg.sender == supplyCapGuardian, "only admin or supply cap guardian can set supply caps" ); uint256 numMarkets = cTokens.length; uint256 numSupplyCaps = newSupplyCaps.length; require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input"); for (uint256 i = 0; i < numMarkets; i++) { supplyCaps[address(cTokens[i])] = newSupplyCaps[i]; emit NewSupplyCap(cTokens[i], newSupplyCaps[i]); } }
67,010
188
// firstUpline has a place
treeChildren[firstUpline][treeType][cNodeID][i] = treeNode(treeRoot,treeType,treeNodeID);
treeChildren[firstUpline][treeType][cNodeID][i] = treeNode(treeRoot,treeType,treeNodeID);
13,398
19
// get the configuration of the LayerZero messaging library of the specified version_version - messaging library version_chainId - the chainId for the pending config change_userApplication - the contract address of the user application_configType - type of configuration. every messaging library has its own convention.
function getConfig( uint16 _version, uint16 _chainId, address _userApplication, uint256 _configType ) external view returns (bytes memory);
function getConfig( uint16 _version, uint16 _chainId, address _userApplication, uint256 _configType ) external view returns (bytes memory);
55,205
3
// Token symbol
string private _symbol;
string private _symbol;
8,100
246
// No active position to exit, just send all want to controller as per wrapper withdrawAll() function
function _withdrawAll() internal override { // This strategy doesn't do anything when tokens are withdrawn, wBTC stays in strategy until governance decides // what to do with it // When a user withdraws, it is performed via _withdrawSome }
function _withdrawAll() internal override { // This strategy doesn't do anything when tokens are withdrawn, wBTC stays in strategy until governance decides // what to do with it // When a user withdraws, it is performed via _withdrawSome }
32,592
16
// note: see `onlyRoleWithSwitch` for ASSET_ROLE behaviour.
_setupRole(_assetRole, address(0)); _setupDefaultRoyaltyInfo(_royaltyRecipient, _royaltyBps); transferRole = _transferRole; minterRole = _minterRole; assetRole = _assetRole;
_setupRole(_assetRole, address(0)); _setupDefaultRoyaltyInfo(_royaltyRecipient, _royaltyBps); transferRole = _transferRole; minterRole = _minterRole; assetRole = _assetRole;
25,666
153
// View function for getting the current Dharma Smart Walletimplementation contract address set on the upgrade beacon.return The current Dharma Smart Wallet implementation contract. /
function getImplementation() external view returns (address implementation) { (bool ok, bytes memory returnData) = address( 0x0000000000b45D6593312ac9fdE193F3D0633644 ).staticcall(""); if (!(ok && returnData.length == 32)) { revert(_revertReason(39)); } implementation = abi.decode(returnData, (address)); }
function getImplementation() external view returns (address implementation) { (bool ok, bytes memory returnData) = address( 0x0000000000b45D6593312ac9fdE193F3D0633644 ).staticcall(""); if (!(ok && returnData.length == 32)) { revert(_revertReason(39)); } implementation = abi.decode(returnData, (address)); }
7,912
253
// Refund agreement, push dai to lender assets, transfer cdp ownership to borrower if debt is payedreturnOperation success /
function _refund() internal { _pushDaiAsset(lender, _unlockAllDai()); _transferCdpOwnershipToProxy(cdpId, borrower); emit CdpOwnershipTransferred(borrower, cdpId); }
function _refund() internal { _pushDaiAsset(lender, _unlockAllDai()); _transferCdpOwnershipToProxy(cdpId, borrower); emit CdpOwnershipTransferred(borrower, cdpId); }
41,183
102
// Swap
address routerAddress = getRouterAddress(); IDEXRouter router = IDEXRouter(routerAddress); address native = router.WETH(); address pair = IDEXFactory(router.factory()).createPair(native, address(this)); exchanges[pair] = true; taxDistributor = new BasicTaxDistributor(routerAddress, pair, native, 1000, 1000);
address routerAddress = getRouterAddress(); IDEXRouter router = IDEXRouter(routerAddress); address native = router.WETH(); address pair = IDEXFactory(router.factory()).createPair(native, address(this)); exchanges[pair] = true; taxDistributor = new BasicTaxDistributor(routerAddress, pair, native, 1000, 1000);
19,450
68
// in theory Q2 <= targetQuoteTokenAmount however when amount is close to 0, precision problems may cause Q2 > targetQuoteTokenAmount
return DODOMath._SolveQuadraticFunctionForTrade( state.Q0, state.Q0, payBaseAmount, state.i, state.K );
return DODOMath._SolveQuadraticFunctionForTrade( state.Q0, state.Q0, payBaseAmount, state.i, state.K );
66,813
29
// ======= ACTION HELPERS =========
function _handleInFlowData(bytes calldata _inFlowData) internal pure virtual returns(address sellToken, uint128 sellAmount)
function _handleInFlowData(bytes calldata _inFlowData) internal pure virtual returns(address sellToken, uint128 sellAmount)
11,802
10
// Send message over lane.
function send_message(address targetContract, bytes calldata encoded) external payable override nonReentrant returns (uint64) { require(hasRole(OUTBOUND_ROLE, msg.sender), "Lane: NotAuthorized"); require(outboundLaneNonce.latest_generated_nonce - outboundLaneNonce.latest_received_nonce <= MAX_PENDING_MESSAGES, "Lane: TooManyPendingMessages"); require(outboundLaneNonce.latest_generated_nonce < uint64(-1), "Lane: Overflow"); uint64 nonce = outboundLaneNonce.latest_generated_nonce + 1; uint256 fee = msg.value; outboundLaneNonce.latest_generated_nonce = nonce; MessagePayload memory messagePayload = MessagePayload({ sourceAccount: msg.sender, targetContract: targetContract, encoded: encoded }); // finally, save messageData in outbound storage and emit `MessageAccepted` event messages[nonce] = MessageData({ payload: messagePayload, fee: fee // a lowest fee may be required and how to set it }); // TODO:: callback `on_messages_accepted` // message sender prune at most `MAX_PRUNE_MESSAGES_ATONCE` messages prune_messages(MAX_PRUNE_MESSAGES_ATONCE); commit(); emit MessageAccepted(nonce); return nonce; }
function send_message(address targetContract, bytes calldata encoded) external payable override nonReentrant returns (uint64) { require(hasRole(OUTBOUND_ROLE, msg.sender), "Lane: NotAuthorized"); require(outboundLaneNonce.latest_generated_nonce - outboundLaneNonce.latest_received_nonce <= MAX_PENDING_MESSAGES, "Lane: TooManyPendingMessages"); require(outboundLaneNonce.latest_generated_nonce < uint64(-1), "Lane: Overflow"); uint64 nonce = outboundLaneNonce.latest_generated_nonce + 1; uint256 fee = msg.value; outboundLaneNonce.latest_generated_nonce = nonce; MessagePayload memory messagePayload = MessagePayload({ sourceAccount: msg.sender, targetContract: targetContract, encoded: encoded }); // finally, save messageData in outbound storage and emit `MessageAccepted` event messages[nonce] = MessageData({ payload: messagePayload, fee: fee // a lowest fee may be required and how to set it }); // TODO:: callback `on_messages_accepted` // message sender prune at most `MAX_PRUNE_MESSAGES_ATONCE` messages prune_messages(MAX_PRUNE_MESSAGES_ATONCE); commit(); emit MessageAccepted(nonce); return nonce; }
22,148
100
// Precisely divides two ratioed units, by first scaling the left hand operand i.e. How much bAsset is this mAsset worth? x Left hand operand in division ratio bAsset ratioreturnResult after multiplying the left operand by the scale, and executing the division on the right hand input. /
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c)
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c)
27,839
284
// POPDAWG contract Extends ERC721 Non-Fungible Token Standard basic implementation /
contract POPDAWG is ERC721, Ownable { using SafeMath for uint256; string public POPDAWG_PROVENANCE = ""; address payable dev_address; address public admin; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public constant dawgPrice = 28000000000000000; //0.028 ETH, 28000000000000000 uint public constant maxDawgPurchase = 20; uint256 public MAX_DAWG; bool public saleIsActive = false; uint256 public REVEAL_TIMESTAMP; //Monday, December 20, 2021 12:00:00 AM, 1639958400 uint256 public SALE_START; uint256 public PRESALE; constructor(string memory name, string memory symbol) ERC721(name, symbol) { MAX_DAWG = 3888; SALE_START = 1639958400; REVEAL_TIMESTAMP = SALE_START.add(4 days + 16 hours); PRESALE = SALE_START.add(2 hours); dev_address = payable(0x2f5DDdd8703a6E0509Ac0314B2df7f5c374B3982); admin = 0xbE5B09aD1f0c01A7f4995623E434cBc0Dd71Db3f; } modifier onlyAdmin() { require(admin == _msgSender(), "Dev: caller is not the admin"); _; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).send(balance.mul(75).div(100)); dev_address.send(balance.sub(balance.mul(75).div(100))); } function setAdmin(address _admin) public onlyOwner { admin = _admin; } /* * Set provenance once it's calculated */ function setProvenanceHash(string memory provenanceHash) public onlyAdmin { POPDAWG_PROVENANCE = provenanceHash; } function setBaseURI(string memory baseURI) public onlyAdmin { _setBaseURI(baseURI); } /* * Pause sale if active, make active if paused */ function flipSaleState() public onlyAdmin { saleIsActive = !saleIsActive; } /** * Mints POPDAWGS */ function mint(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint DAWG"); require(numberOfTokens <= maxDawgPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_DAWG, "Purchase would exceed max supply of POPDAWGS"); if(block.timestamp > PRESALE){ require(dawgPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); } for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_DAWG) { _safeMint(msg.sender, mintIndex); } } // If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after // the end of pre-sale, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_DAWG || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } /** * Set the starting index for the collection */ function setStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_DAWG; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number - 1)) % MAX_DAWG; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * Set the starting index block for the collection, essentially unblocking * setting starting index */ function emergencySetStartingIndexBlock() public onlyAdmin { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } }
contract POPDAWG is ERC721, Ownable { using SafeMath for uint256; string public POPDAWG_PROVENANCE = ""; address payable dev_address; address public admin; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public constant dawgPrice = 28000000000000000; //0.028 ETH, 28000000000000000 uint public constant maxDawgPurchase = 20; uint256 public MAX_DAWG; bool public saleIsActive = false; uint256 public REVEAL_TIMESTAMP; //Monday, December 20, 2021 12:00:00 AM, 1639958400 uint256 public SALE_START; uint256 public PRESALE; constructor(string memory name, string memory symbol) ERC721(name, symbol) { MAX_DAWG = 3888; SALE_START = 1639958400; REVEAL_TIMESTAMP = SALE_START.add(4 days + 16 hours); PRESALE = SALE_START.add(2 hours); dev_address = payable(0x2f5DDdd8703a6E0509Ac0314B2df7f5c374B3982); admin = 0xbE5B09aD1f0c01A7f4995623E434cBc0Dd71Db3f; } modifier onlyAdmin() { require(admin == _msgSender(), "Dev: caller is not the admin"); _; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).send(balance.mul(75).div(100)); dev_address.send(balance.sub(balance.mul(75).div(100))); } function setAdmin(address _admin) public onlyOwner { admin = _admin; } /* * Set provenance once it's calculated */ function setProvenanceHash(string memory provenanceHash) public onlyAdmin { POPDAWG_PROVENANCE = provenanceHash; } function setBaseURI(string memory baseURI) public onlyAdmin { _setBaseURI(baseURI); } /* * Pause sale if active, make active if paused */ function flipSaleState() public onlyAdmin { saleIsActive = !saleIsActive; } /** * Mints POPDAWGS */ function mint(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint DAWG"); require(numberOfTokens <= maxDawgPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_DAWG, "Purchase would exceed max supply of POPDAWGS"); if(block.timestamp > PRESALE){ require(dawgPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); } for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply(); if (totalSupply() < MAX_DAWG) { _safeMint(msg.sender, mintIndex); } } // If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after // the end of pre-sale, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_DAWG || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } /** * Set the starting index for the collection */ function setStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_DAWG; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number - 1)) % MAX_DAWG; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * Set the starting index block for the collection, essentially unblocking * setting starting index */ function emergencySetStartingIndexBlock() public onlyAdmin { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } }
43,514
4
// Modifier to check if the `msg.sender` is the admin.Only admin address can execute. /
modifier onlyAdmin() { require(msg.sender == admin(), "ACOProxy::onlyAdmin"); _; }
modifier onlyAdmin() { require(msg.sender == admin(), "ACOProxy::onlyAdmin"); _; }
3,446
17
// Calculate length of <order.makerAssetData>
sourceOffset := mload(add(order, 0x140)) // makerAssetData arrayLenBytes := mload(sourceOffset) sourceOffset := add(sourceOffset, 0x20) arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20)
sourceOffset := mload(add(order, 0x140)) // makerAssetData arrayLenBytes := mload(sourceOffset) sourceOffset := add(sourceOffset, 0x20) arrayLenWords := div(add(arrayLenBytes, 0x1F), 0x20)
28,438
522
// Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.Calling this in the constructor of a contract will prevent that contract from being initialized or reinitializedto any version. It is recommended to use this to lock implementation contracts that are designed to be calledthrough proxies. /
function _disableInitializers() internal virtual { _setInitializedVersion(type(uint8).max); }
function _disableInitializers() internal virtual { _setInitializedVersion(type(uint8).max); }
9,234
96
// GYSR utilitiesthis library implements utility methods for the GYSR multiplierand spending mechanics /
library GysrUtils { using MathUtils for int128; // constants uint256 public constant DECIMALS = 18; uint256 public constant GYSR_PROPORTION = 10**(DECIMALS - 2); // 1% /** * @notice compute GYSR bonus as a function of usage ratio, stake amount, * and GYSR spent * @param gysr number of GYSR token applied to bonus * @param amount number of tokens or shares to unstake * @param total number of tokens or shares in overall pool * @param ratio usage ratio from 0 to 1 * @return multiplier value */ function gysrBonus( uint256 gysr, uint256 amount, uint256 total, uint256 ratio ) internal pure returns (uint256) { if (amount == 0) { return 0; } if (total == 0) { return 0; } if (gysr == 0) { return 10**DECIMALS; } // scale GYSR amount with respect to proportion uint256 portion = (GYSR_PROPORTION * total) / 10**DECIMALS; if (amount > portion) { gysr = (gysr * portion) / amount; } // 1 + gysr / (0.01 + ratio) uint256 x = 2**64 + (2**64 * gysr) / (10**(DECIMALS - 2) + ratio); return 10**DECIMALS + (uint256(int256(int128(uint128(x)).logbase10())) * 10**DECIMALS) / 2**64; } }
library GysrUtils { using MathUtils for int128; // constants uint256 public constant DECIMALS = 18; uint256 public constant GYSR_PROPORTION = 10**(DECIMALS - 2); // 1% /** * @notice compute GYSR bonus as a function of usage ratio, stake amount, * and GYSR spent * @param gysr number of GYSR token applied to bonus * @param amount number of tokens or shares to unstake * @param total number of tokens or shares in overall pool * @param ratio usage ratio from 0 to 1 * @return multiplier value */ function gysrBonus( uint256 gysr, uint256 amount, uint256 total, uint256 ratio ) internal pure returns (uint256) { if (amount == 0) { return 0; } if (total == 0) { return 0; } if (gysr == 0) { return 10**DECIMALS; } // scale GYSR amount with respect to proportion uint256 portion = (GYSR_PROPORTION * total) / 10**DECIMALS; if (amount > portion) { gysr = (gysr * portion) / amount; } // 1 + gysr / (0.01 + ratio) uint256 x = 2**64 + (2**64 * gysr) / (10**(DECIMALS - 2) + ratio); return 10**DECIMALS + (uint256(int256(int128(uint128(x)).logbase10())) * 10**DECIMALS) / 2**64; } }
18,232
130
// Gets an element from the list.//_index the index in the list.// return the element at the specified index.
function get(List storage _self, uint256 _index) internal view returns (Data storage) { return _self.elements[_index]; }
function get(List storage _self, uint256 _index) internal view returns (Data storage) { return _self.elements[_index]; }
32,559
179
// User withdraws tokens to the Compound protocol/_tokenAddr The address of the token to be withdrawn/_cTokenAddr CTokens to be withdrawn/_amount Amount of tokens to be withdrawn/_isCAmount If true _amount is cTokens if falls _amount is underlying tokens
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } }
function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } }
33,231
12
// Convenience and rounding functions when dealing with numbers already factored by 1018 or 1027Math operations with safety checks that throw on error/
library SafeMathFixedPoint { using SafeMath for uint256; function mul27(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).add(5 * 10**26).div(10**27); } function mul18(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).add(5 * 10**17).div(10**18); } function div18(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(10**18).add(y.div(2)).div(y); } function div27(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(10**27).add(y.div(2)).div(y); } }
library SafeMathFixedPoint { using SafeMath for uint256; function mul27(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).add(5 * 10**26).div(10**27); } function mul18(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).add(5 * 10**17).div(10**18); } function div18(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(10**18).add(y.div(2)).div(y); } function div27(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(10**27).add(y.div(2)).div(y); } }
2,437
5
// Set nexus governance address
nexusGovernance = _nexus;
nexusGovernance = _nexus;
8,320
67
// TO CALL THIS FUNCTION EASILY, SEND A 0 ETHER TRANSACTION TO THIS CONTRACT WITH EXTRA DATA: 0x7a09588b
function cashoutEOSBetStakeTokens_ALL() public { // just forward to cashoutEOSBetStakeTokens with input as the senders entire balance cashoutEOSBetStakeTokens(balances[msg.sender]); }
function cashoutEOSBetStakeTokens_ALL() public { // just forward to cashoutEOSBetStakeTokens with input as the senders entire balance cashoutEOSBetStakeTokens(balances[msg.sender]); }
46,179
121
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount);
address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount);
32,240
13
// Set time to leave of BNS _name Name of BNS _protocol Protocol of BNS _ttl Time to leave of BNS /
function setTTL(string _name, string _protocol, uint64 _ttl) external onlyRegistrant(_name, _protocol) { require(_name.toSlice().len() > 0, "Name length incorrect"); require(_protocol.toSlice().len() > 0, "Protocol length incorrect"); string memory protocol = ".".toSlice().concat(_protocol.toSlice()); string memory bns = _name.toSlice().concat(protocol.toSlice()); emit NewTTL(_name, _protocol, _ttl); records[bns].ttl = _ttl; }
function setTTL(string _name, string _protocol, uint64 _ttl) external onlyRegistrant(_name, _protocol) { require(_name.toSlice().len() > 0, "Name length incorrect"); require(_protocol.toSlice().len() > 0, "Protocol length incorrect"); string memory protocol = ".".toSlice().concat(_protocol.toSlice()); string memory bns = _name.toSlice().concat(protocol.toSlice()); emit NewTTL(_name, _protocol, _ttl); records[bns].ttl = _ttl; }
31,097
19
// Gets the current votes balance for `account` /
function getVotes(address account) public view returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; }
function getVotes(address account) public view returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; }
13,055