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 |
|---|---|---|---|---|
4 | // Forbid trivial inputs, to avoid ecrecover edge cases. The main thing to avoid is something which causes ecrecover to return 0x0: then trivial signatures could be constructed with the nonceTimesGeneratorAddress input set to 0x0. solium-disable-next-line indentation | require(nonceTimesGeneratorAddress != address(0) && signingPubKeyX > 0 &&
signature > 0 && msgHash > 0, "no zero inputs allowed");
| require(nonceTimesGeneratorAddress != address(0) && signingPubKeyX > 0 &&
signature > 0 && msgHash > 0, "no zero inputs allowed");
| 47,507 |
1 | // Retrieving the buyers | function getBuyers() public view returns (address[16] memory) {
return buyers;
}
| function getBuyers() public view returns (address[16] memory) {
return buyers;
}
| 18,800 |
160 | // Add liquidity to uni | addLiquidity(tokensToAddLiquidityWith, currentbalance);
| addLiquidity(tokensToAddLiquidityWith, currentbalance);
| 33,195 |
141 | // Fill a limit order. The taker and sender will be the caller./order The limit order. ETH protocol fees can be/attached to this call. Any unspent ETH will be refunded to/the caller./signature The order signature./takerTokenFillAmount Maximum taker token amount to fill this order with./ return takerTokenFilledAmount How much maker token was filled./ return makerTokenFilledAmount How much maker token was filled. | function fillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
| function fillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
| 19,416 |
109 | // liquidate relay | BancorConverterInterface(converterAddress).liquidate(_amount);
poolAmountSent = _amount;
| BancorConverterInterface(converterAddress).liquidate(_amount);
poolAmountSent = _amount;
| 1,560 |
8 | // withdraw all the funds | function withdraw() payable onlyOwner public {
msg.sender.transfer(address(this).balance);
//reset funders' balance to 0
for(uint256 funderIndex = 0; funderIndex < funders.length; funderIndex++){
address funder = funders[funderIndex];
addressToAmountFunded[funder] = 0;
}
//reset funders array
funders = new address[];
}
| function withdraw() payable onlyOwner public {
msg.sender.transfer(address(this).balance);
//reset funders' balance to 0
for(uint256 funderIndex = 0; funderIndex < funders.length; funderIndex++){
address funder = funders[funderIndex];
addressToAmountFunded[funder] = 0;
}
//reset funders array
funders = new address[];
}
| 33,194 |
230 | // since pool balance isn't calculated on individual contributions we must mint the early adopters rewards as we might come short otherwise. | sushi.mint(msg.sender, pending.mul(
| sushi.mint(msg.sender, pending.mul(
| 35,921 |
7 | // Checks if a given hash of miner,requestId has been disputed _hash is the sha256(abi.encodePacked(_miners[2],_requestId,_timestamp));return uint disputeId / | function getDisputeIdByDisputeHash(bytes32 _hash)
external
view
returns (uint256)
| function getDisputeIdByDisputeHash(bytes32 _hash)
external
view
returns (uint256)
| 51,772 |
40 | // Claims tokens from validator share and sends them to the/ user if his request is in the userToWithdrawRequest/_tokenId - Id of the token that wants to be claimed | function claimTokens(uint256 _tokenId) external override whenNotPaused {
_require(
poLidoNFT.isApprovedOrOwner(msg.sender, _tokenId),
"Not owner"
);
if (token2WithdrawRequest[_tokenId].requestEpoch != 0) {
_claimTokensV1(_tokenId);
} else if (token2WithdrawRequests[_tokenId].length != 0) {
_claimTokensV2(_tokenId);
} else {
revert("Invalid claim token");
}
}
| function claimTokens(uint256 _tokenId) external override whenNotPaused {
_require(
poLidoNFT.isApprovedOrOwner(msg.sender, _tokenId),
"Not owner"
);
if (token2WithdrawRequest[_tokenId].requestEpoch != 0) {
_claimTokensV1(_tokenId);
} else if (token2WithdrawRequests[_tokenId].length != 0) {
_claimTokensV2(_tokenId);
} else {
revert("Invalid claim token");
}
}
| 31,874 |
137 | // Calculate the saltHash given the salt/_salt Salt of the newly created address | function getSaltHash(uint256 _salt) public view returns (bytes32) {
return keccak256(abi.encodePacked(_salt, tx.origin));
}
| function getSaltHash(uint256 _salt) public view returns (bytes32) {
return keccak256(abi.encodePacked(_salt, tx.origin));
}
| 1,113 |
19 | // Remove reserve address whose balance shall no longer be included in the reserve ratio. reserveAddress The reserve address to remove. index The index of the reserve address in otherReserveAddresses.return Returns true if the transaction succeeds. / | function removeOtherReserveAddress(address reserveAddress, uint256 index)
external
onlyOwner
returns (bool)
| function removeOtherReserveAddress(address reserveAddress, uint256 index)
external
onlyOwner
returns (bool)
| 23,099 |
5 | // Min time between accrued reward withdrawals (set to 0 to disallow interim withdrawals) | uint16 rewardLockHours;
| uint16 rewardLockHours;
| 8,099 |
81 | // Split margin-split income between miner and wallet | splitPayFee(
token,
uint(batch[i + 3]),
owner,
minerFeeRecipient,
address(batch[i + 6]),
walletSplitPercentage
);
| splitPayFee(
token,
uint(batch[i + 3]),
owner,
minerFeeRecipient,
address(batch[i + 6]),
walletSplitPercentage
);
| 27,159 |
180 | // Returns x + y, reverts if sum overflows uint256/x The augend/y The addend/ return z The sum of x and y | function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
| function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
| 10,692 |
8 | // Disallows _address The address to change authorization. / | function deauthorize(address _address) public onlyOwner {
require(authorized[_address]);
emit AuthorizationSet(_address, false);
authorized[_address] = false;
}
| function deauthorize(address _address) public onlyOwner {
require(authorized[_address]);
emit AuthorizationSet(_address, false);
authorized[_address] = false;
}
| 24,457 |
99 | // Set Admin //Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.newPendingAdmin New pending admin./ | function _setPendingAdmin(address newPendingAdmin) external;
| function _setPendingAdmin(address newPendingAdmin) external;
| 47,568 |
0 | // using SafeERC20 for covering USDT no-return and other transfer issues | using SafeERC20 for IERC20Metadata;
| using SafeERC20 for IERC20Metadata;
| 12,657 |
381 | // returns the revision number (< type(uint256).max - 1) of the contract.The number should be defined as a private constant. //Returns true if and only if the function is running in the constructor | function isConstructor() private view returns (bool) {
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly {
cs := extcodesize(address())
}
return cs == 0;
}
| function isConstructor() private view returns (bool) {
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly {
cs := extcodesize(address())
}
return cs == 0;
}
| 19,647 |
60 | // Current Round | Round storage round = rounds[currentRoundId];
| Round storage round = rounds[currentRoundId];
| 67,606 |
573 | // Functions | constructor(address payable manager, address tokenAddress) public {
fundManager = manager;
fundCreatedAt = now;
isOpenForFunds = true;
adrianoToken = AdrianoERC20(tokenAddress);
}
| constructor(address payable manager, address tokenAddress) public {
fundManager = manager;
fundCreatedAt = now;
isOpenForFunds = true;
adrianoToken = AdrianoERC20(tokenAddress);
}
| 19,278 |
12 | // if OpenSea's ERC1155 Proxy Address is detected, auto-return true | if (_operator == address(0x207Fa8Df3a17D96Ca7EA4f2893fcdCb78a304101)) {
return true;
}
| if (_operator == address(0x207Fa8Df3a17D96Ca7EA4f2893fcdCb78a304101)) {
return true;
}
| 22,666 |
4 | // Switch from the core implementation to the fallback implemenation | function emergencyUpgrade() external onlyDelegate {
_upgradeCore(fallbackImplementation);
emit EmergencyUpgrade();
}
| function emergencyUpgrade() external onlyDelegate {
_upgradeCore(fallbackImplementation);
emit EmergencyUpgrade();
}
| 2,294 |
59 | // An administrator who can set the pending anchor value for assets. Set in the constructor. / | address public anchorAdmin;
| address public anchorAdmin;
| 10,406 |
66 | // Get the amounts to be redeemed. | (amountX, amountY) = _redeemWithdrawal(round, recipient);
| (amountX, amountY) = _redeemWithdrawal(round, recipient);
| 16,021 |
208 | // including the Metadata extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at `_startTokenId()`(defaults to 0, e.g. 0, 1, 2, 3..). Assumes that an owner cannot have more than 264 - 1 (max value of uint64) of supply. Assumes that the maximum token id cannot exceed 2256 - 1 (max value of uint256). / | contract ERC721A is IERC721A {
// Mask of an entry in packed address data.
uint256 private constant BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;
// The bit position of `numberMinted` in packed address data.
uint256 private constant BITPOS_NUMBER_MINTED = 64;
// The bit position of `numberBurned` in packed address data.
uint256 private constant BITPOS_NUMBER_BURNED = 128;
// The bit position of `aux` in packed address data.
uint256 private constant BITPOS_AUX = 192;
// Mask of all 256 bits in packed address data except the 64 bits for `aux`.
uint256 private constant BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
// The bit position of `startTimestamp` in packed ownership.
uint256 private constant BITPOS_START_TIMESTAMP = 160;
// The bit mask of the `burned` bit in packed ownership.
uint256 private constant BITMASK_BURNED = 1 << 224;
// The bit position of the `nextInitialized` bit in packed ownership.
uint256 private constant BITPOS_NEXT_INITIALIZED = 225;
// The bit mask of the `nextInitialized` bit in packed ownership.
uint256 private constant BITMASK_NEXT_INITIALIZED = 1 << 225;
// The bit position of `extraData` in packed ownership.
uint256 private constant BITPOS_EXTRA_DATA = 232;
// Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
uint256 private constant BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
// The mask of the lower 160 bits for addresses.
uint256 private constant BITMASK_ADDRESS = (1 << 160) - 1;
// The maximum `quantity` that can be minted with `_mintERC2309`.
// This limit is to prevent overflows on the address data entries.
// For a limit of 5000, a total of 3.689e15 calls to `_mintERC2309`
// is required to cause an overflow, which is unrealistic.
uint256 private constant MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
// The tokenId of the next token to be minted.
uint256 private _currentIndex;
// The number of tokens burned.
uint256 private _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned.
// See `_packedOwnershipOf` implementation for details.
//
// Bits Layout:
// - [0..159] `addr`
// - [160..223] `startTimestamp`
// - [224] `burned`
// - [225] `nextInitialized`
// - [232..255] `extraData`
mapping(uint256 => uint256) private _packedOwnerships;
// Mapping owner address to address data.
//
// Bits Layout:
// - [0..63] `balance`
// - [64..127] `numberMinted`
// - [128..191] `numberBurned`
// - [192..255] `aux`
mapping(address => uint256) private _packedAddressData;
// 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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* @dev Returns the starting token ID.
* To change the starting token ID, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev Returns the next token ID to be minted.
*/
function _nextTokenId() internal view returns (uint256) {
return _currentIndex;
}
/**
* @dev Returns the total number of tokens in existence.
* Burned tokens will reduce the count.
* To get the total number of tokens minted, please see `_totalMinted`.
*/
function totalSupply() public view override returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than `_currentIndex - _startTokenId()` times.
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* @dev Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to `_startTokenId()`
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev Returns the total number of tokens burned.
*/
function _totalBurned() internal view returns (uint256) {
return _burnCounter;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
// The interface IDs are constants representing the first 4 bytes of the XOR of
// all function selectors in the interface. See: https://eips.ethereum.org/EIPS/eip-165
// e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`
return
interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.
interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.
interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return _packedAddressData[owner] & BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return (_packedAddressData[owner] >> BITPOS_NUMBER_MINTED) & BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return (_packedAddressData[owner] >> BITPOS_NUMBER_BURNED) & BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return uint64(_packedAddressData[owner] >> BITPOS_AUX);
}
/**
* Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
uint256 packed = _packedAddressData[owner];
uint256 auxCasted;
// Cast `aux` with assembly to avoid redundant masking.
assembly {
auxCasted := aux
}
packed = (packed & BITMASK_AUX_COMPLEMENT) | (auxCasted << BITPOS_AUX);
_packedAddressData[owner] = packed;
}
/**
* Returns the packed ownership data of `tokenId`.
*/
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr)
if (curr < _currentIndex) {
uint256 packed = _packedOwnerships[curr];
// If not burned.
if (packed & BITMASK_BURNED == 0) {
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
//
// We can directly compare the packed value.
// If the address is zero, packed is zero.
while (packed == 0) {
packed = _packedOwnerships[--curr];
}
return packed;
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* Returns the unpacked `TokenOwnership` struct from `packed`.
*/
function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
ownership.addr = address(uint160(packed));
ownership.startTimestamp = uint64(packed >> BITPOS_START_TIMESTAMP);
ownership.burned = packed & BITMASK_BURNED != 0;
ownership.extraData = uint24(packed >> BITPOS_EXTRA_DATA);
}
/**
* Returns the unpacked `TokenOwnership` struct at `index`.
*/
function _ownershipAt(uint256 index) internal view returns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnerships[index]);
}
/**
* @dev Initializes the ownership slot minted at `index` for efficiency purposes.
*/
function _initializeOwnershipAt(uint256 index) internal {
if (_packedOwnerships[index] == 0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnershipOf(tokenId));
}
/**
* @dev Packs ownership data into a single uint256.
*/
function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
assembly {
// Mask `owner` to the lower 160 bits, in case the upper bits somehow aren"t clean.
owner := and(owner, BITMASK_ADDRESS)
// `owner | (block.timestamp << BITPOS_START_TIMESTAMP) | flags`.
result := or(owner, or(shl(BITPOS_START_TIMESTAMP, timestamp()), flags))
}
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return address(uint160(_packedOwnershipOf(tokenId)));
}
/**
* @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) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : "";
}
/**
* @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, it can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
*/
function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
// For branchless setting of the `nextInitialized` flag.
assembly {
// `(quantity == 1) << BITPOS_NEXT_INITIALIZED`.
result := shl(BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
}
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ownerOf(tokenId);
if (_msgSenderERC721A() != owner)
if (!isApprovedForAll(owner, _msgSenderERC721A())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
if (operator == _msgSenderERC721A()) revert ApproveToCaller();
_operatorApprovals[_msgSenderERC721A()][operator] = approved;
emit ApprovalForAll(_msgSenderERC721A(), 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-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 {
transferFrom(from, to, tokenId);
if (to.code.length != 0)
if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return
_startTokenId() <= tokenId &&
tokenId < _currentIndex && // If within bounds,
_packedOwnerships[tokenId] & BITMASK_BURNED == 0; // and not burned.
}
/**
* @dev Equivalent to `_safeMint(to, quantity, "")`.
*/
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement
* {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* See {_mint}.
*
* Emits a {Transfer} event for each mint.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity);
unchecked {
if (to.code.length != 0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (index < end);
// Reentrancy protection.
if (_currentIndex != end) revert();
}
}
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event for each mint.
*/
function _mint(address to, uint256 quantity) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// `balance` and `numberMinted` have a maximum limit of 2**64.
// `tokenId` has a maximum limit of 2**256.
unchecked {
// Updates:
// - `balance += quantity`.
// - `numberMinted += quantity`.
//
// We can directly add to the `balance` and `numberMinted`.
_packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1);
// Updates:
// - `address` to the owner.
// - `startTimestamp` to the timestamp of minting.
// - `burned` to `false`.
// - `nextInitialized` to `quantity == 1`.
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
uint256 tokenId = startTokenId;
uint256 end = startTokenId + quantity;
do {
emit Transfer(address(0), to, tokenId++);
} while (tokenId < end);
_currentIndex = end;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* This function is intended for efficient minting only during contract creation.
*
* It emits only one {ConsecutiveTransfer} as defined in
* [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
* instead of a sequence of {Transfer} event(s).
*
* Calling this function outside of contract creation WILL make your contract
* non-compliant with the ERC721 standard.
* For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
* {ConsecutiveTransfer} event is only permissible during contract creation.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {ConsecutiveTransfer} event.
*/
function _mintERC2309(address to, uint256 quantity) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
if (quantity > MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are unrealistic due to the above check for `quantity` to be below the limit.
unchecked {
// Updates:
// - `balance += quantity`.
// - `numberMinted += quantity`.
//
// We can directly add to the `balance` and `numberMinted`.
_packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1);
// Updates:
// - `address` to the owner.
// - `startTimestamp` to the timestamp of minting.
// - `burned` to `false`.
// - `nextInitialized` to `quantity == 1`.
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
_currentIndex = startTokenId + quantity;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Returns the storage slot and value for the approved address of `tokenId`.
*/
function _getApprovedAddress(uint256 tokenId)
private
view
returns (uint256 approvedAddressSlot, address approvedAddress)
{
mapping(uint256 => address) storage tokenApprovalsPtr = _tokenApprovals;
// The following is equivalent to `approvedAddress = _tokenApprovals[tokenId]`.
assembly {
// Compute the slot.
mstore(0x00, tokenId)
mstore(0x20, tokenApprovalsPtr.slot)
approvedAddressSlot := keccak256(0x00, 0x40)
// Load the slot"s value from storage.
approvedAddress := sload(approvedAddressSlot)
}
}
/**
* @dev Returns whether the `approvedAddress` is equals to `from` or `msgSender`.
*/
function _isOwnerOrApproved(
address approvedAddress,
address from,
address msgSender
) private pure returns (bool result) {
assembly {
// Mask `from` to the lower 160 bits, in case the upper bits somehow aren"t clean.
from := and(from, BITMASK_ADDRESS)
// Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren"t clean.
msgSender := and(msgSender, BITMASK_ADDRESS)
// `msgSender == from || msgSender == approvedAddress`.
result := or(eq(msgSender, from), eq(msgSender, approvedAddress))
}
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
// The nested ifs save around 20+ gas over a compound boolean condition.
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner.
assembly {
if approvedAddress {
// This is equivalent to `delete _tokenApprovals[tokenId]`.
sstore(approvedAddressSlot, 0)
}
}
// Underflow of the sender"s balance is impossible because we check for
// ownership above and the recipient"s balance can"t realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
// We can directly increment and decrement the balances.
--_packedAddressData[from]; // Updates: `balance -= 1`.
++_packedAddressData[to]; // Updates: `balance += 1`.
// Updates:
// - `address` to the next owner.
// - `startTimestamp` to the timestamp of transfering.
// - `burned` to `false`.
// - `nextInitialized` to `true`.
_packedOwnerships[tokenId] = _packOwnershipData(
to,
BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
// If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
// If the next slot"s address is zero and not burned (i.e. packed value is zero).
if (_packedOwnerships[nextTokenId] == 0) {
// If the next slot is within bounds.
if (nextTokenId != _currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Equivalent to `_burn(tokenId, false)`.
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (approvalCheck) {
// The nested ifs save around 20+ gas over a compound boolean condition.
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner.
assembly {
if approvedAddress {
// This is equivalent to `delete _tokenApprovals[tokenId]`.
sstore(approvedAddressSlot, 0)
}
}
// Underflow of the sender"s balance is impossible because we check for
// ownership above and the recipient"s balance can"t realistically overflow.
// Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
unchecked {
// Updates:
// - `balance -= 1`.
// - `numberBurned += 1`.
//
// We can directly decrement the balance, and increment the number burned.
// This is equivalent to `packed -= 1; packed += 1 << BITPOS_NUMBER_BURNED;`.
_packedAddressData[from] += (1 << BITPOS_NUMBER_BURNED) - 1;
// Updates:
// - `address` to the last owner.
// - `startTimestamp` to the timestamp of burning.
// - `burned` to `true`.
// - `nextInitialized` to `true`.
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(BITMASK_BURNED | BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
// If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
// If the next slot"s address is zero and not burned (i.e. packed value is zero).
if (_packedOwnerships[nextTokenId] == 0) {
// If the next slot is within bounds.
if (nextTokenId != _currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Directly sets the extra data for the ownership data `index`.
*/
function _setExtraDataAt(uint256 index, uint24 extraData) internal {
uint256 packed = _packedOwnerships[index];
if (packed == 0) revert OwnershipNotInitializedForExtraData();
uint256 extraDataCasted;
// Cast `extraData` with assembly to avoid redundant masking.
assembly {
extraDataCasted := extraData
}
packed = (packed & BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << BITPOS_EXTRA_DATA);
_packedOwnerships[index] = packed;
}
/**
* @dev Returns the next extra data for the packed ownership data.
* The returned result is shifted into position.
*/
function _nextExtraData(
address from,
address to,
uint256 prevOwnershipPacked
) private view returns (uint256) {
uint24 extraData = uint24(prevOwnershipPacked >> BITPOS_EXTRA_DATA);
return uint256(_extraData(from, to, extraData)) << BITPOS_EXTRA_DATA;
}
/**
* @dev Called during each token transfer to set the 24bit `extraData` field.
* Intended to be overridden by the cosumer contract.
*
* `previousExtraData` - the value of `extraData` before transfer.
*
* 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, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _extraData(
address from,
address to,
uint24 previousExtraData
) internal view virtual returns (uint24) {}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred.
* This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* 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, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred.
* This includes minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`"s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Returns the message sender (defaults to `msg.sender`).
*
* If you are writing GSN compatible contracts, you need to override this function.
*/
function _msgSenderERC721A() internal view virtual returns (address) {
return msg.sender;
}
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function _toString(uint256 value) internal pure returns (string memory ptr) {
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit),
// but we allocate 128 bytes to keep the free memory pointer 32-byte word aliged.
// We will need 1 32-byte word to store the length,
// and 3 32-byte words to store a maximum of 78 digits. Total: 32 + 3 * 32 = 128.
ptr := add(mload(0x40), 128)
// Update the free memory pointer to allocate.
mstore(0x40, ptr)
// Cache the end of the memory to calculate the length later.
let end := ptr
// We write the string from the rightmost digit to the leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
// Costs a bit more than early returning for the zero case,
// but cheaper in terms of deployment and overall runtime costs.
for {
// Initialize and perform the first pass without check.
let temp := value
// Move the pointer 1 byte leftwards to point to an empty character slot.
ptr := sub(ptr, 1)
// Write the character to the pointer. 48 is the ASCII index of "0".
mstore8(ptr, add(48, mod(temp, 10)))
temp := div(temp, 10)
} temp {
// Keep dividing `temp` until zero.
temp := div(temp, 10)
} {
// Body of the for loop.
ptr := sub(ptr, 1)
mstore8(ptr, add(48, mod(temp, 10)))
}
let length := sub(end, ptr)
// Move the pointer 32 bytes leftwards to make room for the length.
ptr := sub(ptr, 32)
// Store the length.
mstore(ptr, length)
}
}
}
| contract ERC721A is IERC721A {
// Mask of an entry in packed address data.
uint256 private constant BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;
// The bit position of `numberMinted` in packed address data.
uint256 private constant BITPOS_NUMBER_MINTED = 64;
// The bit position of `numberBurned` in packed address data.
uint256 private constant BITPOS_NUMBER_BURNED = 128;
// The bit position of `aux` in packed address data.
uint256 private constant BITPOS_AUX = 192;
// Mask of all 256 bits in packed address data except the 64 bits for `aux`.
uint256 private constant BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
// The bit position of `startTimestamp` in packed ownership.
uint256 private constant BITPOS_START_TIMESTAMP = 160;
// The bit mask of the `burned` bit in packed ownership.
uint256 private constant BITMASK_BURNED = 1 << 224;
// The bit position of the `nextInitialized` bit in packed ownership.
uint256 private constant BITPOS_NEXT_INITIALIZED = 225;
// The bit mask of the `nextInitialized` bit in packed ownership.
uint256 private constant BITMASK_NEXT_INITIALIZED = 1 << 225;
// The bit position of `extraData` in packed ownership.
uint256 private constant BITPOS_EXTRA_DATA = 232;
// Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
uint256 private constant BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
// The mask of the lower 160 bits for addresses.
uint256 private constant BITMASK_ADDRESS = (1 << 160) - 1;
// The maximum `quantity` that can be minted with `_mintERC2309`.
// This limit is to prevent overflows on the address data entries.
// For a limit of 5000, a total of 3.689e15 calls to `_mintERC2309`
// is required to cause an overflow, which is unrealistic.
uint256 private constant MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
// The tokenId of the next token to be minted.
uint256 private _currentIndex;
// The number of tokens burned.
uint256 private _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned.
// See `_packedOwnershipOf` implementation for details.
//
// Bits Layout:
// - [0..159] `addr`
// - [160..223] `startTimestamp`
// - [224] `burned`
// - [225] `nextInitialized`
// - [232..255] `extraData`
mapping(uint256 => uint256) private _packedOwnerships;
// Mapping owner address to address data.
//
// Bits Layout:
// - [0..63] `balance`
// - [64..127] `numberMinted`
// - [128..191] `numberBurned`
// - [192..255] `aux`
mapping(address => uint256) private _packedAddressData;
// 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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* @dev Returns the starting token ID.
* To change the starting token ID, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev Returns the next token ID to be minted.
*/
function _nextTokenId() internal view returns (uint256) {
return _currentIndex;
}
/**
* @dev Returns the total number of tokens in existence.
* Burned tokens will reduce the count.
* To get the total number of tokens minted, please see `_totalMinted`.
*/
function totalSupply() public view override returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than `_currentIndex - _startTokenId()` times.
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* @dev Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to `_startTokenId()`
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev Returns the total number of tokens burned.
*/
function _totalBurned() internal view returns (uint256) {
return _burnCounter;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
// The interface IDs are constants representing the first 4 bytes of the XOR of
// all function selectors in the interface. See: https://eips.ethereum.org/EIPS/eip-165
// e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`
return
interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.
interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.
interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return _packedAddressData[owner] & BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return (_packedAddressData[owner] >> BITPOS_NUMBER_MINTED) & BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return (_packedAddressData[owner] >> BITPOS_NUMBER_BURNED) & BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return uint64(_packedAddressData[owner] >> BITPOS_AUX);
}
/**
* Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
uint256 packed = _packedAddressData[owner];
uint256 auxCasted;
// Cast `aux` with assembly to avoid redundant masking.
assembly {
auxCasted := aux
}
packed = (packed & BITMASK_AUX_COMPLEMENT) | (auxCasted << BITPOS_AUX);
_packedAddressData[owner] = packed;
}
/**
* Returns the packed ownership data of `tokenId`.
*/
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr)
if (curr < _currentIndex) {
uint256 packed = _packedOwnerships[curr];
// If not burned.
if (packed & BITMASK_BURNED == 0) {
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
//
// We can directly compare the packed value.
// If the address is zero, packed is zero.
while (packed == 0) {
packed = _packedOwnerships[--curr];
}
return packed;
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* Returns the unpacked `TokenOwnership` struct from `packed`.
*/
function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
ownership.addr = address(uint160(packed));
ownership.startTimestamp = uint64(packed >> BITPOS_START_TIMESTAMP);
ownership.burned = packed & BITMASK_BURNED != 0;
ownership.extraData = uint24(packed >> BITPOS_EXTRA_DATA);
}
/**
* Returns the unpacked `TokenOwnership` struct at `index`.
*/
function _ownershipAt(uint256 index) internal view returns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnerships[index]);
}
/**
* @dev Initializes the ownership slot minted at `index` for efficiency purposes.
*/
function _initializeOwnershipAt(uint256 index) internal {
if (_packedOwnerships[index] == 0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnershipOf(tokenId));
}
/**
* @dev Packs ownership data into a single uint256.
*/
function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
assembly {
// Mask `owner` to the lower 160 bits, in case the upper bits somehow aren"t clean.
owner := and(owner, BITMASK_ADDRESS)
// `owner | (block.timestamp << BITPOS_START_TIMESTAMP) | flags`.
result := or(owner, or(shl(BITPOS_START_TIMESTAMP, timestamp()), flags))
}
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return address(uint160(_packedOwnershipOf(tokenId)));
}
/**
* @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) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : "";
}
/**
* @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, it can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
*/
function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
// For branchless setting of the `nextInitialized` flag.
assembly {
// `(quantity == 1) << BITPOS_NEXT_INITIALIZED`.
result := shl(BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
}
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ownerOf(tokenId);
if (_msgSenderERC721A() != owner)
if (!isApprovedForAll(owner, _msgSenderERC721A())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
if (operator == _msgSenderERC721A()) revert ApproveToCaller();
_operatorApprovals[_msgSenderERC721A()][operator] = approved;
emit ApprovalForAll(_msgSenderERC721A(), 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-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 {
transferFrom(from, to, tokenId);
if (to.code.length != 0)
if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return
_startTokenId() <= tokenId &&
tokenId < _currentIndex && // If within bounds,
_packedOwnerships[tokenId] & BITMASK_BURNED == 0; // and not burned.
}
/**
* @dev Equivalent to `_safeMint(to, quantity, "")`.
*/
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement
* {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* See {_mint}.
*
* Emits a {Transfer} event for each mint.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity);
unchecked {
if (to.code.length != 0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (index < end);
// Reentrancy protection.
if (_currentIndex != end) revert();
}
}
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event for each mint.
*/
function _mint(address to, uint256 quantity) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// `balance` and `numberMinted` have a maximum limit of 2**64.
// `tokenId` has a maximum limit of 2**256.
unchecked {
// Updates:
// - `balance += quantity`.
// - `numberMinted += quantity`.
//
// We can directly add to the `balance` and `numberMinted`.
_packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1);
// Updates:
// - `address` to the owner.
// - `startTimestamp` to the timestamp of minting.
// - `burned` to `false`.
// - `nextInitialized` to `quantity == 1`.
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
uint256 tokenId = startTokenId;
uint256 end = startTokenId + quantity;
do {
emit Transfer(address(0), to, tokenId++);
} while (tokenId < end);
_currentIndex = end;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* This function is intended for efficient minting only during contract creation.
*
* It emits only one {ConsecutiveTransfer} as defined in
* [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
* instead of a sequence of {Transfer} event(s).
*
* Calling this function outside of contract creation WILL make your contract
* non-compliant with the ERC721 standard.
* For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
* {ConsecutiveTransfer} event is only permissible during contract creation.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {ConsecutiveTransfer} event.
*/
function _mintERC2309(address to, uint256 quantity) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
if (quantity > MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are unrealistic due to the above check for `quantity` to be below the limit.
unchecked {
// Updates:
// - `balance += quantity`.
// - `numberMinted += quantity`.
//
// We can directly add to the `balance` and `numberMinted`.
_packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1);
// Updates:
// - `address` to the owner.
// - `startTimestamp` to the timestamp of minting.
// - `burned` to `false`.
// - `nextInitialized` to `quantity == 1`.
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
_currentIndex = startTokenId + quantity;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Returns the storage slot and value for the approved address of `tokenId`.
*/
function _getApprovedAddress(uint256 tokenId)
private
view
returns (uint256 approvedAddressSlot, address approvedAddress)
{
mapping(uint256 => address) storage tokenApprovalsPtr = _tokenApprovals;
// The following is equivalent to `approvedAddress = _tokenApprovals[tokenId]`.
assembly {
// Compute the slot.
mstore(0x00, tokenId)
mstore(0x20, tokenApprovalsPtr.slot)
approvedAddressSlot := keccak256(0x00, 0x40)
// Load the slot"s value from storage.
approvedAddress := sload(approvedAddressSlot)
}
}
/**
* @dev Returns whether the `approvedAddress` is equals to `from` or `msgSender`.
*/
function _isOwnerOrApproved(
address approvedAddress,
address from,
address msgSender
) private pure returns (bool result) {
assembly {
// Mask `from` to the lower 160 bits, in case the upper bits somehow aren"t clean.
from := and(from, BITMASK_ADDRESS)
// Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren"t clean.
msgSender := and(msgSender, BITMASK_ADDRESS)
// `msgSender == from || msgSender == approvedAddress`.
result := or(eq(msgSender, from), eq(msgSender, approvedAddress))
}
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
// The nested ifs save around 20+ gas over a compound boolean condition.
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner.
assembly {
if approvedAddress {
// This is equivalent to `delete _tokenApprovals[tokenId]`.
sstore(approvedAddressSlot, 0)
}
}
// Underflow of the sender"s balance is impossible because we check for
// ownership above and the recipient"s balance can"t realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
// We can directly increment and decrement the balances.
--_packedAddressData[from]; // Updates: `balance -= 1`.
++_packedAddressData[to]; // Updates: `balance += 1`.
// Updates:
// - `address` to the next owner.
// - `startTimestamp` to the timestamp of transfering.
// - `burned` to `false`.
// - `nextInitialized` to `true`.
_packedOwnerships[tokenId] = _packOwnershipData(
to,
BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
// If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
// If the next slot"s address is zero and not burned (i.e. packed value is zero).
if (_packedOwnerships[nextTokenId] == 0) {
// If the next slot is within bounds.
if (nextTokenId != _currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Equivalent to `_burn(tokenId, false)`.
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedAddress(tokenId);
if (approvalCheck) {
// The nested ifs save around 20+ gas over a compound boolean condition.
if (!_isOwnerOrApproved(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner.
assembly {
if approvedAddress {
// This is equivalent to `delete _tokenApprovals[tokenId]`.
sstore(approvedAddressSlot, 0)
}
}
// Underflow of the sender"s balance is impossible because we check for
// ownership above and the recipient"s balance can"t realistically overflow.
// Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
unchecked {
// Updates:
// - `balance -= 1`.
// - `numberBurned += 1`.
//
// We can directly decrement the balance, and increment the number burned.
// This is equivalent to `packed -= 1; packed += 1 << BITPOS_NUMBER_BURNED;`.
_packedAddressData[from] += (1 << BITPOS_NUMBER_BURNED) - 1;
// Updates:
// - `address` to the last owner.
// - `startTimestamp` to the timestamp of burning.
// - `burned` to `true`.
// - `nextInitialized` to `true`.
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(BITMASK_BURNED | BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
// If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
if (prevOwnershipPacked & BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
// If the next slot"s address is zero and not burned (i.e. packed value is zero).
if (_packedOwnerships[nextTokenId] == 0) {
// If the next slot is within bounds.
if (nextTokenId != _currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Directly sets the extra data for the ownership data `index`.
*/
function _setExtraDataAt(uint256 index, uint24 extraData) internal {
uint256 packed = _packedOwnerships[index];
if (packed == 0) revert OwnershipNotInitializedForExtraData();
uint256 extraDataCasted;
// Cast `extraData` with assembly to avoid redundant masking.
assembly {
extraDataCasted := extraData
}
packed = (packed & BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << BITPOS_EXTRA_DATA);
_packedOwnerships[index] = packed;
}
/**
* @dev Returns the next extra data for the packed ownership data.
* The returned result is shifted into position.
*/
function _nextExtraData(
address from,
address to,
uint256 prevOwnershipPacked
) private view returns (uint256) {
uint24 extraData = uint24(prevOwnershipPacked >> BITPOS_EXTRA_DATA);
return uint256(_extraData(from, to, extraData)) << BITPOS_EXTRA_DATA;
}
/**
* @dev Called during each token transfer to set the 24bit `extraData` field.
* Intended to be overridden by the cosumer contract.
*
* `previousExtraData` - the value of `extraData` before transfer.
*
* 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, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _extraData(
address from,
address to,
uint24 previousExtraData
) internal view virtual returns (uint24) {}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred.
* This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* 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, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred.
* This includes minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`"s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Returns the message sender (defaults to `msg.sender`).
*
* If you are writing GSN compatible contracts, you need to override this function.
*/
function _msgSenderERC721A() internal view virtual returns (address) {
return msg.sender;
}
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function _toString(uint256 value) internal pure returns (string memory ptr) {
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit),
// but we allocate 128 bytes to keep the free memory pointer 32-byte word aliged.
// We will need 1 32-byte word to store the length,
// and 3 32-byte words to store a maximum of 78 digits. Total: 32 + 3 * 32 = 128.
ptr := add(mload(0x40), 128)
// Update the free memory pointer to allocate.
mstore(0x40, ptr)
// Cache the end of the memory to calculate the length later.
let end := ptr
// We write the string from the rightmost digit to the leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
// Costs a bit more than early returning for the zero case,
// but cheaper in terms of deployment and overall runtime costs.
for {
// Initialize and perform the first pass without check.
let temp := value
// Move the pointer 1 byte leftwards to point to an empty character slot.
ptr := sub(ptr, 1)
// Write the character to the pointer. 48 is the ASCII index of "0".
mstore8(ptr, add(48, mod(temp, 10)))
temp := div(temp, 10)
} temp {
// Keep dividing `temp` until zero.
temp := div(temp, 10)
} {
// Body of the for loop.
ptr := sub(ptr, 1)
mstore8(ptr, add(48, mod(temp, 10)))
}
let length := sub(end, ptr)
// Move the pointer 32 bytes leftwards to make room for the length.
ptr := sub(ptr, 32)
// Store the length.
mstore(ptr, length)
}
}
}
| 1,750 |
2 | // Overrides existing Treasury contracttreasury_ Address of new Treasury contractMust implement ITreasury and cannot be same as existing/ | function setTreasury(ITreasury treasury_) public onlyOwner {
require(treasury != treasury_, "Same Treasury");
ITreasury _previousTreasury = treasury;
treasury = treasury_;
emit TreasuryChanged(_previousTreasury, treasury);
}
| function setTreasury(ITreasury treasury_) public onlyOwner {
require(treasury != treasury_, "Same Treasury");
ITreasury _previousTreasury = treasury;
treasury = treasury_;
emit TreasuryChanged(_previousTreasury, treasury);
}
| 14,338 |
185 | // Initialize the oracle array by writing the first slot. Called once for the lifecycle of the observations array/self The stored oracle array/time The time of the oracle initialization, via block.timestamp truncated to uint32/ return cardinality The number of populated elements in the oracle array/ return cardinalityNext The new length of the oracle array, independent of population | function initialize(Observation[65535] storage self, uint32 time)
internal
returns (uint16 cardinality, uint16 cardinalityNext)
| function initialize(Observation[65535] storage self, uint32 time)
internal
returns (uint16 cardinality, uint16 cardinalityNext)
| 2,487 |
5 | // End of show properties / | function setBalance(address payable account, uint256 newBalance) public onlyOwner {
_setBalance(account, newBalance);
}
| function setBalance(address payable account, uint256 newBalance) public onlyOwner {
_setBalance(account, newBalance);
}
| 19,338 |
157 | // Safe holyheld token transfer function, just in case if rounding error causes pool to not have enough HOLYs. | function safeTokenTransfer(address _to, uint256 _amount) internal {
uint256 balance = holytoken.balanceOf(address(this));
if (_amount > balance) {
holytoken.transfer(_to, balance);
} else {
holytoken.transfer(_to, _amount);
}
}
| function safeTokenTransfer(address _to, uint256 _amount) internal {
uint256 balance = holytoken.balanceOf(address(this));
if (_amount > balance) {
holytoken.transfer(_to, balance);
} else {
holytoken.transfer(_to, _amount);
}
}
| 29,879 |
61 | // Returns the integer division of two unsigned integers, reverting with custom message ondivision by zero. The result is rounded towards zero. CAUTION: This function is deprecated because it requires allocating memory for the error | * message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
| * message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
| 489 |
39 | // get all rewards that have not been claimed yet | function viewUnpaidVestRewards(address vester) public view returns (uint256)
| function viewUnpaidVestRewards(address vester) public view returns (uint256)
| 6,699 |
297 | // Initialize swapStorage struct | swapStorage.lpToken = lpToken;
swapStorage.pooledTokens = _pooledTokens;
swapStorage.tokenPrecisionMultipliers = precisionMultipliers;
swapStorage.balances = new uint256[](_pooledTokens.length);
swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION);
swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION);
| swapStorage.lpToken = lpToken;
swapStorage.pooledTokens = _pooledTokens;
swapStorage.tokenPrecisionMultipliers = precisionMultipliers;
swapStorage.balances = new uint256[](_pooledTokens.length);
swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION);
swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION);
| 64,702 |
1 | // deposit an ERC721 token from another contract into an ERC721 in this contract/_token the address of the NFT you are depositing/_tokenId the ID of the NFT you are depositing | function depositERC721(address _token, uint256 _tokenId) external {
require(_token != address(this), "can't deposit self");
IERC721(_token).safeTransferFrom(msg.sender, address(this), _tokenId);
emit Deposit(_token, _tokenId, msg.sender);
}
| function depositERC721(address _token, uint256 _tokenId) external {
require(_token != address(this), "can't deposit self");
IERC721(_token).safeTransferFrom(msg.sender, address(this), _tokenId);
emit Deposit(_token, _tokenId, msg.sender);
}
| 32,781 |
143 | // 更新一个属于自己的资源的内容和价格 _claimIdbytes16 : 资源的索引 _newUdfsstring: 新的udfs _newPrice uint256 : 新的价格returnbool: 操作成功返回 true / | function updateClaim(bytes16 _claimId, string _newUdfs, uint256 _newPrice) public returns(bool){
if(_hashFilter(_newUdfs) == false){
emit LogError(RScorr.InvalidUdfs);
return false;
}
return Center_.updateClaim(_claimId, msg.sender, _newUdfs, _newPrice);
}
| function updateClaim(bytes16 _claimId, string _newUdfs, uint256 _newPrice) public returns(bool){
if(_hashFilter(_newUdfs) == false){
emit LogError(RScorr.InvalidUdfs);
return false;
}
return Center_.updateClaim(_claimId, msg.sender, _newUdfs, _newPrice);
}
| 38,955 |
119 | // Update reward per block Only callable by owner. _rewardPerBlock: the reward per block / | function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
rewardPerBlock = _rewardPerBlock;
emit NewRewardPerBlock(_rewardPerBlock);
}
| function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
rewardPerBlock = _rewardPerBlock;
emit NewRewardPerBlock(_rewardPerBlock);
}
| 76,169 |
717 | // Domain of home chain | uint32 public remoteDomain;
| uint32 public remoteDomain;
| 22,583 |
31 | // get leader's follow fee | if (uints[13] == 0) return; // uints[13] = followFee
uint profit = SafeMath.subtract(value, self.followStartValue);
uint followFeeAmount = DecimalMath.fromFixed(SafeMath.multiply(uints[13], profit)); // uints[13] = followFee
| if (uints[13] == 0) return; // uints[13] = followFee
uint profit = SafeMath.subtract(value, self.followStartValue);
uint followFeeAmount = DecimalMath.fromFixed(SafeMath.multiply(uints[13], profit)); // uints[13] = followFee
| 42,903 |
17 | // ===================================== Address to send the charity! :)https:giveth.io/ https:etherscan.io/address/0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc | address constant public giveEthCharityAddress = 0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc;
uint256 public totalEthCharityRecieved; // total ETH charity recieved from this contract
uint256 public totalEthCharityCollected; // total ETH charity collected in this contract
| address constant public giveEthCharityAddress = 0x5ADF43DD006c6C36506e2b2DFA352E60002d22Dc;
uint256 public totalEthCharityRecieved; // total ETH charity recieved from this contract
uint256 public totalEthCharityCollected; // total ETH charity collected in this contract
| 16,228 |
49 | // Ensure assetData length is valid | require(
assetData.length > 3,
"LENGTH_GREATER_THAN_3_REQUIRED"
);
| require(
assetData.length > 3,
"LENGTH_GREATER_THAN_3_REQUIRED"
);
| 3,754 |
167 | // set the value of outtoken in the next round, the ratio to target token.since when the outtoken is generated, its amount is 1:1 bind to long_term token at first,the ratio of outtoken to target token should be set to "ratio_to".HTokenInterfaceGK(info.long_term.houttokenAtPeriodWithRatio(info._round + 1, ratio)).set_ratio_to_target(ratio_to); | info.aggr.setRatioTo(address(this), info._round + 1, ratio, 2, ratio_to);
| info.aggr.setRatioTo(address(this), info._round + 1, ratio, 2, ratio_to);
| 29,375 |
3 | // handler Array / | modifier onlyManager {
address msgSender = msg.sender;
require((msgSender == managerAddr) || (msgSender == owner), "onlyManager function");
_;
}
| modifier onlyManager {
address msgSender = msg.sender;
require((msgSender == managerAddr) || (msgSender == owner), "onlyManager function");
_;
}
| 53,305 |
143 | // Initializes the domain separator and parameter caches. The meaning of `name` and `version` is specified in - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.- `version`: the current major version of the signing domain. NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smartcontract upgrade]. / | constructor(string memory name, string memory version) {
| constructor(string memory name, string memory version) {
| 21,590 |
61 | // solhint-disable-next-line no-unused-vars | function _authorizeUpgrade(address) internal view override {
_onlyGovernance();
}
| function _authorizeUpgrade(address) internal view override {
_onlyGovernance();
}
| 69,588 |
8 | // Transfer functions / | function transfer(address _to, uint256 _value) public {
require(_to != address(this));
require(_to != address(0), "Cannot use zero address");
require(_value > 0, "Cannot use zero value");
require (balanceOf[msg.sender] >= _value, "Balance not enough"); // Check if the sender has enough
require (balanceOf[_to] + _value >= balanceOf[_to], "Overflow" ); // Check for overflows
uint previousBalances = balanceOf[msg.sender] + balanceOf[_to];
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
assert(balanceOf[msg.sender] + balanceOf[_to] == previousBalances);
}
| function transfer(address _to, uint256 _value) public {
require(_to != address(this));
require(_to != address(0), "Cannot use zero address");
require(_value > 0, "Cannot use zero value");
require (balanceOf[msg.sender] >= _value, "Balance not enough"); // Check if the sender has enough
require (balanceOf[_to] + _value >= balanceOf[_to], "Overflow" ); // Check for overflows
uint previousBalances = balanceOf[msg.sender] + balanceOf[_to];
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
assert(balanceOf[msg.sender] + balanceOf[_to] == previousBalances);
}
| 46,821 |
46 | // Require that the sender has the funds to buy the ticket | require(addressToAmountFunded[msg.sender] > ticketPrice, "RE-9");
| require(addressToAmountFunded[msg.sender] > ticketPrice, "RE-9");
| 45,911 |
11 | // the state is set | c.blockNumberN = blockNumberN;
| c.blockNumberN = blockNumberN;
| 42,896 |
1 | // Returns the smallest of two numbers. / | function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
| function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
| 46,286 |
81 | // Gets the total amount of tokens stored by the contract.return uint256 representing the total amount of tokens / | function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
| function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
| 8,877 |
15 | // Decreases the tracked value for totalLP/ Can only be called by an approved vault/amount_The amount of LP tokens to remove from the total | function decreaseTotalLp(uint256 amount_) external;
| function decreaseTotalLp(uint256 amount_) external;
| 24,875 |
22 | // EIP-1271 signer | address private signer;
| address private signer;
| 15,581 |
10 | // Check the merkle proof | require(node == merkleRoots[groupId], 'MerklePreSale: Invalid proof.' );
| require(node == merkleRoots[groupId], 'MerklePreSale: Invalid proof.' );
| 8,259 |
47 | // Safe Variety transfer function, just in case if rounding error causes pool do not have enough Variety. | function safeVarietyTransfer(address _to, uint256 _amount) internal {
if (Variety.balanceOf(address(this)) > totalVarietyInPools) {
//VarietyBal = total Variety in VarietyDistributor - total Variety in Variety pools, this will make sure that VarietyDistributor never transfer rewards from deposited Variety pools
uint256 VarietyBal = Variety.balanceOf(address(this)).sub(
totalVarietyInPools
);
if (_amount >= VarietyBal) {
Variety.transfer(_to, VarietyBal);
} else if (_amount > 0) {
Variety.transfer(_to, _amount);
}
}
}
| function safeVarietyTransfer(address _to, uint256 _amount) internal {
if (Variety.balanceOf(address(this)) > totalVarietyInPools) {
//VarietyBal = total Variety in VarietyDistributor - total Variety in Variety pools, this will make sure that VarietyDistributor never transfer rewards from deposited Variety pools
uint256 VarietyBal = Variety.balanceOf(address(this)).sub(
totalVarietyInPools
);
if (_amount >= VarietyBal) {
Variety.transfer(_to, VarietyBal);
} else if (_amount > 0) {
Variety.transfer(_to, _amount);
}
}
}
| 50,124 |
147 | // If there are multiple reward tokens, they should all be liquidated to rewardToken. | function _getReward() internal {
if (address(rewardPool) != address(0)) {
rewardPool.getReward();
}
}
| function _getReward() internal {
if (address(rewardPool) != address(0)) {
rewardPool.getReward();
}
}
| 33,762 |
65 | // Returns the legacy signer for the specified account and role. If no signer has been specified it will return the account itself. _account The address of the account. role The role of the signer. / | function getLegacySigner(address _account, bytes32 role) public view returns (address) {
require(isLegacyRole(role), "Role is not a legacy signer");
Account storage account = accounts[_account];
address signer;
if (role == ValidatorSigner) {
signer = account.signers.validator;
} else if (role == AttestationSigner) {
signer = account.signers.attestation;
} else if (role == VoteSigner) {
signer = account.signers.vote;
}
return signer == address(0) ? _account : signer;
}
| function getLegacySigner(address _account, bytes32 role) public view returns (address) {
require(isLegacyRole(role), "Role is not a legacy signer");
Account storage account = accounts[_account];
address signer;
if (role == ValidatorSigner) {
signer = account.signers.validator;
} else if (role == AttestationSigner) {
signer = account.signers.attestation;
} else if (role == VoteSigner) {
signer = account.signers.vote;
}
return signer == address(0) ? _account : signer;
}
| 20,139 |
268 | // Stops ramping A immediately. Once this function is called, rampA()cannot be called for another 24 hours self Swap struct to update / | function stopRampA(Swap storage self) external {
require(self.futureATime > block.timestamp, "Ramp is already stopped");
uint256 currentA = _getAPrecise(self);
self.initialA = currentA;
self.futureA = currentA;
self.initialATime = block.timestamp;
self.futureATime = block.timestamp;
emit StopRampA(currentA, block.timestamp);
}
| function stopRampA(Swap storage self) external {
require(self.futureATime > block.timestamp, "Ramp is already stopped");
uint256 currentA = _getAPrecise(self);
self.initialA = currentA;
self.futureA = currentA;
self.initialATime = block.timestamp;
self.futureATime = block.timestamp;
emit StopRampA(currentA, block.timestamp);
}
| 19,663 |
18 | // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` | bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
| bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
| 2,433 |
46 | // Divide [prod1 prod0] by the factors of two | assembly {
prod0 := div(prod0, twos)
}
| assembly {
prod0 := div(prod0, twos)
}
| 25,464 |
81 | // _softCap min wei amount needed to allow send it to investment address. / | constructor(uint _softCap) public {
softCap = _softCap;
}
| constructor(uint _softCap) public {
softCap = _softCap;
}
| 35,453 |
11 | // Returns a boolean array where each value corresponds to theinterfaces passed in and whether they're supported or not. This allowsyou to batch check interfaces for a contract where your expectationis that some interfaces may not be supported. | * See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)
internal
view
returns (bool[] memory)
{
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
| * See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)
internal
view
returns (bool[] memory)
{
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
| 21,043 |
2 | // forkKey Fork's key | function deposit(
mapping(bytes32 => Info) storage self,
bytes32 forkKey,
uint256 amount,
bool deny
| function deposit(
mapping(bytes32 => Info) storage self,
bytes32 forkKey,
uint256 amount,
bool deny
| 20,841 |
183 | // Integer division for negative numbers already uses ceiling, so only check boundary condition for positive numbers | if(netCost <= 0 || netCost / int(ONE) * int(ONE) == netCost) {
netCost /= int(ONE);
} else {
| if(netCost <= 0 || netCost / int(ONE) * int(ONE) == netCost) {
netCost /= int(ONE);
} else {
| 49,083 |
156 | // set withdrawed total | Withdrawed[sender] = Withdrawed[sender] + WithdrawAmount ;
| Withdrawed[sender] = Withdrawed[sender] + WithdrawAmount ;
| 16,477 |
124 | // Clear the current queue, and update the `nextL1ToForgeQueue` and `nextL1FillingQueue` if needed / | function _clearQueue() internal returns (uint16) {
uint16 l1UserTxsLen = uint16(
mapL1TxQueue[nextL1ToForgeQueue].length / _L1_USER_TOTALBYTES
);
delete mapL1TxQueue[nextL1ToForgeQueue];
nextL1ToForgeQueue++;
if (nextL1ToForgeQueue == nextL1FillingQueue) {
nextL1FillingQueue++;
}
return l1UserTxsLen;
}
| function _clearQueue() internal returns (uint16) {
uint16 l1UserTxsLen = uint16(
mapL1TxQueue[nextL1ToForgeQueue].length / _L1_USER_TOTALBYTES
);
delete mapL1TxQueue[nextL1ToForgeQueue];
nextL1ToForgeQueue++;
if (nextL1ToForgeQueue == nextL1FillingQueue) {
nextL1FillingQueue++;
}
return l1UserTxsLen;
}
| 61,058 |
98 | // Swap native ETH for CVX on Curve/amount - amount to swap/ return amount of CRV obtained after the swap | function _swapEthToCvx(uint256 amount) internal returns (uint256) {
return _ethToCvx(amount, 0);
}
| function _swapEthToCvx(uint256 amount) internal returns (uint256) {
return _ethToCvx(amount, 0);
}
| 21,502 |
7 | // URI variables ------------------------------------------------------------------------ | string private _contractURI;
string private _baseTokenURI;
| string private _contractURI;
string private _baseTokenURI;
| 77,919 |
131 | // Note: There are no time related requirements regarding limitEndTime. If it's below openingTime, token purchases will never be limited. If it's above closingTime, token purchases will always be limited. | if (_limitEndTime > _openingTime) {
| if (_limitEndTime > _openingTime) {
| 75,306 |
187 | // A map from an account owner to an approved transaction hash to if the transaction is approved or not | mapping (address => mapping (bytes32 => bool)) approvedTx;
| mapping (address => mapping (bytes32 => bool)) approvedTx;
| 19,645 |
8 | // The CarbonCreditTokens that form this bundle | EnumerableSetUpgradeable.AddressSet private _tokenAddresses;
| EnumerableSetUpgradeable.AddressSet private _tokenAddresses;
| 24,745 |
14 | // era to index+1 | mapping(bytes32 => uint256) internal eraIndex;
uint256 public mintPriceOffset = 0 szabo;
uint256 public mintStepPrice = 500 szabo;
uint256 public mintPriceBuffer = 5000 szabo;
| mapping(bytes32 => uint256) internal eraIndex;
uint256 public mintPriceOffset = 0 szabo;
uint256 public mintStepPrice = 500 szabo;
uint256 public mintPriceBuffer = 5000 szabo;
| 608 |
35 | // set tokenOwnerAddress as owner of all tokens | _mint(tokenOwnerAddress, totalSupply);
| _mint(tokenOwnerAddress, totalSupply);
| 27,158 |
1,005 | // Packs an uint value into a "floating point" storage slot. Used for storinglastClaimIntegralSupply values in balance storage. For these values, we don't needto maintain exact precision but we don't want to be limited by storage size overflows. A floating point value is defined by the 48 most significant bits and an 8 bit numberof bit shifts required to restore its precision. The unpacked value will always be lessthan the packed value with a maximum absolute loss of precision of (2bitShift) - 1. / | library FloatingPoint56 {
function packTo56Bits(uint256 value) internal pure returns (uint56) {
uint256 bitShift;
// If the value is over the uint48 max value then we will shift it down
// given the index of the most significant bit. We store this bit shift
// in the least significant byte of the 56 bit slot available.
if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47);
uint256 shiftedValue = value >> bitShift;
return uint56((shiftedValue << 8) | bitShift);
}
function unpackFrom56Bits(uint256 value) internal pure returns (uint256) {
// The least significant 8 bits will be the amount to bit shift
uint256 bitShift = uint256(uint8(value));
return ((value >> 8) << bitShift);
}
}
| library FloatingPoint56 {
function packTo56Bits(uint256 value) internal pure returns (uint56) {
uint256 bitShift;
// If the value is over the uint48 max value then we will shift it down
// given the index of the most significant bit. We store this bit shift
// in the least significant byte of the 56 bit slot available.
if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47);
uint256 shiftedValue = value >> bitShift;
return uint56((shiftedValue << 8) | bitShift);
}
function unpackFrom56Bits(uint256 value) internal pure returns (uint256) {
// The least significant 8 bits will be the amount to bit shift
uint256 bitShift = uint256(uint8(value));
return ((value >> 8) << bitShift);
}
}
| 16,343 |
261 | // Subtracts the user's staking amount in the Property. / | function subValue(
address _property,
address _sender,
uint256 _value
| function subValue(
address _property,
address _sender,
uint256 _value
| 2,756 |
4 | // send referral subscribers | claimedsubscribers[referrals[msg.sender]]=SafeMath.add(claimedsubscribers[referrals[msg.sender]],SafeMath.div(subscribersUsed,5));
| claimedsubscribers[referrals[msg.sender]]=SafeMath.add(claimedsubscribers[referrals[msg.sender]],SafeMath.div(subscribersUsed,5));
| 46,356 |
34 | // 来源于下级完成复投 当下级完成4个位置,自动复投的情况,将滑落到左/右谁少,给谁新增的位子,右边完成复投说明左边少 | if (users[referrerAddress].x6Matrix[level].firstLevelReferrals[1] == userAddress) {
updateX6(userAddress, referrerAddress, level, false);
return updateX6ReferrerSecondLevel(userAddress, referrerAddress, level);
} else if (users[referrerAddress].x6Matrix[level].firstLevelReferrals[0] == userAddress) {
| if (users[referrerAddress].x6Matrix[level].firstLevelReferrals[1] == userAddress) {
updateX6(userAddress, referrerAddress, level, false);
return updateX6ReferrerSecondLevel(userAddress, referrerAddress, level);
} else if (users[referrerAddress].x6Matrix[level].firstLevelReferrals[0] == userAddress) {
| 25,161 |
69 | // Private function to clear current approval of a given token IDReverts if the given address is not indeed the owner of the token owner owner of the token tokenId uint256 ID of the token to be transferred / | function _clearApproval(address owner, uint256 tokenId) private {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
| function _clearApproval(address owner, uint256 tokenId) private {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
| 52 |
142 | // force removes the lender even if it still has a balance | function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
| function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length - 1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
| 21,326 |
11 | // ======== MINTING ========/ presale mint / | function preSaleMint(uint256 _quantity, uint256 _maxAmount, bytes32[] calldata _proof) external payable callerIsUser {
require(isPreSaleActive, "PRESALE NOT ACTIVE");
require(msg.value == preSalePrice * _quantity, "NEED TO SEND CORRECT ETH AMOUNT");
require(totalSupply() + _quantity <= MAX_SUPPLY, "MAX SUPPLY REACHED" );
require(preSaleMinted[msg.sender] + _quantity <= _maxAmount, "EXCEEDS MAX CLAIM");
bytes32 sender = keccak256(abi.encodePacked(msg.sender, _maxAmount));
bool isValidProof = MerkleProof.verify(_proof, preSaleMerkleRoot, sender);
require(isValidProof, "INVALID PROOF");
preSaleMinted[msg.sender] += _quantity;
_safeMint(msg.sender, _quantity);
}
| function preSaleMint(uint256 _quantity, uint256 _maxAmount, bytes32[] calldata _proof) external payable callerIsUser {
require(isPreSaleActive, "PRESALE NOT ACTIVE");
require(msg.value == preSalePrice * _quantity, "NEED TO SEND CORRECT ETH AMOUNT");
require(totalSupply() + _quantity <= MAX_SUPPLY, "MAX SUPPLY REACHED" );
require(preSaleMinted[msg.sender] + _quantity <= _maxAmount, "EXCEEDS MAX CLAIM");
bytes32 sender = keccak256(abi.encodePacked(msg.sender, _maxAmount));
bool isValidProof = MerkleProof.verify(_proof, preSaleMerkleRoot, sender);
require(isValidProof, "INVALID PROOF");
preSaleMinted[msg.sender] += _quantity;
_safeMint(msg.sender, _quantity);
}
| 49,165 |
59 | // approve spender when not paused / | function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
| function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
| 44,849 |
28 | // Increases approved amount of tokens for spender. Returns success. | function increaseApproval(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = add(allowed[msg.sender][_spender], _value);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| function increaseApproval(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = add(allowed[msg.sender][_spender], _value);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| 44,645 |
15 | // Emitted when XVS is distributed to a supplier | event DistributedSupplierVenus(VToken indexed vToken, address indexed supplier, uint venusDelta, uint venusSupplyIndex);
| event DistributedSupplierVenus(VToken indexed vToken, address indexed supplier, uint venusDelta, uint venusSupplyIndex);
| 24,404 |
9 | // sale | address public immutable saleAddress;
uint256 private immutable _saleSupply;
| address public immutable saleAddress;
uint256 private immutable _saleSupply;
| 25,898 |
282 | // DocumentMajority: :proposal has achieved majority | event DocumentMajority(bytes32 proposal);
| event DocumentMajority(bytes32 proposal);
| 37,011 |
66 | // returns the ratio of inflation already minted | function inflationMintedRatio() external view returns (uint256);
| function inflationMintedRatio() external view returns (uint256);
| 64,538 |
8 | // Finally, set the price | items[_hash].price = _price;
| items[_hash].price = _price;
| 11,021 |
27 | // Changes the name for CosmoMask tokenId / | function changeName(uint256 tokenId, string memory newName) public {
address owner = ownerOf(tokenId);
require(_msgSender() == owner, "CosmoBugs: caller is not the token owner");
require(validateName(newName) == true, "CosmoBugs: not a valid new name");
require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "CosmoBugs: new name is same as the current one");
require(isNameReserved(newName) == false, "CosmoBugs: name already reserved");
IERC20BurnTransfer(nftPower).transferFrom(msg.sender, address(this), NAME_CHANGE_PRICE);
// If already named, dereserve old name
if (bytes(_tokenName[tokenId]).length > 0) {
toggleReserveName(_tokenName[tokenId], false);
}
toggleReserveName(newName, true);
_tokenName[tokenId] = newName;
IERC20BurnTransfer(nftPower).burn(NAME_CHANGE_PRICE);
emit NameChange(tokenId, newName);
}
| function changeName(uint256 tokenId, string memory newName) public {
address owner = ownerOf(tokenId);
require(_msgSender() == owner, "CosmoBugs: caller is not the token owner");
require(validateName(newName) == true, "CosmoBugs: not a valid new name");
require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "CosmoBugs: new name is same as the current one");
require(isNameReserved(newName) == false, "CosmoBugs: name already reserved");
IERC20BurnTransfer(nftPower).transferFrom(msg.sender, address(this), NAME_CHANGE_PRICE);
// If already named, dereserve old name
if (bytes(_tokenName[tokenId]).length > 0) {
toggleReserveName(_tokenName[tokenId], false);
}
toggleReserveName(newName, true);
_tokenName[tokenId] = newName;
IERC20BurnTransfer(nftPower).burn(NAME_CHANGE_PRICE);
emit NameChange(tokenId, newName);
}
| 64,103 |
13 | // Get the underlying price of a listed cToken asset cToken The cToken to get the underlying price ofreturn The underlying asset price mantissa (scaled by 1e18) / | function getUnderlyingPrice(CToken cToken) public view returns (uint) {
address cTokenAddress = address(cToken);
if (cTokenAddress == cyY3CRVAddress) {
uint yVaultPrice = YVaultInterface(yVaults[cyY3CRVAddress]).getPricePerFullShare();
uint virtualPrice = CurveSwapInterface(curveSwap[cyY3CRVAddress]).get_virtual_price();
return mul_(yVaultPrice, Exp({mantissa: virtualPrice}));
}
AggregatorV3Interface aggregator = aggregators[cTokenAddress];
if (address(aggregator) != address(0)) {
uint price = getPriceFromChainlink(aggregator);
uint underlyingDecimals = EIP20Interface(CErc20(cTokenAddress).underlying()).decimals();
return mul_(price, 10**(18 - underlyingDecimals));
}
// Raise error.
assert(false);
}
| function getUnderlyingPrice(CToken cToken) public view returns (uint) {
address cTokenAddress = address(cToken);
if (cTokenAddress == cyY3CRVAddress) {
uint yVaultPrice = YVaultInterface(yVaults[cyY3CRVAddress]).getPricePerFullShare();
uint virtualPrice = CurveSwapInterface(curveSwap[cyY3CRVAddress]).get_virtual_price();
return mul_(yVaultPrice, Exp({mantissa: virtualPrice}));
}
AggregatorV3Interface aggregator = aggregators[cTokenAddress];
if (address(aggregator) != address(0)) {
uint price = getPriceFromChainlink(aggregator);
uint underlyingDecimals = EIP20Interface(CErc20(cTokenAddress).underlying()).decimals();
return mul_(price, 10**(18 - underlyingDecimals));
}
// Raise error.
assert(false);
}
| 38,687 |
120 | // limit per tx per type Id | mapping(uint256 => uint256) public typeLimitPerTx;
| mapping(uint256 => uint256) public typeLimitPerTx;
| 14,117 |
203 | // this event is emitted whenever a Country has been whitelisted. the event is emitted by 'whitelistCountry' and 'batchWhitelistCountries' functions. `_country` is the numeric ISO 3166-1 of the whitelisted country. / | event WhitelistedCountry(uint16 _country);
| event WhitelistedCountry(uint16 _country);
| 14,164 |
8 | // add new module to wallet _wallet attach module to new module _module attach module / | function addModule(address _moduleRegistry, address _wallet, address _module, bytes calldata data) external virtual override onlyWallet(_wallet) onlyWhenUnlocked(_wallet) {
require(registry.isRegisteredModule(_module), "TM: module is not registered");
IWallet(_wallet).authoriseModule(_moduleRegistry, _module, true, data);
}
| function addModule(address _moduleRegistry, address _wallet, address _module, bytes calldata data) external virtual override onlyWallet(_wallet) onlyWhenUnlocked(_wallet) {
require(registry.isRegisteredModule(_module), "TM: module is not registered");
IWallet(_wallet).authoriseModule(_moduleRegistry, _module, true, data);
}
| 20,687 |
109 | // allows the withdrawal of the liquidity from a position or from the item tokens.positionId id of the position.objectId object id of the item token to burn.unwrapPair if the liquidity pool tokens will be unwrapped or not.removedLiquidity amount of liquidity to remove. / | function withdrawLiquidity(uint256 positionId, uint256 objectId, bool unwrapPair, uint256 removedLiquidity) public {
// retrieve liquidity mining position
LiquidityMiningPosition storage liquidityMiningPosition = _positions[positionId];
uint256 setupIndex = objectId != 0 ? getObjectIdSetupIndex(objectId) : liquidityMiningPosition.setupIndex;
require(positionId != 0 || (_setups[setupIndex].objectId == objectId || _finishedLockedSetups[objectId]), "Invalid position");
// current owned liquidity
require(
(
liquidityMiningPosition.free &&
removedLiquidity <= liquidityMiningPosition.liquidityPoolTokenAmount &&
!_positionRedeemed[positionId]
// && liquidityMiningPosition.liquidityPoolData.liquidityPoolAddress != address(0)
) || (positionId == 0 && INativeV1(_liquidityFarmTokenCollection).balanceOf(msg.sender, objectId) >= removedLiquidity), "Invalid withdraw");
// check if liquidity mining position is valid
require(liquidityMiningPosition.free || (_setups[setupIndex].endBlock <= block.number || _finishedLockedSetups[objectId]), "Invalid withdraw");
// burn the liquidity in the locked setup
if (positionId == 0) {
_burnLiquidity(objectId, removedLiquidity);
} else {
_positionRedeemed[positionId] = removedLiquidity == liquidityMiningPosition.liquidityPoolTokenAmount;
withdrawReward(positionId);
_setups[liquidityMiningPosition.setupIndex].totalSupply -= removedLiquidity;
}
_removeLiquidity(positionId, objectId, setupIndex, unwrapPair, removedLiquidity, false);
}
| function withdrawLiquidity(uint256 positionId, uint256 objectId, bool unwrapPair, uint256 removedLiquidity) public {
// retrieve liquidity mining position
LiquidityMiningPosition storage liquidityMiningPosition = _positions[positionId];
uint256 setupIndex = objectId != 0 ? getObjectIdSetupIndex(objectId) : liquidityMiningPosition.setupIndex;
require(positionId != 0 || (_setups[setupIndex].objectId == objectId || _finishedLockedSetups[objectId]), "Invalid position");
// current owned liquidity
require(
(
liquidityMiningPosition.free &&
removedLiquidity <= liquidityMiningPosition.liquidityPoolTokenAmount &&
!_positionRedeemed[positionId]
// && liquidityMiningPosition.liquidityPoolData.liquidityPoolAddress != address(0)
) || (positionId == 0 && INativeV1(_liquidityFarmTokenCollection).balanceOf(msg.sender, objectId) >= removedLiquidity), "Invalid withdraw");
// check if liquidity mining position is valid
require(liquidityMiningPosition.free || (_setups[setupIndex].endBlock <= block.number || _finishedLockedSetups[objectId]), "Invalid withdraw");
// burn the liquidity in the locked setup
if (positionId == 0) {
_burnLiquidity(objectId, removedLiquidity);
} else {
_positionRedeemed[positionId] = removedLiquidity == liquidityMiningPosition.liquidityPoolTokenAmount;
withdrawReward(positionId);
_setups[liquidityMiningPosition.setupIndex].totalSupply -= removedLiquidity;
}
_removeLiquidity(positionId, objectId, setupIndex, unwrapPair, removedLiquidity, false);
}
| 38,434 |
0 | // contractState => (accountAddress => bool) | mapping (uint8 => mapping (address => bool)) public confirmations;
| mapping (uint8 => mapping (address => bool)) public confirmations;
| 12,193 |
149 | // PriorityQueue A priority queue implementation. / | contract PriorityQueue is Ownable {
using SafeMath for uint256;
uint256[] heapList;
uint256 public currentSize;
constructor() public {
heapList = [0];
}
/**
* @dev Inserts an element into the priority queue.
* @param _priority Priority to insert.
* @param _value Some additional value.
*/
function insert(uint256 _priority, uint256 _value) public onlyOwner {
uint256 element = (_priority << 128) | _value;
heapList.push(element);
currentSize = currentSize.add(1);
_percUp(currentSize);
}
/**
* @dev Returns the top element of the heap.
* @return The smallest element in the priority queue.
*/
function getMin() public view returns (uint256, uint256) {
return _splitElement(heapList[1]);
}
/**
* @dev Deletes the top element of the heap and shifts everything up.
* @return The smallest element in the priorty queue.
*/
function delMin() public onlyOwner returns (uint256, uint256) {
uint256 retVal = heapList[1];
heapList[1] = heapList[currentSize];
delete heapList[currentSize];
currentSize = currentSize.sub(1);
_percDown(1);
heapList.length = heapList.length.sub(1);
return _splitElement(retVal);
}
/**
* @dev Determines the minimum child of a given node in the tree.
* @param _index Index of the node in the tree.
* @return The smallest child node.
*/
function _minChild(uint256 _index) private view returns (uint256) {
if (_index.mul(2).add(1) > currentSize) {
return _index.mul(2);
} else {
if (heapList[_index.mul(2)] < heapList[_index.mul(2).add(1)]) {
return _index.mul(2);
} else {
return _index.mul(2).add(1);
}
}
}
/**
* @dev Bubbles the element at some index up.
*/
function _percUp(uint256 _index) private {
uint256 index = _index;
uint256 j = index;
uint256 newVal = heapList[index];
while (newVal < heapList[index.div(2)]) {
heapList[index] = heapList[index.div(2)];
index = index.div(2);
}
if (index != j) {
heapList[index] = newVal;
}
}
/**
* @dev Bubbles the element at some index down.
*/
function _percDown(uint256 _index) private {
uint256 index = _index;
uint256 j = index;
uint256 newVal = heapList[index];
uint256 mc = _minChild(index);
while (mc <= currentSize && newVal > heapList[mc]) {
heapList[index] = heapList[mc];
index = mc;
mc = _minChild(index);
}
if (index != j) {
heapList[index] = newVal;
}
}
/**
* @dev Split an element into its priority and value.
* @param _element Element to decode.
* @return A tuple containing the priority and value.
*/
function _splitElement(uint256 _element)
private
pure
returns (uint256, uint256)
{
uint256 priority = _element >> 128;
uint256 value = uint256(uint128(_element));
return (priority, value);
}
}
| contract PriorityQueue is Ownable {
using SafeMath for uint256;
uint256[] heapList;
uint256 public currentSize;
constructor() public {
heapList = [0];
}
/**
* @dev Inserts an element into the priority queue.
* @param _priority Priority to insert.
* @param _value Some additional value.
*/
function insert(uint256 _priority, uint256 _value) public onlyOwner {
uint256 element = (_priority << 128) | _value;
heapList.push(element);
currentSize = currentSize.add(1);
_percUp(currentSize);
}
/**
* @dev Returns the top element of the heap.
* @return The smallest element in the priority queue.
*/
function getMin() public view returns (uint256, uint256) {
return _splitElement(heapList[1]);
}
/**
* @dev Deletes the top element of the heap and shifts everything up.
* @return The smallest element in the priorty queue.
*/
function delMin() public onlyOwner returns (uint256, uint256) {
uint256 retVal = heapList[1];
heapList[1] = heapList[currentSize];
delete heapList[currentSize];
currentSize = currentSize.sub(1);
_percDown(1);
heapList.length = heapList.length.sub(1);
return _splitElement(retVal);
}
/**
* @dev Determines the minimum child of a given node in the tree.
* @param _index Index of the node in the tree.
* @return The smallest child node.
*/
function _minChild(uint256 _index) private view returns (uint256) {
if (_index.mul(2).add(1) > currentSize) {
return _index.mul(2);
} else {
if (heapList[_index.mul(2)] < heapList[_index.mul(2).add(1)]) {
return _index.mul(2);
} else {
return _index.mul(2).add(1);
}
}
}
/**
* @dev Bubbles the element at some index up.
*/
function _percUp(uint256 _index) private {
uint256 index = _index;
uint256 j = index;
uint256 newVal = heapList[index];
while (newVal < heapList[index.div(2)]) {
heapList[index] = heapList[index.div(2)];
index = index.div(2);
}
if (index != j) {
heapList[index] = newVal;
}
}
/**
* @dev Bubbles the element at some index down.
*/
function _percDown(uint256 _index) private {
uint256 index = _index;
uint256 j = index;
uint256 newVal = heapList[index];
uint256 mc = _minChild(index);
while (mc <= currentSize && newVal > heapList[mc]) {
heapList[index] = heapList[mc];
index = mc;
mc = _minChild(index);
}
if (index != j) {
heapList[index] = newVal;
}
}
/**
* @dev Split an element into its priority and value.
* @param _element Element to decode.
* @return A tuple containing the priority and value.
*/
function _splitElement(uint256 _element)
private
pure
returns (uint256, uint256)
{
uint256 priority = _element >> 128;
uint256 value = uint256(uint128(_element));
return (priority, value);
}
}
| 40,003 |
18 | // Tier 2 presale | require(_presaleAllowance[msg.sender] > 0, "You are not eligible to presale mint");
| require(_presaleAllowance[msg.sender] > 0, "You are not eligible to presale mint");
| 30,929 |
46 | // Returns a boolean stating whether `deployer` is allowed to deploy many-to-oneproxies. / | function isApprovedDeployer(address deployer) external override view returns (bool) {
return _approvedDeployers[deployer];
}
| function isApprovedDeployer(address deployer) external override view returns (bool) {
return _approvedDeployers[deployer];
}
| 5,382 |
12 | // The LIQUIDATION_KEEPER role. / | bytes32 public constant LIQUIDATION_KEEPER = keccak256(abi.encode("LIQUIDATION_KEEPER"));
| bytes32 public constant LIQUIDATION_KEEPER = keccak256(abi.encode("LIQUIDATION_KEEPER"));
| 25,764 |
78 | // Iterate the array of distributions sending the configured amounts | for (uint256 i = 0; i < distributions.length; i++) {
if (
distributions[i].destination != address(0) ||
distributions[i].amount != 0
) {
remainder = remainder.sub(distributions[i].amount);
| for (uint256 i = 0; i < distributions.length; i++) {
if (
distributions[i].destination != address(0) ||
distributions[i].amount != 0
) {
remainder = remainder.sub(distributions[i].amount);
| 15,887 |
54 | // Stake/Deposit into the reward pool (mining pool) for other account/ other The target account/ amount The target amount | function stakeForOther(address other, uint256 amount) external;
| function stakeForOther(address other, uint256 amount) external;
| 2,803 |
33 | // Check If SWAP contract have enaf ether for this opertion | require(this.balance>=safeAdd(msg.value, _ethBonus));
| require(this.balance>=safeAdd(msg.value, _ethBonus));
| 32,423 |
27 | // Transfer tokens from other addressSend '_value' tokens to '_to' on behalf of '_from'_from The address of the sender_to The address of the recipient_value The amount to be sent/ | function transferFrom(address _from, address _to, uint256 _value) public returns(bool success){
//Check allowance
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
| function transferFrom(address _from, address _to, uint256 _value) public returns(bool success){
//Check allowance
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
| 12,826 |
150 | // Make unspent vested balance persistent. | _balances[msg.sender] = _balances[msg.sender].add(unspentVestedBalance);
| _balances[msg.sender] = _balances[msg.sender].add(unspentVestedBalance);
| 18,888 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.