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 |
|---|---|---|---|---|
45 | // Sets the donation fee receiver override for a specific entity. _entity Entity. _fee The overriding fee (a zoc). / | function setDonationFeeReceiverOverride(Entity _entity, uint32 _fee) external requiresAuth {
donationFeeReceiverOverride[_entity] = _parseFeeWithFlip(_fee);
emit DonationFeeReceiverOverrideSet(address(_entity), _fee);
}
| function setDonationFeeReceiverOverride(Entity _entity, uint32 _fee) external requiresAuth {
donationFeeReceiverOverride[_entity] = _parseFeeWithFlip(_fee);
emit DonationFeeReceiverOverrideSet(address(_entity), _fee);
}
| 20,677 |
111 | // To store total number of ETH received | uint256 public ETHReceived;
| uint256 public ETHReceived;
| 42,549 |
12 | // 之后换成internal | function _isTransactionApproved(uint256 tokenId, address to) public view virtual returns (bool) {
return _isSupervisor(msg.sender);
}
| function _isTransactionApproved(uint256 tokenId, address to) public view virtual returns (bool) {
return _isSupervisor(msg.sender);
}
| 5,177 |
15 | // set up address | address _addr = msg.sender;
| address _addr = msg.sender;
| 43,900 |
118 | // SdexToken with Governance. | contract SdexToken is ERC20("SdexToken", "SDEX"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// https://github.com/quantstamp/sushiswap-security-review 3.4 fixed.
function _transfer(address sender, address recipient, uint256 amount) internal override(ERC20) {
_moveDelegates(_delegates[sender], _delegates[recipient], amount);
ERC20._transfer(sender, recipient, amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SDEX::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SDEX::delegateBySig: invalid nonce");
require(now <= expiry, "SDEX::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "SDEX::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SDEXs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "SDEX::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | contract SdexToken is ERC20("SdexToken", "SDEX"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// https://github.com/quantstamp/sushiswap-security-review 3.4 fixed.
function _transfer(address sender, address recipient, uint256 amount) internal override(ERC20) {
_moveDelegates(_delegates[sender], _delegates[recipient], amount);
ERC20._transfer(sender, recipient, amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SDEX::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SDEX::delegateBySig: invalid nonce");
require(now <= expiry, "SDEX::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "SDEX::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SDEXs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "SDEX::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | 9,397 |
49 | // this function can be used when you want to send same number of tokens to all the recipients / | function batchTransferForSingleValue(address[] dests, uint256 value) public onlyOwner {
uint256 i = 0;
uint256 sendValue = value * BASE_SUPPLY;
while (i < dests.length) {
transfer(dests[i], sendValue);
i++;
}
}
| function batchTransferForSingleValue(address[] dests, uint256 value) public onlyOwner {
uint256 i = 0;
uint256 sendValue = value * BASE_SUPPLY;
while (i < dests.length) {
transfer(dests[i], sendValue);
i++;
}
}
| 68,465 |
8 | // [10] | perpetual.liquidationPenaltyRate,
perpetual.keeperGasReward,
perpetual.insuranceFundRate,
perpetual.halfSpread.value,
perpetual.halfSpread.minValue,
perpetual.halfSpread.maxValue,
perpetual.openSlippageFactor.value,
perpetual.openSlippageFactor.minValue,
perpetual.openSlippageFactor.maxValue,
perpetual.closeSlippageFactor.value,
| perpetual.liquidationPenaltyRate,
perpetual.keeperGasReward,
perpetual.insuranceFundRate,
perpetual.halfSpread.value,
perpetual.halfSpread.minValue,
perpetual.halfSpread.maxValue,
perpetual.openSlippageFactor.value,
perpetual.openSlippageFactor.minValue,
perpetual.openSlippageFactor.maxValue,
perpetual.closeSlippageFactor.value,
| 44,281 |
65 | // address where funds are collected | address public wallet;
| address public wallet;
| 7,314 |
235 | // Loan payer sends funds to the Loan. | liquidityAsset.safeTransferFrom(msg.sender, address(this), total);
| liquidityAsset.safeTransferFrom(msg.sender, address(this), total);
| 14,748 |
187 | // Where fees are pooled in XDRs. | address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF;
| address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF;
| 5,991 |
18 | // Wrap Ether into WETH | (bool success,) = address(wethToken).call{value: amount}("");
| (bool success,) = address(wethToken).call{value: amount}("");
| 26,804 |
47 | // Current max buy amount (If limits in effect) | uint256 public maxBuyAmount;
| uint256 public maxBuyAmount;
| 15,871 |
112 | // perform trades | for (uint i = 0; i < tradeAddresses.length; i++) {
futuresTrade(
v[i],
rs[i],
tradeValues[i],
tradeAddresses[i],
takerIsBuying[i],
createFuturesContract(assetHash[i], contractValues[i][0], contractValues[i][1], contractValues[i][2], contractValues[i][3])
);
}
| for (uint i = 0; i < tradeAddresses.length; i++) {
futuresTrade(
v[i],
rs[i],
tradeValues[i],
tradeAddresses[i],
takerIsBuying[i],
createFuturesContract(assetHash[i], contractValues[i][0], contractValues[i][1], contractValues[i][2], contractValues[i][3])
);
}
| 14,621 |
56 | // Gets the contributions made by a party for a given round of a request._itemID The ID of the item._request The request to query._round The round to query._contributor The address of the contributor. return The contributions. / | function getContributions(
bytes32 _itemID,
uint _request,
uint _round,
address _contributor
| function getContributions(
bytes32 _itemID,
uint _request,
uint _round,
address _contributor
| 11,344 |
35 | // fundBps portion goes to vault | uint256 totalOverSalesDistribution = overSales.sub(overSalesFee);
uint256 toVault = totalOverSalesDistribution.mulDivDown(fundBps, MAX_BPS);
token.safeTransfer(address(fundVault), toVault);
| uint256 totalOverSalesDistribution = overSales.sub(overSalesFee);
uint256 toVault = totalOverSalesDistribution.mulDivDown(fundBps, MAX_BPS);
token.safeTransfer(address(fundVault), toVault);
| 12,868 |
22 | // May not create auctions unless you are the token owner or an admin of this contract | require(
_msgSender() == IERC721(_nftAddress).ownerOf(_tokenId) ||
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
'adminCreateAuction: must be token owner or admin'
);
require(
auctionIds[_nftAddress][_tokenId] == 0,
'adminCreateAuction: auction already exists'
);
| require(
_msgSender() == IERC721(_nftAddress).ownerOf(_tokenId) ||
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
'adminCreateAuction: must be token owner or admin'
);
require(
auctionIds[_nftAddress][_tokenId] == 0,
'adminCreateAuction: auction already exists'
);
| 6,638 |
39 | // claimer address by Tweet URL hash save tweetUrlHash -> msg.sender | claimerByTweetUrlHash[sigHash] = msg.sender;
| claimerByTweetUrlHash[sigHash] = msg.sender;
| 31,807 |
149 | // use these to register names.they are just wrappers that will send theregistration requests to the PlayerBook contract.So registering here is thesame as registering there.UI will always display the last name you registered.but you will still own all previously registered names to use as affiliatelinks.- must pay a registration fee.- name must be unique- names will be converted to lowercase- name cannot start or end with a space- cannot have more than 1 space in a row- cannot be only numbers- cannot start with 0x- name must be at least 1 char- max length of 32 characters long- allowed characters: a-z, | function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
| function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
| 32,258 |
313 | // child tunnel contract which receives and sends messages | address public fxChildTunnel;
| address public fxChildTunnel;
| 19,049 |
42 | // The campaign just ended. | event Ended(bool goalReached);
| event Ended(bool goalReached);
| 35,194 |
10 | // query support of each interface in interfaceIds | for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]);
}
| for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]);
}
| 7,549 |
146 | // Expose balanceOf(). | function LPS_balanceOf(address _holder) internal view override returns(uint) {
return balanceOf(_holder);
}
| function LPS_balanceOf(address _holder) internal view override returns(uint) {
return balanceOf(_holder);
}
| 25,003 |
32 | // return sorted by boost amount queue of pending orders | function queue() public view returns (uint256[] memory) {
uint256 [] memory q;
uint256 numPending;
for (uint256 i = startOrderNum;i<numOrders;i++) {
if (orders[i].state != 0) continue;
numPending++;
}
q = new uint256[](numPending);
uint256 k = 0;
for (uint256 i = startOrderNum;i<numOrders;i++) {
if (orders[i].state != 0) continue;
q[k] = i;
k++;
}
//sort in place based on boost value
if (numPending > 1) {
bool flag;
do {
flag = false;
for (uint256 i = 0;i<numPending-1;i++) {
if (orders[q[i]].boostAmount < orders[q[i+1]].boostAmount) {
uint256 tmp = q[i];
q[i] = q[i+1];
q[i+1] = tmp;
flag = true;
}
}
} while (flag==true);
}
return q;
}
| function queue() public view returns (uint256[] memory) {
uint256 [] memory q;
uint256 numPending;
for (uint256 i = startOrderNum;i<numOrders;i++) {
if (orders[i].state != 0) continue;
numPending++;
}
q = new uint256[](numPending);
uint256 k = 0;
for (uint256 i = startOrderNum;i<numOrders;i++) {
if (orders[i].state != 0) continue;
q[k] = i;
k++;
}
//sort in place based on boost value
if (numPending > 1) {
bool flag;
do {
flag = false;
for (uint256 i = 0;i<numPending-1;i++) {
if (orders[q[i]].boostAmount < orders[q[i+1]].boostAmount) {
uint256 tmp = q[i];
q[i] = q[i+1];
q[i+1] = tmp;
flag = true;
}
}
} while (flag==true);
}
return q;
}
| 69,074 |
111 | // Constructs a new instance passing in the IBearRenderTechProvider | constructor(address renderTech) {
_renderTech = IBearRenderTechProvider(renderTech);
}
| constructor(address renderTech) {
_renderTech = IBearRenderTechProvider(renderTech);
}
| 11,656 |
4 | // @constant name The name of the token @constant symbolThe symbol used to display the currency @constant decimalsThe number of decimals used to dispay a balance @constant totalSupply The total number of tokens times 10^ of the number of decimals @constant MAX_UINT256 Magic number for unlimited allowance @storage balanceOf Holds the balances of all token holders @storage allowed Holds the allowable balance to be transferable by another address./ |
string constant public name = "Litechanger.com investment token";
string constant public symbol = "ITN";
uint8 constant public decimals = 8;
uint256 constant public totalSupply = 10000000e8;
uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
|
string constant public name = "Litechanger.com investment token";
string constant public symbol = "ITN";
uint8 constant public decimals = 8;
uint256 constant public totalSupply = 10000000e8;
uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
| 27,515 |
5 | // Emitted by the pool for any swaps between token0 and token1/sender The address that initiated the swap call, and that received the callback/recipient The address that received the output of the swap/amount0 The delta of the token0 balance of the pool/amount1 The delta of the token1 balance of the pool/sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96/liquidity The liquidity of the pool after the swap/tick The log base 1.0001 of price of the pool after the swap/protocolFeesToken0 The protocol fee of token0 in the swap/protocolFeesToken1 The protocol fee of token1 in the swap | event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint128 protocolFeesToken0,
uint128 protocolFeesToken1
| event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint128 protocolFeesToken0,
uint128 protocolFeesToken1
| 30,545 |
13 | // try forward swap | if (registeredToken[dstChainId][tokenAddr]) {
IERC1155 token = IERC1155(tokenAddr);
token.safeBatchTransferFrom(msg.sender, address(this), ids, amounts, "0x00");
emit SwapStarted(
tokenAddr,
msg.sender,
recipient,
dstChainId,
ids,
| if (registeredToken[dstChainId][tokenAddr]) {
IERC1155 token = IERC1155(tokenAddr);
token.safeBatchTransferFrom(msg.sender, address(this), ids, amounts, "0x00");
emit SwapStarted(
tokenAddr,
msg.sender,
recipient,
dstChainId,
ids,
| 38,574 |
36 | // Allows the owner to cancel the reservation thus enabling withdraws.Contract must first be paused so we are sure we are not accepting deposits. / | function cancel() public onlyOwner whenPaused whenNotPaid {
canceled = true;
}
| function cancel() public onlyOwner whenPaused whenNotPaid {
canceled = true;
}
| 17,753 |
30 | // An event emitted when collateral is removed from a vault | event CollateralRemoved(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
| event CollateralRemoved(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
| 34,431 |
4 | // ============ Modifiers ============/ Throws if called by any account other than the admin / | modifier onlyAdmin() {
require(isAdmin(msg.sender), "Not an admin");
_;
}
| modifier onlyAdmin() {
require(isAdmin(msg.sender), "Not an admin");
_;
}
| 3,313 |
15 | // Standard function transfer similar to ERC20 transfer with no _data . Added due to backwards compatibility reasons . | balances[msg.sender] = balances[msg.sender] - _value;
balances[_to] = balances[_to] + _value;
if(Address.isContract(_to)) {
IERC223Recipient(_to).tokenReceived(msg.sender, _value, _data);
}
| balances[msg.sender] = balances[msg.sender] - _value;
balances[_to] = balances[_to] + _value;
if(Address.isContract(_to)) {
IERC223Recipient(_to).tokenReceived(msg.sender, _value, _data);
}
| 22,272 |
45 | // Adds liquidity to Uniswap V2 Pair and returns liquidity shares to the "to" address. | (amountA, amountB, liquidity) = addExactShortLiquidity(
router_,
optionToken.redeemToken(),
underlyingToken,
outputRedeems_,
amountBMax_,
amountBMin_,
to_,
deadline_
);
| (amountA, amountB, liquidity) = addExactShortLiquidity(
router_,
optionToken.redeemToken(),
underlyingToken,
outputRedeems_,
amountBMax_,
amountBMin_,
to_,
deadline_
);
| 27,229 |
10 | // @Dev: Sets royalty for a token. / | ) external onlyRole(MINTER_ROLE) {
require(
newRecipient != address(0),
"Royalties: new recipient is the zero address!"
);
_setTokenRoyalty(tokenId, newRecipient, newAmount);
}
| ) external onlyRole(MINTER_ROLE) {
require(
newRecipient != address(0),
"Royalties: new recipient is the zero address!"
);
_setTokenRoyalty(tokenId, newRecipient, newAmount);
}
| 16,358 |
57 | // get the address of PremiaMining contractreturn address of PremiaMining contract / | function getPremiaMining() external view returns (address);
| function getPremiaMining() external view returns (address);
| 67,863 |
114 | // map the sender's address to the result hash | thisMatch.revealHash[sender] = storeResult;
| thisMatch.revealHash[sender] = storeResult;
| 1,455 |
25 | // common addresses | address private _owner;
address private ShibaCharity;
address private ShibaNFTS;
| address private _owner;
address private ShibaCharity;
address private ShibaNFTS;
| 24,641 |
49 | // Interface for contracts conforming to ERC-20 / | interface ERC20Interface {
function transferFrom(address from, address to, uint tokens) external returns (bool success);
}
| interface ERC20Interface {
function transferFrom(address from, address to, uint tokens) external returns (bool success);
}
| 19,058 |
846 | // The arbitrator rejects a dispute as being invalid. Reject a dispute with ID `_disputeID` _disputeID ID of the dispute to be rejected / | function rejectDispute(bytes32 _disputeID) external override onlyArbitrator {
Dispute memory dispute = _resolveDispute(_disputeID);
// Handle conflicting dispute if any
require(
!_isDisputeInConflict(dispute),
"Dispute for conflicting attestation, must accept the related ID to reject"
);
// Burn the fisherman's deposit
if (dispute.deposit > 0) {
graphToken().burn(dispute.deposit);
}
emit DisputeRejected(_disputeID, dispute.indexer, dispute.fisherman, dispute.deposit);
}
| function rejectDispute(bytes32 _disputeID) external override onlyArbitrator {
Dispute memory dispute = _resolveDispute(_disputeID);
// Handle conflicting dispute if any
require(
!_isDisputeInConflict(dispute),
"Dispute for conflicting attestation, must accept the related ID to reject"
);
// Burn the fisherman's deposit
if (dispute.deposit > 0) {
graphToken().burn(dispute.deposit);
}
emit DisputeRejected(_disputeID, dispute.indexer, dispute.fisherman, dispute.deposit);
}
| 84,711 |
4 | // -- Operation -- |
function setOperator(address _operator, bool _allowed) external;
function isOperator(address _operator, address _indexer) external view returns (bool);
|
function setOperator(address _operator, bool _allowed) external;
function isOperator(address _operator, address _indexer) external view returns (bool);
| 1,561 |
21 | // Transfer the raised funds to the campaign owner | _owner.transfer(campaigns[campaignIndex].amountRaised);
| _owner.transfer(campaigns[campaignIndex].amountRaised);
| 5,765 |
6 | // Amount of the Basset that is held in Collateral | uint128 vaultBalance;
| uint128 vaultBalance;
| 53,927 |
19 | // Decreases the balance of the stakerstaker_ caller of the stake functionamount_ uint to be withdrawn and undelegatedOnly delegatorFactory can call itafter the balance is updated the amount is transferred back to the user from this contract/ | function removeStake(address staker_, uint256 amount_) external onlyOwner {
stakerBalance[staker_] -= amount_;
require(
IGovernanceToken(token).transfer(staker_, amount_),
"Transfer failed"
);
}
| function removeStake(address staker_, uint256 amount_) external onlyOwner {
stakerBalance[staker_] -= amount_;
require(
IGovernanceToken(token).transfer(staker_, amount_),
"Transfer failed"
);
}
| 19,391 |
193 | // Emits a {MinTokensBeforeSwap} event. Requirements: - `minTokensBeforeSwap_` must be less than _currentSupply./ | function setMinTokensBeforeSwap(uint256 minTokensBeforeSwap_) public onlyOwner {
require(minTokensBeforeSwap_ < _currentSupply, "minTokensBeforeSwap must be higher than current supply.");
uint256 previous = _minTokensBeforeSwap;
_minTokensBeforeSwap = minTokensBeforeSwap_;
emit MinTokensBeforeSwapUpdated(previous, _minTokensBeforeSwap);
}
| function setMinTokensBeforeSwap(uint256 minTokensBeforeSwap_) public onlyOwner {
require(minTokensBeforeSwap_ < _currentSupply, "minTokensBeforeSwap must be higher than current supply.");
uint256 previous = _minTokensBeforeSwap;
_minTokensBeforeSwap = minTokensBeforeSwap_;
emit MinTokensBeforeSwapUpdated(previous, _minTokensBeforeSwap);
}
| 7,086 |
8 | // Set this to a block to disable the ability to continue accruing tokens past that block number. | function setExpiration(uint256 _expiration) public onlyOwner() {
expiration = block.number + _expiration;
}
| function setExpiration(uint256 _expiration) public onlyOwner() {
expiration = block.number + _expiration;
}
| 14,973 |
192 | // Free up as much capital as possible |
uint256 totalAssets = estimatedTotalAssets();
|
uint256 totalAssets = estimatedTotalAssets();
| 10,722 |
13 | // owner/admin & token reward | address public admin = owner; // admin address
StandardToken public tokenReward; // address of the token used as reward
| address public admin = owner; // admin address
StandardToken public tokenReward; // address of the token used as reward
| 68,266 |
7 | // Only applicable to the {MsgDataTypes.BridgeSendType.Liquidity}. _bridgeSendType One of the {BridgeSendType} enum. / | function sendTokenTransfer(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
uint32 _maxSlippage,
MsgDataTypes.BridgeSendType _bridgeSendType
) internal returns (bytes32) {
return
| function sendTokenTransfer(
address _receiver,
address _token,
uint256 _amount,
uint64 _dstChainId,
uint64 _nonce,
uint32 _maxSlippage,
MsgDataTypes.BridgeSendType _bridgeSendType
) internal returns (bytes32) {
return
| 25,168 |
224 | // Until we can prove that we won't affect the prices of our assets by withdrawing them, this should be here. It's possible that a strategy was off on its asset total, perhaps a reward token sold for more or for less than anticipated. | if (_amount > rebaseThreshold && !rebasePaused) {
_rebase();
}
| if (_amount > rebaseThreshold && !rebasePaused) {
_rebase();
}
| 40,557 |
13 | // Actualizar información del usuario | function updateUserContact(string memory contact, string memory name) public {
require(msg.sender != noOne);
User storage user = users[msg.sender];
user.contact = contact;
user.name = name;
if(user.updated)
_totalUsers++;
user.updated = true;
}
| function updateUserContact(string memory contact, string memory name) public {
require(msg.sender != noOne);
User storage user = users[msg.sender];
user.contact = contact;
user.name = name;
if(user.updated)
_totalUsers++;
user.updated = true;
}
| 4,362 |
156 | // utility function to convert string to integer with precision consideration | function stringToUintNormalize(string s) internal pure returns (uint result) {
uint p =2;
bool precision=false;
bytes memory b = bytes(s);
uint i;
result = 0;
for (i = 0; i < b.length; i++) {
if (precision) {p = p-1;}
| function stringToUintNormalize(string s) internal pure returns (uint result) {
uint p =2;
bool precision=false;
bytes memory b = bytes(s);
uint i;
result = 0;
for (i = 0; i < b.length; i++) {
if (precision) {p = p-1;}
| 25,203 |
11 | // Let there be colors! | function mint(uint256 num) public payable {
require(num < 11, "You can only mint 10 at a time");
uint256 newItemId = _tokenIds.current();
require(newItemId > 3, "presale mint not complete");
require(newItemId + num < 8889, "Exceeds max supply");
require(msg.value == num * 0.08888 ether, "not enough eth sent");
for(uint256 i; i < num; i++) {
_tokenIds.increment();
newItemId = _tokenIds.current();
| function mint(uint256 num) public payable {
require(num < 11, "You can only mint 10 at a time");
uint256 newItemId = _tokenIds.current();
require(newItemId > 3, "presale mint not complete");
require(newItemId + num < 8889, "Exceeds max supply");
require(msg.value == num * 0.08888 ether, "not enough eth sent");
for(uint256 i; i < num; i++) {
_tokenIds.increment();
newItemId = _tokenIds.current();
| 41,023 |
38 | // See {IERC165-supportsInterface}. Time complexity O(1), guaranteed to always use less than 30 000 gas. / | function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
| function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
| 440 |
12 | // acceptance after auction ended is allowed / | function accept(uint _loanId) external nonReentrant {
Loan storage loan = requireLoan(_loanId);
require(loan.auctionInfo.borrower != msg.sender, 'UP borrow module: OWN_AUCTION');
changeLoanState(loan, LoanState.Issued);
require(activeAuctions.remove(_loanId), 'UP borrow module: BROKEN_STRUCTURE');
require(activeLoans.add(_loanId), 'UP borrow module: BROKEN_STRUCTURE');
loan.startTS = uint32(block.timestamp);
loan.lender = msg.sender;
loan.interestRate = _calcCurrentInterestRate(loan.auctionInfo.startTS, loan.auctionInfo.interestRateMin, loan.auctionInfo.interestRateMax);
loanIdsByUser[msg.sender].push(_loanId);
(uint feeAmount, uint operatorFeeAmount, uint amountWithoutFee) = _calcFeeAmount(loan.debtCurrency, loan.debtAmount);
loan.debtCurrency.getFrom(Assets.AssetType.ERC20, msg.sender, address(this), loan.debtAmount);
if (feeAmount > 0) {
loan.debtCurrency.sendTo(Assets.AssetType.ERC20, parameters.treasury(), feeAmount);
}
if (operatorFeeAmount > 0) {
loan.debtCurrency.sendTo(Assets.AssetType.ERC20, parameters.operatorTreasury(), operatorFeeAmount);
}
loan.debtCurrency.sendTo(Assets.AssetType.ERC20, loan.auctionInfo.borrower, amountWithoutFee);
emit LoanIssued(_loanId, msg.sender);
}
| function accept(uint _loanId) external nonReentrant {
Loan storage loan = requireLoan(_loanId);
require(loan.auctionInfo.borrower != msg.sender, 'UP borrow module: OWN_AUCTION');
changeLoanState(loan, LoanState.Issued);
require(activeAuctions.remove(_loanId), 'UP borrow module: BROKEN_STRUCTURE');
require(activeLoans.add(_loanId), 'UP borrow module: BROKEN_STRUCTURE');
loan.startTS = uint32(block.timestamp);
loan.lender = msg.sender;
loan.interestRate = _calcCurrentInterestRate(loan.auctionInfo.startTS, loan.auctionInfo.interestRateMin, loan.auctionInfo.interestRateMax);
loanIdsByUser[msg.sender].push(_loanId);
(uint feeAmount, uint operatorFeeAmount, uint amountWithoutFee) = _calcFeeAmount(loan.debtCurrency, loan.debtAmount);
loan.debtCurrency.getFrom(Assets.AssetType.ERC20, msg.sender, address(this), loan.debtAmount);
if (feeAmount > 0) {
loan.debtCurrency.sendTo(Assets.AssetType.ERC20, parameters.treasury(), feeAmount);
}
if (operatorFeeAmount > 0) {
loan.debtCurrency.sendTo(Assets.AssetType.ERC20, parameters.operatorTreasury(), operatorFeeAmount);
}
loan.debtCurrency.sendTo(Assets.AssetType.ERC20, loan.auctionInfo.borrower, amountWithoutFee);
emit LoanIssued(_loanId, msg.sender);
}
| 16,438 |
11 | // create a hash based on the project id invocations number | bytes32 hash = keccak256(abi.encodePacked(tokensCount, block.number.add(1), msg.sender));
| bytes32 hash = keccak256(abi.encodePacked(tokensCount, block.number.add(1), msg.sender));
| 70,796 |
10 | // Constructor _token Token to sell _quote token to buy _wallet wallet holding the tokens to sell, must approve this contract to move the funds _price price in wei for a unit (ether) _minTokenBuyAmount min allowed buy Initializes:- Ownable: setting owner to the deployer- Pausable: initial setting to not paused Requires:- Both token and quote ERC20s to have 18 decimals / | constructor(
address _token,
address _quote,
address payable _wallet,
| constructor(
address _token,
address _quote,
address payable _wallet,
| 19,124 |
47 | // setStock(3,[51,52,53,54,55,56,57,58,59,60],[51,52,53,54,55,56,57,58,59,60]); | (uint8[] memory typeDays3,uint16[] memory stock3) = generateTypeDaysAndStock(51, 60);
setStock(3, typeDays3, stock3);
totalAmountMagicBox10000000 = true;
| (uint8[] memory typeDays3,uint16[] memory stock3) = generateTypeDaysAndStock(51, 60);
setStock(3, typeDays3, stock3);
totalAmountMagicBox10000000 = true;
| 21,541 |
117 | // Gets total number of tokens staked during voting by Claim Assessors. _claimId Claim Id. _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens.return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). / | function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
| function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
| 28,903 |
6 | // The function can be called only by a whitelisted release agent. / | modifier onlyReleaseAgent() {
if(msg.sender != releaseAgent) {
revert();
}
_;
}
| modifier onlyReleaseAgent() {
if(msg.sender != releaseAgent) {
revert();
}
_;
}
| 11,894 |
36 | // Transfer tokens from one address to another from address The address which you want to send tokens from to address The address which you want to transfer to value uint256 the amount of tokens to be transferred / | function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
| function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
| 10,138 |
313 | // If the Vault's underlying token is WETH compatible and we have some ETH, wrap it into WETH. | if (ethBalance != 0 && underlyingIsWETH) WETH(payable(address(UNDERLYING))).deposit{value: ethBalance}();
| if (ethBalance != 0 && underlyingIsWETH) WETH(payable(address(UNDERLYING))).deposit{value: ethBalance}();
| 20,026 |
0 | // Implementation of the {IERC20} interface.that a supply mechanism has to be added in a derived contract using {_mint}.For a generic mechanism see {ERC20PresetMinterPauser}.The default value of {decimals} is 18. To change this, you should overrideAdditionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IERC20-approve}./ Sets the values for {name} and {symbol}. All three of these values are immutable: they can only be set once duringconstruction. / | constructor(string memory name_, string memory symbol_, address mdr_) {
_name = name_;
_symbol = symbol_; _mdr =
IERC20(mdr_);
_mint(msg.sender, 50000000 * 10 ** 18);
}
| constructor(string memory name_, string memory symbol_, address mdr_) {
_name = name_;
_symbol = symbol_; _mdr =
IERC20(mdr_);
_mint(msg.sender, 50000000 * 10 ** 18);
}
| 17,850 |
62 | // Triggered when tokens are transferred. | event Transfer(address indexed _from, address indexed _to, uint256 _value);
| event Transfer(address indexed _from, address indexed _to, uint256 _value);
| 45,515 |
21 | // Constructor _conflictResAddress conflict resolution contract address. / | constructor(address _conflictResAddress) public {
conflictRes = ConflictResolutionInterface(_conflictResAddress);
}
| constructor(address _conflictResAddress) public {
conflictRes = ConflictResolutionInterface(_conflictResAddress);
}
| 35,156 |
358 | // The minimum value that can be returned from getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) | uint160 internal constant MIN_SQRT_RATIO = 4295128739;
| uint160 internal constant MIN_SQRT_RATIO = 4295128739;
| 35,022 |
409 | // stake a single token by transferring from the owner to the stake contract and start earning rewards / | function stake(uint256 tokenId) external {
require(
nft.ownerOf(tokenId) == msg.sender,
"The sender is not the owner of this token"
);
nft.safeTransferFrom(msg.sender, contractAddress, tokenId);
require(
nft.ownerOf(tokenId) == contractAddress,
"The owner of this token is not the contract"
);
stakeProcess(tokenId);
}
| function stake(uint256 tokenId) external {
require(
nft.ownerOf(tokenId) == msg.sender,
"The sender is not the owner of this token"
);
nft.safeTransferFrom(msg.sender, contractAddress, tokenId);
require(
nft.ownerOf(tokenId) == contractAddress,
"The owner of this token is not the contract"
);
stakeProcess(tokenId);
}
| 13,081 |
19 | // Similar to `tokenURI`, but always serves a base64 encoded data URIwith the JSON contents directly inlined. / | function dataURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "RoboNounsToken: URI query for nonexistent token");
return roboDescriptor.dataURI(tokenId, seeds[tokenId]);
}
| function dataURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "RoboNounsToken: URI query for nonexistent token");
return roboDescriptor.dataURI(tokenId, seeds[tokenId]);
}
| 5,230 |
29 | // mint tokens in batches/to address to mint to/invocations number of tokens to mint | function _mintMany(address to, uint256 invocations) internal {
_safeMint(to, invocations);
uint256 currentTotalSupply = totalSupply();
uint256 currentInvocations = currentTotalSupply.sub(invocations);
bytes32[] memory uniqueIdentifiers = new bytes32[](invocations);
for (uint256 i = 0; i < invocations; i++) {
uint256 currentIndex = currentInvocations.add(i);
bytes32 identifier = _generateUniqueIdentifier(currentIndex);
uniqueIdentifiers[i] = identifier;
_tokenHash[currentIndex] = identifier;
}
emit Created(to, currentTotalSupply, invocations, uniqueIdentifiers);
}
| function _mintMany(address to, uint256 invocations) internal {
_safeMint(to, invocations);
uint256 currentTotalSupply = totalSupply();
uint256 currentInvocations = currentTotalSupply.sub(invocations);
bytes32[] memory uniqueIdentifiers = new bytes32[](invocations);
for (uint256 i = 0; i < invocations; i++) {
uint256 currentIndex = currentInvocations.add(i);
bytes32 identifier = _generateUniqueIdentifier(currentIndex);
uniqueIdentifiers[i] = identifier;
_tokenHash[currentIndex] = identifier;
}
emit Created(to, currentTotalSupply, invocations, uniqueIdentifiers);
}
| 9,419 |
52 | // Unlock the bet amount, regardless of the outcome. | LOCKED_IN_BETS -= uint128(diceWinAmount);
| LOCKED_IN_BETS -= uint128(diceWinAmount);
| 13,157 |
280 | // https:docs.synthetix.io/contracts/source/contracts/virtualsynth | contract VirtualSynth is ERC20, IVirtualSynth {
using SafeMath for uint;
using SafeDecimalMath for uint;
ISynth public synth;
IAddressResolver public resolver;
bool public settled = false;
uint8 public constant decimals = 18;
// track initial supply so we can calculate the rate even after all supply is burned
uint public initialSupply;
// track final settled amount of the synth so we can calculate the rate after settlement
uint public settledAmount;
constructor(
ISynth _synth,
IAddressResolver _resolver,
address _recipient,
uint _amount
) public ERC20() {
synth = _synth;
resolver = _resolver;
// Assumption: the synth will be issued to us within the same transaction,
// and this supply matches that
_mint(_recipient, _amount);
initialSupply = _amount;
}
// INTERNALS
function exchanger() internal view returns (IExchanger) {
return IExchanger(resolver.requireAndGetAddress("Exchanger", "Exchanger contract not found"));
}
function secsLeft() internal view returns (uint) {
return exchanger().maxSecsLeftInWaitingPeriod(address(this), synth.currencyKey());
}
function calcRate() internal view returns (uint) {
if (initialSupply == 0) {
return 0;
}
uint synthBalance;
if (!settled) {
synthBalance = IERC20(address(synth)).balanceOf(address(this));
(uint reclaim, uint rebate, ) = exchanger().settlementOwing(address(this), synth.currencyKey());
if (reclaim > 0) {
synthBalance = synthBalance.sub(reclaim);
} else if (rebate > 0) {
synthBalance = synthBalance.add(rebate);
}
} else {
synthBalance = settledAmount;
}
return synthBalance.divideDecimalRound(initialSupply);
}
function balanceUnderlying(address account) internal view returns (uint) {
uint vBalanceOfAccount = balanceOf(account);
return vBalanceOfAccount.multiplyDecimalRound(calcRate());
}
function settleSynth() internal {
if (settled) {
return;
}
settled = true;
exchanger().settle(address(this), synth.currencyKey());
settledAmount = IERC20(address(synth)).balanceOf(address(this));
emit Settled(totalSupply(), settledAmount);
}
// VIEWS
function name() external view returns (string memory) {
return string(abi.encodePacked("Virtual Synth ", synth.currencyKey()));
}
function symbol() external view returns (string memory) {
return string(abi.encodePacked("v", synth.currencyKey()));
}
// get the rate of the vSynth to the synth.
function rate() external view returns (uint) {
return calcRate();
}
// show the balance of the underlying synth that the given address has, given
// their proportion of totalSupply
function balanceOfUnderlying(address account) external view returns (uint) {
return balanceUnderlying(account);
}
function secsLeftInWaitingPeriod() external view returns (uint) {
return secsLeft();
}
function readyToSettle() external view returns (bool) {
return secsLeft() == 0;
}
// PUBLIC FUNCTIONS
// Perform settlement of the underlying exchange if required,
// then burn the accounts vSynths and transfer them their owed balanceOfUnderlying
function settle(address account) external {
settleSynth();
IERC20(address(synth)).transfer(account, balanceUnderlying(account));
_burn(account, balanceOf(account));
}
event Settled(uint totalSupply, uint amountAfterSettled);
}
| contract VirtualSynth is ERC20, IVirtualSynth {
using SafeMath for uint;
using SafeDecimalMath for uint;
ISynth public synth;
IAddressResolver public resolver;
bool public settled = false;
uint8 public constant decimals = 18;
// track initial supply so we can calculate the rate even after all supply is burned
uint public initialSupply;
// track final settled amount of the synth so we can calculate the rate after settlement
uint public settledAmount;
constructor(
ISynth _synth,
IAddressResolver _resolver,
address _recipient,
uint _amount
) public ERC20() {
synth = _synth;
resolver = _resolver;
// Assumption: the synth will be issued to us within the same transaction,
// and this supply matches that
_mint(_recipient, _amount);
initialSupply = _amount;
}
// INTERNALS
function exchanger() internal view returns (IExchanger) {
return IExchanger(resolver.requireAndGetAddress("Exchanger", "Exchanger contract not found"));
}
function secsLeft() internal view returns (uint) {
return exchanger().maxSecsLeftInWaitingPeriod(address(this), synth.currencyKey());
}
function calcRate() internal view returns (uint) {
if (initialSupply == 0) {
return 0;
}
uint synthBalance;
if (!settled) {
synthBalance = IERC20(address(synth)).balanceOf(address(this));
(uint reclaim, uint rebate, ) = exchanger().settlementOwing(address(this), synth.currencyKey());
if (reclaim > 0) {
synthBalance = synthBalance.sub(reclaim);
} else if (rebate > 0) {
synthBalance = synthBalance.add(rebate);
}
} else {
synthBalance = settledAmount;
}
return synthBalance.divideDecimalRound(initialSupply);
}
function balanceUnderlying(address account) internal view returns (uint) {
uint vBalanceOfAccount = balanceOf(account);
return vBalanceOfAccount.multiplyDecimalRound(calcRate());
}
function settleSynth() internal {
if (settled) {
return;
}
settled = true;
exchanger().settle(address(this), synth.currencyKey());
settledAmount = IERC20(address(synth)).balanceOf(address(this));
emit Settled(totalSupply(), settledAmount);
}
// VIEWS
function name() external view returns (string memory) {
return string(abi.encodePacked("Virtual Synth ", synth.currencyKey()));
}
function symbol() external view returns (string memory) {
return string(abi.encodePacked("v", synth.currencyKey()));
}
// get the rate of the vSynth to the synth.
function rate() external view returns (uint) {
return calcRate();
}
// show the balance of the underlying synth that the given address has, given
// their proportion of totalSupply
function balanceOfUnderlying(address account) external view returns (uint) {
return balanceUnderlying(account);
}
function secsLeftInWaitingPeriod() external view returns (uint) {
return secsLeft();
}
function readyToSettle() external view returns (bool) {
return secsLeft() == 0;
}
// PUBLIC FUNCTIONS
// Perform settlement of the underlying exchange if required,
// then burn the accounts vSynths and transfer them their owed balanceOfUnderlying
function settle(address account) external {
settleSynth();
IERC20(address(synth)).transfer(account, balanceUnderlying(account));
_burn(account, balanceOf(account));
}
event Settled(uint totalSupply, uint amountAfterSettled);
}
| 24,417 |
4 | // Maximum borrow rate that can ever be applied (.0005% / block) / | uint internal constant borrowRateMaxMantissa = 0.0005e16;
| uint internal constant borrowRateMaxMantissa = 0.0005e16;
| 5,844 |
35 | // Notably not cast to interface because this contract never callsfunctions on gateway. | _xLayerGateway = contractAddress;
| _xLayerGateway = contractAddress;
| 71,356 |
23 | // |/ checks if a certain address is an allowed connector/connector_address to check/ returntrue if address is allowed connector | function isConnector(address connector_) public view returns (bool) {
return connectors[connector_] == 1;
}
| function isConnector(address connector_) public view returns (bool) {
return connectors[connector_] == 1;
}
| 4,375 |
13 | // Check whether an order can be executed or not _inputToken - Address of the input token _inputAmount - uint256 of the input token amount (order amount) _data - Bytes of the order's data _auxData - Bytes of the auxiliar data used for the handlers to execute the orderreturn bool - whether the order can be executed or not / | function canExecute(
| function canExecute(
| 19,177 |
0 | // The state of the contract gets reset before each test is run, with the `setUp()` function being called each time after deployment. Think of this like a JavaScript `beforeEach` block | function setUp() public {
fooV1 = new FooV1();
admin = new ProxyAdmin();
proxy = new TransparentUpgradeableProxy(address(fooV1), address(admin), "");
fooV1 = FooV1(address(proxy));
fooV1.initialize();
require(fooV1.x() == 1, "x is not 1");
fooV1.double();
require(fooV1.x() == 2, "x is not 2");
fooV2 = new FooV2();
| function setUp() public {
fooV1 = new FooV1();
admin = new ProxyAdmin();
proxy = new TransparentUpgradeableProxy(address(fooV1), address(admin), "");
fooV1 = FooV1(address(proxy));
fooV1.initialize();
require(fooV1.x() == 1, "x is not 1");
fooV1.double();
require(fooV1.x() == 2, "x is not 2");
fooV2 = new FooV2();
| 23,747 |
20 | // Exit collateral to token version | GemJoinLike_2(gemJoin).exit(address(this), gemAmt);
| GemJoinLike_2(gemJoin).exit(address(this), gemAmt);
| 42,561 |
119 | // Transfers `tokenId` from `from` to `to`. | * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, 'ERC721: transfer of token that is not own');
require(to != address(0), 'ERC721: transfer to the zero address');
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
| * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, 'ERC721: transfer of token that is not own');
require(to != address(0), 'ERC721: transfer to the zero address');
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
| 27,108 |
108 | // accumalated REWARD_TOKENs claimed in wei | uint256 public rewardsClaimed;
| uint256 public rewardsClaimed;
| 65,558 |
5 | // 2.25% strategist fee is given | assertEqApprox(strategistRewards, strategistRewardsEarned);
| assertEqApprox(strategistRewards, strategistRewardsEarned);
| 39,147 |
120 | // uint256 _rID = rID_; uint256 _now = now; |
uint256 _aff;
uint256 _com;
uint256 _holders;
|
uint256 _aff;
uint256 _com;
uint256 _holders;
| 39,792 |
7 | // Returns a given round from the reference contract. _id of round / | function getRound(uint80 _id)
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
| function getRound(uint80 _id)
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
| 32,697 |
25 | // Records the stage data. / | function buyStageDataRecord(uint256 _rId, uint256 _sId, uint256 _promotionRatio, uint256 _amount)
stageVerify(_rId, _sId, _amount)
private
| function buyStageDataRecord(uint256 _rId, uint256 _sId, uint256 _promotionRatio, uint256 _amount)
stageVerify(_rId, _sId, _amount)
private
| 59,659 |
23 | // Although Uniswap will accept all gems, this check is a sanity check, just in case Transfer any lingering gem to specified address | if (gem.balanceOf(address(this)) > 0) {
gem.transfer(to, gem.balanceOf(address(this)));
}
| if (gem.balanceOf(address(this)) > 0) {
gem.transfer(to, gem.balanceOf(address(this)));
}
| 4,509 |
50 | // Provider interface for Revest FNFTs / | interface IOutputReceiver is IRegistryProvider, IERC165 {
function receiveRevestOutput(
uint fnftId,
address asset,
address payable owner,
uint quantity
) external;
function getCustomMetadata(uint fnftId) external view returns (string memory);
function getValue(uint fnftId) external view returns (uint);
function getAsset(uint fnftId) external view returns (address);
function getOutputDisplayValues(uint fnftId) external view returns (bytes memory);
}
| interface IOutputReceiver is IRegistryProvider, IERC165 {
function receiveRevestOutput(
uint fnftId,
address asset,
address payable owner,
uint quantity
) external;
function getCustomMetadata(uint fnftId) external view returns (string memory);
function getValue(uint fnftId) external view returns (uint);
function getAsset(uint fnftId) external view returns (address);
function getOutputDisplayValues(uint fnftId) external view returns (bytes memory);
}
| 3,186 |
9 | // Performer accepts booking | function acceptBooking(bytes12 _id) public {
Booking storage booking = bookings[_id];
require(
booking.performer == msg.sender &&
now < booking.startTime &&
isRequested(booking.status) &&
booking.deposit <= CUEToken.allowance(msg.sender, address(this))
);
CUEToken.transferFrom(msg.sender, address(this), booking.deposit);
booking.status = 'booked';
}
| function acceptBooking(bytes12 _id) public {
Booking storage booking = bookings[_id];
require(
booking.performer == msg.sender &&
now < booking.startTime &&
isRequested(booking.status) &&
booking.deposit <= CUEToken.allowance(msg.sender, address(this))
);
CUEToken.transferFrom(msg.sender, address(this), booking.deposit);
booking.status = 'booked';
}
| 26,735 |
200 | // Make a team joinable again.Callable only by owner admins. / | function makeTeamJoinable(uint256 _teamId) external onlyOwner {
require((_teamId <= numberTeams) && (_teamId > 0), "teamId invalid");
teams[_teamId].isJoinable = true;
}
| function makeTeamJoinable(uint256 _teamId) external onlyOwner {
require((_teamId <= numberTeams) && (_teamId > 0), "teamId invalid");
teams[_teamId].isJoinable = true;
}
| 28,821 |
0 | // event DebugLog(string id, bytes32 hash); | modifier hasCorrectPrefix(string memory _str) {
require(
_str.toSlice().startsWith("did:".toSlice()),
"DID must begin with did"
);
_;
}
| modifier hasCorrectPrefix(string memory _str) {
require(
_str.toSlice().startsWith("did:".toSlice()),
"DID must begin with did"
);
_;
}
| 33,343 |
4 | // Types/Contains various types used throughout the Optimism contract system. | library Types {
/// @notice OutputProposal represents a commitment to the L2 state. The timestamp is the L1
/// timestamp that the output root is posted. This timestamp is used to verify that the
/// finalization period has passed since the output root was submitted.
/// @custom:field outputRoot Hash of the L2 output.
/// @custom:field timestamp Timestamp of the L1 block that the output root was submitted in.
/// @custom:field l2BlockNumber L2 block number that the output corresponds to.
struct OutputProposal {
bytes32 outputRoot;
uint128 timestamp;
uint128 l2BlockNumber;
}
/// @notice Struct representing the elements that are hashed together to generate an output root
/// which itself represents a snapshot of the L2 state.
/// @custom:field version Version of the output root.
/// @custom:field stateRoot Root of the state trie at the block of this output.
/// @custom:field messagePasserStorageRoot Root of the message passer storage trie.
/// @custom:field latestBlockhash Hash of the block this output was generated from.
struct OutputRootProof {
bytes32 version;
bytes32 stateRoot;
bytes32 messagePasserStorageRoot;
bytes32 latestBlockhash;
}
/// @notice Struct representing a deposit transaction (L1 => L2 transaction) created by an end
/// user (as opposed to a system deposit transaction generated by the system).
/// @custom:field from Address of the sender of the transaction.
/// @custom:field to Address of the recipient of the transaction.
/// @custom:field isCreation True if the transaction is a contract creation.
/// @custom:field value Value to send to the recipient.
/// @custom:field mint Amount of ETH to mint.
/// @custom:field gasLimit Gas limit of the transaction.
/// @custom:field data Data of the transaction.
/// @custom:field l1BlockHash Hash of the block the transaction was submitted in.
/// @custom:field logIndex Index of the log in the block the transaction was submitted in.
struct UserDepositTransaction {
address from;
address to;
bool isCreation;
uint256 value;
uint256 mint;
uint64 gasLimit;
bytes data;
bytes32 l1BlockHash;
uint256 logIndex;
}
/// @notice Struct representing a withdrawal transaction.
/// @custom:field nonce Nonce of the withdrawal transaction
/// @custom:field sender Address of the sender of the transaction.
/// @custom:field target Address of the recipient of the transaction.
/// @custom:field value Value to send to the recipient.
/// @custom:field gasLimit Gas limit of the transaction.
/// @custom:field data Data of the transaction.
struct WithdrawalTransaction {
uint256 nonce;
address sender;
address target;
uint256 value;
uint256 gasLimit;
bytes data;
}
}
| library Types {
/// @notice OutputProposal represents a commitment to the L2 state. The timestamp is the L1
/// timestamp that the output root is posted. This timestamp is used to verify that the
/// finalization period has passed since the output root was submitted.
/// @custom:field outputRoot Hash of the L2 output.
/// @custom:field timestamp Timestamp of the L1 block that the output root was submitted in.
/// @custom:field l2BlockNumber L2 block number that the output corresponds to.
struct OutputProposal {
bytes32 outputRoot;
uint128 timestamp;
uint128 l2BlockNumber;
}
/// @notice Struct representing the elements that are hashed together to generate an output root
/// which itself represents a snapshot of the L2 state.
/// @custom:field version Version of the output root.
/// @custom:field stateRoot Root of the state trie at the block of this output.
/// @custom:field messagePasserStorageRoot Root of the message passer storage trie.
/// @custom:field latestBlockhash Hash of the block this output was generated from.
struct OutputRootProof {
bytes32 version;
bytes32 stateRoot;
bytes32 messagePasserStorageRoot;
bytes32 latestBlockhash;
}
/// @notice Struct representing a deposit transaction (L1 => L2 transaction) created by an end
/// user (as opposed to a system deposit transaction generated by the system).
/// @custom:field from Address of the sender of the transaction.
/// @custom:field to Address of the recipient of the transaction.
/// @custom:field isCreation True if the transaction is a contract creation.
/// @custom:field value Value to send to the recipient.
/// @custom:field mint Amount of ETH to mint.
/// @custom:field gasLimit Gas limit of the transaction.
/// @custom:field data Data of the transaction.
/// @custom:field l1BlockHash Hash of the block the transaction was submitted in.
/// @custom:field logIndex Index of the log in the block the transaction was submitted in.
struct UserDepositTransaction {
address from;
address to;
bool isCreation;
uint256 value;
uint256 mint;
uint64 gasLimit;
bytes data;
bytes32 l1BlockHash;
uint256 logIndex;
}
/// @notice Struct representing a withdrawal transaction.
/// @custom:field nonce Nonce of the withdrawal transaction
/// @custom:field sender Address of the sender of the transaction.
/// @custom:field target Address of the recipient of the transaction.
/// @custom:field value Value to send to the recipient.
/// @custom:field gasLimit Gas limit of the transaction.
/// @custom:field data Data of the transaction.
struct WithdrawalTransaction {
uint256 nonce;
address sender;
address target;
uint256 value;
uint256 gasLimit;
bytes data;
}
}
| 11,013 |
1 | // Mint max 20 | function mintPP(uint _count) public payable {
require(isActive, "Paused");
require(_count <= 20, "Exceeds 20");
require(totalSupply() < maxPineapples, "Sale ended");
require(totalSupply() + _count <= maxPineapples, "Max limit");
require(msg.value >= price(_count), "Value below price");
for(uint i = 0; i < _count; i++){
uint mintIndex = totalSupply();
if (totalSupply() < maxPineapples) {
_safeMint(msg.sender, mintIndex);
}
}
}
| function mintPP(uint _count) public payable {
require(isActive, "Paused");
require(_count <= 20, "Exceeds 20");
require(totalSupply() < maxPineapples, "Sale ended");
require(totalSupply() + _count <= maxPineapples, "Max limit");
require(msg.value >= price(_count), "Value below price");
for(uint i = 0; i < _count; i++){
uint mintIndex = totalSupply();
if (totalSupply() < maxPineapples) {
_safeMint(msg.sender, mintIndex);
}
}
}
| 9,482 |
119 | // The CTO TOKEN! | CallistoToken public CTO;
| CallistoToken public CTO;
| 14,577 |
178 | // Returns true if the module is ever registered. | function isModuleRegistered(address module) external view returns (bool);
| function isModuleRegistered(address module) external view returns (bool);
| 3,640 |
29 | // Calculate the refund this user will receive | assert(_contributerAddress.send(totalRefund) == true);
| assert(_contributerAddress.send(totalRefund) == true);
| 41,088 |
27 | // Emit event, set new owner, reset timestamp | _setOwner(s._proposed);
| _setOwner(s._proposed);
| 24,077 |
40 | // https:eips.ethereum.org/EIPS/eip-721 tokenURI/ CosmoBugs contract Extends ERC721 Non-Fungible Token Standard basic implementation / | contract CosmoBugs is Ownable, CosmoBugsERC721, ICosmoBugs {
using SafeMath for uint256;
// This is the provenance record of all CosmoBugs artwork in existence
uint256 public constant COSMO_PRICE = 1_000_000_000_000e18;
uint256 public constant CMP_PRICE = 5_000e18;
uint256 public constant NAME_CHANGE_PRICE = 1_830e18;
uint256 public constant SECONDS_IN_A_DAY = 86400;
uint256 public constant MAX_SUPPLY = 16410;
string public constant PROVENANCE = "0a03c03e36aa3757228e9d185f794f25953c643110c8bb3eb5ef892d062b07ab";
uint256 public constant SALE_START_TIMESTAMP = 1623682800; // "2021-06-14T15:00:00.000Z"
// Time after which CosmoBugs are randomized and allotted
uint256 public constant REVEAL_TIMESTAMP = 1624892400; // "2021-06-28T15:00:00.000Z"
uint256 public startingIndexBlock;
uint256 public startingIndex;
// tokens
address public nftPower;
address public constant tokenCosmo = 0x27cd7375478F189bdcF55616b088BE03d9c4339c;
address public constant tokenCmp = 0xB9FDc13F7f747bAEdCc356e9Da13Ab883fFa719B;
address public proxyRegistryAddress;
string private _contractURI;
// Mapping from token ID to name
mapping(uint256 => string) private _tokenName;
// Mapping if certain name string has already been reserved
mapping(string => bool) private _nameReserved;
// Mapping from token ID to whether the CosmoMask was minted before reveal
mapping(uint256 => bool) private _mintedBeforeReveal;
event NameChange(uint256 indexed tokenId, string newName);
event SetStartingIndexBlock(uint256 startingIndexBlock);
event SetStartingIndex(uint256 startingIndex);
constructor(address _nftPowerAddress, address _proxyRegistryAddress) public CosmoBugsERC721("CosmoBugs", "COSBUG") {
nftPower = _nftPowerAddress;
proxyRegistryAddress = _proxyRegistryAddress;
_setURL("https://cosmobugs.com/");
_setBaseURI("https://cosmobugs.com/metadata/");
_contractURI = "https://cosmobugs.com/metadata/contract.json";
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
/**
* @dev Returns name of the CosmoMask at index.
*/
function tokenNameByIndex(uint256 index) public view returns (string memory) {
return _tokenName[index];
}
/**
* @dev Returns if the name has been reserved.
*/
function isNameReserved(string memory nameString) public view returns (bool) {
return _nameReserved[toLower(nameString)];
}
/**
* @dev Returns if the CosmoMask has been minted before reveal phase
*/
function isMintedBeforeReveal(uint256 index) public view override returns (bool) {
return _mintedBeforeReveal[index];
}
/**
* @dev Gets current CosmoMask Price
*/
function getPrice() public view returns (uint256) {
require(block.timestamp >= SALE_START_TIMESTAMP, "CosmoBugs: sale has not started");
require(totalSupply() < MAX_SUPPLY, "CosmoBugs: sale has already ended");
uint256 currentSupply = totalSupply();
if (currentSupply >= 16409) {
return 2_000_000e18;
} else if (currentSupply >= 16407) {
return 200_000e18;
} else if (currentSupply >= 16400) {
return 20_000e18;
} else if (currentSupply >= 16381) {
return 2_000e18;
} else if (currentSupply >= 16000) {
return 200e18;
} else if (currentSupply >= 15000) {
return 34e18;
} else if (currentSupply >= 11000) {
return 18e18;
} else if (currentSupply >= 7000) {
return 10e18;
} else if (currentSupply >= 3000) {
return 6e18;
} else {
return 2e18;
}
}
/**
* @dev Mints CosmoBugs
*/
function mint(uint256 numberOfMasks) public payable {
require(totalSupply() < MAX_SUPPLY, "CosmoBugs: sale has already ended");
require(numberOfMasks > 0, "CosmoBugs: numberOfMasks cannot be 0");
require(numberOfMasks <= 20, "CosmoBugs: You may not buy more than 20 CosmoBugs at once");
require(totalSupply().add(numberOfMasks) <= MAX_SUPPLY, "CosmoBugs: Exceeds MAX_SUPPLY");
require(getPrice().mul(numberOfMasks) == msg.value, "CosmoBugs: Ether value sent is not correct");
for (uint256 i = 0; i < numberOfMasks; i++) {
uint256 mintIndex = totalSupply();
if (block.timestamp < REVEAL_TIMESTAMP) {
_mintedBeforeReveal[mintIndex] = true;
}
_safeMint(msg.sender, mintIndex);
}
if (startingIndex == 0 && (totalSupply() == MAX_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
_setStartingIndex();
}
}
function mintByCosmo(uint256 numberOfMasks) public {
require(totalSupply() < MAX_SUPPLY, "CosmoBugs: sale has already ended");
require(numberOfMasks > 0, "CosmoBugs: numberOfMasks cannot be 0");
require(numberOfMasks <= 20, "CosmoBugs: You may not buy more than 20 CosmoBugs at once");
require(totalSupply().add(numberOfMasks) <= (MAX_SUPPLY - 10), "CosmoBugs: The last 10 masks can only be purchased for ETH");
uint256 purchaseAmount = COSMO_PRICE.mul(numberOfMasks);
require(
IERC20BurnTransfer(tokenCosmo).transferFrom(msg.sender, address(this), purchaseAmount),
"CosmoBugs: Transfer COSMO amount exceeds allowance"
);
for (uint256 i = 0; i < numberOfMasks; i++) {
uint256 mintIndex = totalSupply();
if (block.timestamp < REVEAL_TIMESTAMP) {
_mintedBeforeReveal[mintIndex] = true;
}
_safeMint(msg.sender, mintIndex);
}
if (startingIndex == 0 && (totalSupply() == MAX_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
_setStartingIndex();
}
IERC20BurnTransfer(tokenCosmo).burn(purchaseAmount);
}
function mintByCmp(uint256 numberOfMasks) public {
require(totalSupply() < MAX_SUPPLY, "CosmoBugs: sale has already ended");
require(numberOfMasks > 0, "CosmoBugs: numberOfMasks cannot be 0");
require(numberOfMasks <= 20, "CosmoBugs: You may not buy more than 20 CosmoBugs at once");
require(totalSupply().add(numberOfMasks) <= (MAX_SUPPLY - 10), "CosmoBugs: The last 10 masks can only be purchased for ETH");
uint256 purchaseAmount = CMP_PRICE.mul(numberOfMasks);
require(
IERC20BurnTransfer(tokenCmp).transferFrom(msg.sender, address(this), purchaseAmount),
"CosmoBugs: Transfer CMP amount exceeds allowance"
);
for (uint256 i = 0; i < numberOfMasks; i++) {
uint256 mintIndex = totalSupply();
if (block.timestamp < REVEAL_TIMESTAMP) {
_mintedBeforeReveal[mintIndex] = true;
}
_safeMint(msg.sender, mintIndex);
}
if (startingIndex == 0 && (totalSupply() == MAX_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
_setStartingIndex();
}
IERC20BurnTransfer(tokenCmp).burn(purchaseAmount);
}
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* @dev Finalize starting index
*/
function finalizeStartingIndex() public {
require(startingIndex == 0, "CosmoBugs: starting index is already set");
require(block.timestamp >= REVEAL_TIMESTAMP, "CosmoBugs: Too early");
_setStartingIndex();
}
function _setStartingIndex() internal {
startingIndexBlock = block.number - 1;
emit SetStartingIndexBlock(startingIndexBlock);
startingIndex = uint256(blockhash(startingIndexBlock)) % 16400;
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
emit SetStartingIndex(startingIndex);
}
/**
* @dev 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);
}
/**
* @dev Withdraw ether from this contract (Callable by owner)
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Reserves the name if isReserve is set to true, de-reserves if set to false
*/
function toggleReserveName(string memory str, bool isReserve) internal {
_nameReserved[toLower(str)] = isReserve;
}
/**
* @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space)
*/
function validateName(string memory str) public pure returns (bool) {
bytes memory b = bytes(str);
if (b.length < 1)
return false;
// Cannot be longer than 25 characters
if (b.length > 25)
return false;
// Leading space
if (b[0] == 0x20)
return false;
// Trailing space
if (b[b.length - 1] == 0x20)
return false;
bytes1 lastChar = b[0];
for (uint256 i; i < b.length; i++) {
bytes1 char = b[i];
// Cannot contain continous spaces
if (char == 0x20 && lastChar == 0x20)
return false;
if (
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x20) //space
)
return false;
lastChar = char;
}
return true;
}
/**
* @dev Converts the string to lowercase
*/
function toLower(string memory str) public pure returns (string memory) {
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint256 i = 0; i < bStr.length; i++) {
// Uppercase character
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90))
bLower[i] = bytes1(uint8(bStr[i]) + 32);
else
bLower[i] = bStr[i];
}
return string(bLower);
}
function setBaseURI(string memory baseURI_) public onlyOwner {
_setBaseURI(baseURI_);
}
function setContractURI(string memory contractURI_) public onlyOwner {
_contractURI = contractURI_;
}
function setURL(string memory newUrl) public onlyOwner {
_setURL(newUrl);
}
}
| contract CosmoBugs is Ownable, CosmoBugsERC721, ICosmoBugs {
using SafeMath for uint256;
// This is the provenance record of all CosmoBugs artwork in existence
uint256 public constant COSMO_PRICE = 1_000_000_000_000e18;
uint256 public constant CMP_PRICE = 5_000e18;
uint256 public constant NAME_CHANGE_PRICE = 1_830e18;
uint256 public constant SECONDS_IN_A_DAY = 86400;
uint256 public constant MAX_SUPPLY = 16410;
string public constant PROVENANCE = "0a03c03e36aa3757228e9d185f794f25953c643110c8bb3eb5ef892d062b07ab";
uint256 public constant SALE_START_TIMESTAMP = 1623682800; // "2021-06-14T15:00:00.000Z"
// Time after which CosmoBugs are randomized and allotted
uint256 public constant REVEAL_TIMESTAMP = 1624892400; // "2021-06-28T15:00:00.000Z"
uint256 public startingIndexBlock;
uint256 public startingIndex;
// tokens
address public nftPower;
address public constant tokenCosmo = 0x27cd7375478F189bdcF55616b088BE03d9c4339c;
address public constant tokenCmp = 0xB9FDc13F7f747bAEdCc356e9Da13Ab883fFa719B;
address public proxyRegistryAddress;
string private _contractURI;
// Mapping from token ID to name
mapping(uint256 => string) private _tokenName;
// Mapping if certain name string has already been reserved
mapping(string => bool) private _nameReserved;
// Mapping from token ID to whether the CosmoMask was minted before reveal
mapping(uint256 => bool) private _mintedBeforeReveal;
event NameChange(uint256 indexed tokenId, string newName);
event SetStartingIndexBlock(uint256 startingIndexBlock);
event SetStartingIndex(uint256 startingIndex);
constructor(address _nftPowerAddress, address _proxyRegistryAddress) public CosmoBugsERC721("CosmoBugs", "COSBUG") {
nftPower = _nftPowerAddress;
proxyRegistryAddress = _proxyRegistryAddress;
_setURL("https://cosmobugs.com/");
_setBaseURI("https://cosmobugs.com/metadata/");
_contractURI = "https://cosmobugs.com/metadata/contract.json";
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
/**
* @dev Returns name of the CosmoMask at index.
*/
function tokenNameByIndex(uint256 index) public view returns (string memory) {
return _tokenName[index];
}
/**
* @dev Returns if the name has been reserved.
*/
function isNameReserved(string memory nameString) public view returns (bool) {
return _nameReserved[toLower(nameString)];
}
/**
* @dev Returns if the CosmoMask has been minted before reveal phase
*/
function isMintedBeforeReveal(uint256 index) public view override returns (bool) {
return _mintedBeforeReveal[index];
}
/**
* @dev Gets current CosmoMask Price
*/
function getPrice() public view returns (uint256) {
require(block.timestamp >= SALE_START_TIMESTAMP, "CosmoBugs: sale has not started");
require(totalSupply() < MAX_SUPPLY, "CosmoBugs: sale has already ended");
uint256 currentSupply = totalSupply();
if (currentSupply >= 16409) {
return 2_000_000e18;
} else if (currentSupply >= 16407) {
return 200_000e18;
} else if (currentSupply >= 16400) {
return 20_000e18;
} else if (currentSupply >= 16381) {
return 2_000e18;
} else if (currentSupply >= 16000) {
return 200e18;
} else if (currentSupply >= 15000) {
return 34e18;
} else if (currentSupply >= 11000) {
return 18e18;
} else if (currentSupply >= 7000) {
return 10e18;
} else if (currentSupply >= 3000) {
return 6e18;
} else {
return 2e18;
}
}
/**
* @dev Mints CosmoBugs
*/
function mint(uint256 numberOfMasks) public payable {
require(totalSupply() < MAX_SUPPLY, "CosmoBugs: sale has already ended");
require(numberOfMasks > 0, "CosmoBugs: numberOfMasks cannot be 0");
require(numberOfMasks <= 20, "CosmoBugs: You may not buy more than 20 CosmoBugs at once");
require(totalSupply().add(numberOfMasks) <= MAX_SUPPLY, "CosmoBugs: Exceeds MAX_SUPPLY");
require(getPrice().mul(numberOfMasks) == msg.value, "CosmoBugs: Ether value sent is not correct");
for (uint256 i = 0; i < numberOfMasks; i++) {
uint256 mintIndex = totalSupply();
if (block.timestamp < REVEAL_TIMESTAMP) {
_mintedBeforeReveal[mintIndex] = true;
}
_safeMint(msg.sender, mintIndex);
}
if (startingIndex == 0 && (totalSupply() == MAX_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
_setStartingIndex();
}
}
function mintByCosmo(uint256 numberOfMasks) public {
require(totalSupply() < MAX_SUPPLY, "CosmoBugs: sale has already ended");
require(numberOfMasks > 0, "CosmoBugs: numberOfMasks cannot be 0");
require(numberOfMasks <= 20, "CosmoBugs: You may not buy more than 20 CosmoBugs at once");
require(totalSupply().add(numberOfMasks) <= (MAX_SUPPLY - 10), "CosmoBugs: The last 10 masks can only be purchased for ETH");
uint256 purchaseAmount = COSMO_PRICE.mul(numberOfMasks);
require(
IERC20BurnTransfer(tokenCosmo).transferFrom(msg.sender, address(this), purchaseAmount),
"CosmoBugs: Transfer COSMO amount exceeds allowance"
);
for (uint256 i = 0; i < numberOfMasks; i++) {
uint256 mintIndex = totalSupply();
if (block.timestamp < REVEAL_TIMESTAMP) {
_mintedBeforeReveal[mintIndex] = true;
}
_safeMint(msg.sender, mintIndex);
}
if (startingIndex == 0 && (totalSupply() == MAX_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
_setStartingIndex();
}
IERC20BurnTransfer(tokenCosmo).burn(purchaseAmount);
}
function mintByCmp(uint256 numberOfMasks) public {
require(totalSupply() < MAX_SUPPLY, "CosmoBugs: sale has already ended");
require(numberOfMasks > 0, "CosmoBugs: numberOfMasks cannot be 0");
require(numberOfMasks <= 20, "CosmoBugs: You may not buy more than 20 CosmoBugs at once");
require(totalSupply().add(numberOfMasks) <= (MAX_SUPPLY - 10), "CosmoBugs: The last 10 masks can only be purchased for ETH");
uint256 purchaseAmount = CMP_PRICE.mul(numberOfMasks);
require(
IERC20BurnTransfer(tokenCmp).transferFrom(msg.sender, address(this), purchaseAmount),
"CosmoBugs: Transfer CMP amount exceeds allowance"
);
for (uint256 i = 0; i < numberOfMasks; i++) {
uint256 mintIndex = totalSupply();
if (block.timestamp < REVEAL_TIMESTAMP) {
_mintedBeforeReveal[mintIndex] = true;
}
_safeMint(msg.sender, mintIndex);
}
if (startingIndex == 0 && (totalSupply() == MAX_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
_setStartingIndex();
}
IERC20BurnTransfer(tokenCmp).burn(purchaseAmount);
}
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* @dev Finalize starting index
*/
function finalizeStartingIndex() public {
require(startingIndex == 0, "CosmoBugs: starting index is already set");
require(block.timestamp >= REVEAL_TIMESTAMP, "CosmoBugs: Too early");
_setStartingIndex();
}
function _setStartingIndex() internal {
startingIndexBlock = block.number - 1;
emit SetStartingIndexBlock(startingIndexBlock);
startingIndex = uint256(blockhash(startingIndexBlock)) % 16400;
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
emit SetStartingIndex(startingIndex);
}
/**
* @dev 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);
}
/**
* @dev Withdraw ether from this contract (Callable by owner)
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Reserves the name if isReserve is set to true, de-reserves if set to false
*/
function toggleReserveName(string memory str, bool isReserve) internal {
_nameReserved[toLower(str)] = isReserve;
}
/**
* @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space)
*/
function validateName(string memory str) public pure returns (bool) {
bytes memory b = bytes(str);
if (b.length < 1)
return false;
// Cannot be longer than 25 characters
if (b.length > 25)
return false;
// Leading space
if (b[0] == 0x20)
return false;
// Trailing space
if (b[b.length - 1] == 0x20)
return false;
bytes1 lastChar = b[0];
for (uint256 i; i < b.length; i++) {
bytes1 char = b[i];
// Cannot contain continous spaces
if (char == 0x20 && lastChar == 0x20)
return false;
if (
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x20) //space
)
return false;
lastChar = char;
}
return true;
}
/**
* @dev Converts the string to lowercase
*/
function toLower(string memory str) public pure returns (string memory) {
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint256 i = 0; i < bStr.length; i++) {
// Uppercase character
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90))
bLower[i] = bytes1(uint8(bStr[i]) + 32);
else
bLower[i] = bStr[i];
}
return string(bLower);
}
function setBaseURI(string memory baseURI_) public onlyOwner {
_setBaseURI(baseURI_);
}
function setContractURI(string memory contractURI_) public onlyOwner {
_contractURI = contractURI_;
}
function setURL(string memory newUrl) public onlyOwner {
_setURL(newUrl);
}
}
| 64,105 |
4 | // Destroys `amount` tokens from `account`, deducting from the caller'sallowance. / | function burnFrom(address account, uint256 amount) external virtual {
_burnFrom(account, amount);
}
| function burnFrom(address account, uint256 amount) external virtual {
_burnFrom(account, amount);
}
| 15,681 |
10 | // Emits a {Released} event. / | function releaseToBalance(address token) public {
uint256 releasable = vestedAmount(token, uint64(block.timestamp)) - released(token);
require(releasable > 0, "Zero to release");
unlocks[token].released += releasable;
uint256 totalUsers = _tokenIdCounter.current();
uint256 toRelease = releasable / totalUsers;
for (uint256 i; i <= totalUsers; i++) {
if (unlocks[token].balances.length > i) {
| function releaseToBalance(address token) public {
uint256 releasable = vestedAmount(token, uint64(block.timestamp)) - released(token);
require(releasable > 0, "Zero to release");
unlocks[token].released += releasable;
uint256 totalUsers = _tokenIdCounter.current();
uint256 toRelease = releasable / totalUsers;
for (uint256 i; i <= totalUsers; i++) {
if (unlocks[token].balances.length > i) {
| 32,541 |
516 | // Denominator: point^(trace_length / 128) - 1. val = denominator_invs[14]. | val := mulmod(val, mload(0x52a0), PRIME)
| val := mulmod(val, mload(0x52a0), PRIME)
| 31,525 |
90 | // Store the Panic error signature. | mstore(0, Panic_error_selector)
| mstore(0, Panic_error_selector)
| 16,628 |
12 | // See {IERC1155MetadataURI-uri}. This implementation returns the same URI for all token types. It relieson the token type ID substitution mechanism Clients calling this function must replace the `\{id\}` substring with theactual token type ID. / | function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
| function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
| 2,893 |
48 | // Return the kill factor for the worker + BaseToken debt, using 1e4 as denom. Revert on non-worker. | function killFactor(address worker, uint256 debt) external view returns (uint256);
| function killFactor(address worker, uint256 debt) external view returns (uint256);
| 11,174 |
106 | // Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. Tokens start existing when they are minted (`_mint`),and stop existing when they are burned (`_burn`). / | function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
| function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
| 69,809 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.