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
|
|---|---|---|---|---|
76
|
// Determine the amount of coverage left for a specific protocol. _protocol The address of the protocol we're determining coverage left for./
|
returns (uint256) {
(/* uint256 shield */, uint256 allowed) = _checkBuyerAllowed(_protocol);
return allowed;
}
|
returns (uint256) {
(/* uint256 shield */, uint256 allowed) = _checkBuyerAllowed(_protocol);
return allowed;
}
| 26,730
|
25
|
// Define Types.Order
|
sellOrder.nonce = airswapNonce++;
sellOrder.expiry = block.timestamp + 1 days;
sellOrder.signer = signer;
sellOrder.sender = sender;
ISwap(exchange).swap(sellOrder);
|
sellOrder.nonce = airswapNonce++;
sellOrder.expiry = block.timestamp + 1 days;
sellOrder.signer = signer;
sellOrder.sender = sender;
ISwap(exchange).swap(sellOrder);
| 13,911
|
7
|
// get a claim corresponding to a creator contract and instanceId creatorContractAddressthe address of the creator contract instanceIdthe claim instanceId for the creator contractreturnthe claim object /
|
function getClaim(address creatorContractAddress, uint256 instanceId) external view returns(Claim memory);
|
function getClaim(address creatorContractAddress, uint256 instanceId) external view returns(Claim memory);
| 23,099
|
52
|
// get balance of caller
|
uint256 bal = _balances[msg.sender];
require(bal >= nHoldings && bal > 0, "Zero Holdings");
|
uint256 bal = _balances[msg.sender];
require(bal >= nHoldings && bal > 0, "Zero Holdings");
| 29,614
|
156
|
// returns the address of the LendingPoolConfigurator proxy return the lending pool configurator proxy address/
|
function getLendingPoolConfigurator() public view returns (address) {
return getAddress(LENDING_POOL_CONFIGURATOR);
}
|
function getLendingPoolConfigurator() public view returns (address) {
return getAddress(LENDING_POOL_CONFIGURATOR);
}
| 34,813
|
162
|
// Issue a new NFT of the specified kind. that will throw if kind has reached its maximum or is invalid _beneficiary - owner of the token _optionId - option id _issuedId - issued id /
|
function issueToken(address _beneficiary, uint256 _optionId, uint256 _issuedId) external onlyAllowed {
_issueToken(_beneficiary, _optionId, _issuedId);
}
|
function issueToken(address _beneficiary, uint256 _optionId, uint256 _issuedId) external onlyAllowed {
_issueToken(_beneficiary, _optionId, _issuedId);
}
| 57,640
|
18
|
// src Pointer to source dest Pointer to destination len Amount of memory to copy from the source /
|
function copy(
uint256 src,
uint256 dest,
uint256 len
|
function copy(
uint256 src,
uint256 dest,
uint256 len
| 36,729
|
75
|
// Add new totals for new protocol/cover amounts. _newProtocols Protocols that are being borrowed for. _newCoverAmounts Cover amounts (in Wei) that are being borrowed./
|
function _addNewTotals(address[] memory _newProtocols, uint256[] memory _newCoverAmounts) internal {
for (uint256 i = 0; i < _newProtocols.length; i++) {
(uint256 shield, uint256 allowed) = _checkBuyerAllowed(_newProtocols[i]);
require(allowed >= _newCoverAmounts[i], "Exceeds allowed cover amount.");
totalUsedCover[_newProtocols[i]] = totalUsedCover[_newProtocols[i]].add(_newCoverAmounts[i]);
if (shield == 1) {
arShieldCover[_newProtocols[i]] = arShieldCover[_newProtocols[i]].add(_newCoverAmounts[i]);
} else if (shield == 2) {
arShieldPlusCover[_newProtocols[i]] = arShieldPlusCover[_newProtocols[i]].add(_newCoverAmounts[i]);
} else {
coreCover[_newProtocols[i]] = coreCover[_newProtocols[i]].add(_newCoverAmounts[i]);
}
}
}
|
function _addNewTotals(address[] memory _newProtocols, uint256[] memory _newCoverAmounts) internal {
for (uint256 i = 0; i < _newProtocols.length; i++) {
(uint256 shield, uint256 allowed) = _checkBuyerAllowed(_newProtocols[i]);
require(allowed >= _newCoverAmounts[i], "Exceeds allowed cover amount.");
totalUsedCover[_newProtocols[i]] = totalUsedCover[_newProtocols[i]].add(_newCoverAmounts[i]);
if (shield == 1) {
arShieldCover[_newProtocols[i]] = arShieldCover[_newProtocols[i]].add(_newCoverAmounts[i]);
} else if (shield == 2) {
arShieldPlusCover[_newProtocols[i]] = arShieldPlusCover[_newProtocols[i]].add(_newCoverAmounts[i]);
} else {
coreCover[_newProtocols[i]] = coreCover[_newProtocols[i]].add(_newCoverAmounts[i]);
}
}
}
| 26,729
|
203
|
// verify the provided _merkleProof
|
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Not part of the Free Mint whitelist.");
|
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Not part of the Free Mint whitelist.");
| 26,062
|
410
|
// If 'createdAt' is zero, then it's non-existent for us
|
require(metadata.createdAt > 0, "PB-1");
require(metadata.opType == opHandle.opType, "PB-2");
return metadata;
|
require(metadata.createdAt > 0, "PB-1");
require(metadata.opType == opHandle.opType, "PB-2");
return metadata;
| 67,425
|
44
|
// SafeMath.sub will throw if there is not enough balance.
|
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
|
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
| 21,178
|
54
|
// See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is notrequired by the EIP. See the note at the beginning of {ERC20}. Requirements: - `sender` and `recipient` cannot be the zero address.- `sender` must have a balance of at least `amount`.- the caller must have allowance for ``sender``'s tokens of at least`amount`. /
|
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
|
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
| 2,532
|
219
|
// Perform the transfer: if there is a problem an exception will be thrown in this call.
|
_transferByProxy(messageSender, to, value);
return true;
|
_transferByProxy(messageSender, to, value);
return true;
| 23,627
|
1
|
// target/parent(one to one): ((source/child token address + id) -> (target/parent token address+ target/parent id))
|
mapping(address => mapping(uint256 => NFT)) _target;
|
mapping(address => mapping(uint256 => NFT)) _target;
| 23,773
|
3
|
// BK NOTE - mload(p) - mem[p..(p+32)). Load word from memory. BK Ok - Len will be 0x48 (72), the number of bytes in clone
|
let len := mload(clone)
|
let len := mload(clone)
| 31,998
|
55
|
// interface contract for multisig proxy contracts; see below for docs.
|
contract multisig {
// EVENTS
// logged events:
// Funds has arrived into the wallet (record how much).
event Deposit(address _from, uint value);
// Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going).
event SingleTransact(address owner, uint value, address to, bytes data, address created);
// Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going).
event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created);
// Confirmation still needed for a transaction.
event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data);
// FUNCTIONS
// TODO: document
function changeOwner(address _from, address _to) external;
function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash);
function confirm(bytes32 _h) returns (bool o_success);
}
|
contract multisig {
// EVENTS
// logged events:
// Funds has arrived into the wallet (record how much).
event Deposit(address _from, uint value);
// Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going).
event SingleTransact(address owner, uint value, address to, bytes data, address created);
// Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going).
event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created);
// Confirmation still needed for a transaction.
event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data);
// FUNCTIONS
// TODO: document
function changeOwner(address _from, address _to) external;
function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash);
function confirm(bytes32 _h) returns (bool o_success);
}
| 40,782
|
245
|
// When a payment is canceled, never is assigned to a project.
|
uint64 idOldPledge = _findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
p.token,
PledgeState.Pledged
);
|
uint64 idOldPledge = _findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
p.token,
PledgeState.Pledged
);
| 2,542
|
33
|
// The timestamp of last changed for user's stake.
|
mapping(address=>uint256) _stakeLastChangeTime;
uint256 private _totalStakeLastChangeTime;
address private _tempStakeAddress;
uint256 _weightDays = 30 days;
bool _mutex = false;
|
mapping(address=>uint256) _stakeLastChangeTime;
uint256 private _totalStakeLastChangeTime;
address private _tempStakeAddress;
uint256 _weightDays = 30 days;
bool _mutex = false;
| 27,528
|
8
|
// Emitted when the time buffer is updated/timeBuffer The new time buffer
|
event TimeBufferUpdated(uint256 timeBuffer);
|
event TimeBufferUpdated(uint256 timeBuffer);
| 29,971
|
1
|
// require(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1) && LOGIC_SLOT==bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)this require is simply against human error, can be removed if you know what you are doing&& NEXT_LOGIC_SLOT == bytes32(uint256(keccak256('eip1984.proxy.nextLogic')) - 1) && NEXT_LOGIC_BLOCK_SLOT == bytes32(uint256(keccak256('eip1984.proxy.nextLogicBlock')) - 1)&& PROPOSE_BLOCK_SLOT == bytes32(uint256(keccak256('eip1984.proxy.proposeBlock')) - 1)/ && DEADLINE_SLOT == bytes32(uint256(keccak256('eip1984.proxy.deadline')) - 1)/&& TRUST_MINIMIZED_SLOT == bytes32(uint256(keccak256('eip1984.proxy.trustMinimized')) - 1));
|
_setAdmin(msg.sender);
|
_setAdmin(msg.sender);
| 68,633
|
98
|
// Change the signer used to validate payloads/newSigner The new address that will be signing rewards payloads
|
function setSigner(address newSigner) external;
|
function setSigner(address newSigner) external;
| 28,338
|
73
|
// makes migration possible for uniswap V3 (only Owner).---------------------------------------------------------- _unistakeMigrationContract--> the migration contract address.-------------------------------------------------------------------------returns whether successfully migrated or not. /
|
function allowMigration(address _unistakeMigrationContract) external onlyOwner returns (bool) {
require(_unistakeMigrationContract != address(0x0), "cannot migrate to a null address");
migrationContract = _unistakeMigrationContract;
emit VersionMigrated(msg.sender, now, migrationContract);
return true;
}
|
function allowMigration(address _unistakeMigrationContract) external onlyOwner returns (bool) {
require(_unistakeMigrationContract != address(0x0), "cannot migrate to a null address");
migrationContract = _unistakeMigrationContract;
emit VersionMigrated(msg.sender, now, migrationContract);
return true;
}
| 22,276
|
23
|
// Issue a new amount of tokens. these tokens are deposited into the owner addressamount Number of tokens to be issued
|
function issue(uint amount) public onlyOwner returns (bool) {
balances[owner] = balances[owner].add(amount);
totalSupply = totalSupply.add(amount);
emit Issue(amount);
emit Transfer(address(0), owner, amount);
return true;
}
|
function issue(uint amount) public onlyOwner returns (bool) {
balances[owner] = balances[owner].add(amount);
totalSupply = totalSupply.add(amount);
emit Issue(amount);
emit Transfer(address(0), owner, amount);
return true;
}
| 30,632
|
32
|
// Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
|
if (sqrtRatioX96 <= type(uint128).max) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
quoteAmount_ = baseToken < quoteToken
? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
: FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
} else {
|
if (sqrtRatioX96 <= type(uint128).max) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
quoteAmount_ = baseToken < quoteToken
? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
: FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
} else {
| 6,501
|
1
|
// ..and the index in the lower 128
|
uint256 constant INDEX_MASK = type(uint128).max;
|
uint256 constant INDEX_MASK = type(uint128).max;
| 31,890
|
33
|
// update the balance on the account
|
AccountsByOwner[oldOwner].Balance += msg.value;
AccountsByOwner[oldOwner].TotalSold += msg.value;
|
AccountsByOwner[oldOwner].Balance += msg.value;
AccountsByOwner[oldOwner].TotalSold += msg.value;
| 1,104
|
27
|
// token == token-usdt
|
mapping(address => address) public feedsManager;
|
mapping(address => address) public feedsManager;
| 23,713
|
139
|
// Checks if currently purchased amount does not reach cap per wallet. purchaseAmount DHV tokens currently purchased /
|
function _checkCapReached(uint256 purchaseAmount) private view {
if (_isPreSale()) {
require(purchaseAmount.add(purchased[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded");
}
else {
require(purchaseAmount.add(purchasedPublic[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded");
}
}
|
function _checkCapReached(uint256 purchaseAmount) private view {
if (_isPreSale()) {
require(purchaseAmount.add(purchased[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded");
}
else {
require(purchaseAmount.add(purchasedPublic[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded");
}
}
| 4,184
|
1
|
// Initializes `AccountImplementation` contract registry_ registry address /
|
function initialize(
address registry_
)
external
onlyInitializer
{
registry = registry_;
}
|
function initialize(
address registry_
)
external
onlyInitializer
{
registry = registry_;
}
| 32,461
|
4
|
// 복권 당첨금 비율 /
|
uint32 public constant TOKEN_DRAWER_REWARD_RATIO = 80;
uint32 public constant DRAWER_1REWARD_RATIO = 70;
uint32 public constant DRAWER_2REWARD_RATIO = 15;
uint32 public constant DRAWER_3REWARD_RATIO = 15;
|
uint32 public constant TOKEN_DRAWER_REWARD_RATIO = 80;
uint32 public constant DRAWER_1REWARD_RATIO = 70;
uint32 public constant DRAWER_2REWARD_RATIO = 15;
uint32 public constant DRAWER_3REWARD_RATIO = 15;
| 47,704
|
117
|
// SushiToken with Governance.
|
contract BoneToken is ERC20("BoneToken", "BONE"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SUSHI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce");
require(now <= expiry, "SUSHI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSHIs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
contract BoneToken is ERC20("BoneToken", "BONE"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SUSHI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce");
require(now <= expiry, "SUSHI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSHIs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
| 34,141
|
1
|
// tokenAddress => amount
|
mapping(address => uint256) treasury;
address wbnb; // obsolete
address exchangeTreasury; // obsolete
uint16 securityMarginP; // 1e4
|
mapping(address => uint256) treasury;
address wbnb; // obsolete
address exchangeTreasury; // obsolete
uint16 securityMarginP; // 1e4
| 21,503
|
139
|
// buyTwaAndAddLiquidityToUniswapV2(ethAmountForLP);
|
totalEthSwap = totalEthSwap.add(ethAmountForLP);
|
totalEthSwap = totalEthSwap.add(ethAmountForLP);
| 34,484
|
0
|
// Get the exchange rate of QiTokens => underlying/https:compound.finance/docs/ctokensexchange-rate/qiToken The qiToken address rate to get/ return The exchange rate scaled by 1e18
|
function getExchangeRate(address qiToken) internal view returns (uint256) {
return IQiToken(qiToken).exchangeRateStored();
}
|
function getExchangeRate(address qiToken) internal view returns (uint256) {
return IQiToken(qiToken).exchangeRateStored();
}
| 5,651
|
34
|
// Is in punishment period
|
function isUnderPunishment(uint _id) private view returns (bool) {
if (!hasPrize(_id)) {
return false;
}
if (!isExpired(_id)) {
return false;
}
return !isPunishmentOver(_id);
}
|
function isUnderPunishment(uint _id) private view returns (bool) {
if (!hasPrize(_id)) {
return false;
}
if (!isExpired(_id)) {
return false;
}
return !isPunishmentOver(_id);
}
| 30,112
|
15
|
// SmartWalletWhitelist/Curve Finance and adapted by Stake DAO Core Team (https:etherscan.io/address/0xca719728ef172d0961768581fdf35cb116e0b7a4code)/Provides functions to check whether a wallet has been verified or not to own veSDT
|
contract SmartWalletWhitelist {
/// @notice Mapping between addresses and whether they are whitelisted or not
mapping(address => bool) public wallets;
/// @notice Admin address of the contract
address public admin;
/// @notice Future admin address of the contract
//solhint-disable-next-line
address public future_admin;
/// @notice Contract which works as this contract and that can whitelist addresses
address public checker;
/// @notice Future address to become checker
//solhint-disable-next-line
address public future_checker;
event ApproveWallet(address indexed _wallet);
event RevokeWallet(address indexed _wallet);
/// @notice Constructor of the contract
/// @param _admin Admin address of the contract
constructor(address _admin) {
require(_admin != address(0), "0");
admin = _admin;
}
/// @notice Commits to change the admin
/// @param _admin New admin of the contract
function commitAdmin(address _admin) external {
require(msg.sender == admin, "!admin");
future_admin = _admin;
}
/// @notice Changes the admin to the admin that has been committed
function applyAdmin() external {
require(msg.sender == admin, "!admin");
require(future_admin != address(0), "admin not set");
admin = future_admin;
}
/// @notice Commits to change the checker address
/// @param _checker New checker address
/// @dev This address can be the zero address in which case there will be no checker
function commitSetChecker(address _checker) external {
require(msg.sender == admin, "!admin");
future_checker = _checker;
}
/// @notice Applies the checker previously committed
function applySetChecker() external {
require(msg.sender == admin, "!admin");
checker = future_checker;
}
/// @notice Approves a wallet
/// @param _wallet Wallet to approve
function approveWallet(address _wallet) public {
require(msg.sender == admin, "!admin");
wallets[_wallet] = true;
emit ApproveWallet(_wallet);
}
/// @notice Revokes a wallet
/// @param _wallet Wallet to revoke
function revokeWallet(address _wallet) external {
require(msg.sender == admin, "!admin");
wallets[_wallet] = false;
emit RevokeWallet(_wallet);
}
/// @notice Checks whether a wallet is whitelisted
/// @param _wallet Wallet address to check
/// @dev This function can also rely on another SmartWalletChecker (a `checker` to see whether the wallet is whitelisted or not)
function check(address _wallet) external view returns (bool) {
bool _check = wallets[_wallet];
if (_check) {
return _check;
} else {
if (checker != address(0)) {
return SmartWalletChecker(checker).check(_wallet);
}
}
return false;
}
}
|
contract SmartWalletWhitelist {
/// @notice Mapping between addresses and whether they are whitelisted or not
mapping(address => bool) public wallets;
/// @notice Admin address of the contract
address public admin;
/// @notice Future admin address of the contract
//solhint-disable-next-line
address public future_admin;
/// @notice Contract which works as this contract and that can whitelist addresses
address public checker;
/// @notice Future address to become checker
//solhint-disable-next-line
address public future_checker;
event ApproveWallet(address indexed _wallet);
event RevokeWallet(address indexed _wallet);
/// @notice Constructor of the contract
/// @param _admin Admin address of the contract
constructor(address _admin) {
require(_admin != address(0), "0");
admin = _admin;
}
/// @notice Commits to change the admin
/// @param _admin New admin of the contract
function commitAdmin(address _admin) external {
require(msg.sender == admin, "!admin");
future_admin = _admin;
}
/// @notice Changes the admin to the admin that has been committed
function applyAdmin() external {
require(msg.sender == admin, "!admin");
require(future_admin != address(0), "admin not set");
admin = future_admin;
}
/// @notice Commits to change the checker address
/// @param _checker New checker address
/// @dev This address can be the zero address in which case there will be no checker
function commitSetChecker(address _checker) external {
require(msg.sender == admin, "!admin");
future_checker = _checker;
}
/// @notice Applies the checker previously committed
function applySetChecker() external {
require(msg.sender == admin, "!admin");
checker = future_checker;
}
/// @notice Approves a wallet
/// @param _wallet Wallet to approve
function approveWallet(address _wallet) public {
require(msg.sender == admin, "!admin");
wallets[_wallet] = true;
emit ApproveWallet(_wallet);
}
/// @notice Revokes a wallet
/// @param _wallet Wallet to revoke
function revokeWallet(address _wallet) external {
require(msg.sender == admin, "!admin");
wallets[_wallet] = false;
emit RevokeWallet(_wallet);
}
/// @notice Checks whether a wallet is whitelisted
/// @param _wallet Wallet address to check
/// @dev This function can also rely on another SmartWalletChecker (a `checker` to see whether the wallet is whitelisted or not)
function check(address _wallet) external view returns (bool) {
bool _check = wallets[_wallet];
if (_check) {
return _check;
} else {
if (checker != address(0)) {
return SmartWalletChecker(checker).check(_wallet);
}
}
return false;
}
}
| 7,303
|
25
|
// update staked amount
|
stakedAmount = stakedAmount.add(rewards);
|
stakedAmount = stakedAmount.add(rewards);
| 9,656
|
128
|
// This returns balance last time someone transacted with cToken
|
function getCachedPosition()
external
view
returns (
uint supplied,
uint borrowed,
uint marketCol,
uint safeCol
)
|
function getCachedPosition()
external
view
returns (
uint supplied,
uint borrowed,
uint marketCol,
uint safeCol
)
| 34,210
|
49
|
// Admin function to set the minimum amount required for a depositminDepositAmount The minimum amount required to submit a depositrequest /
|
function setMinimumDepositAmount(
uint256 minDepositAmount
|
function setMinimumDepositAmount(
uint256 minDepositAmount
| 24,639
|
1
|
// Base Currency
|
_assets[0] = _baseCurrency;
_assets[1] = _baseAssimilator;
_assets[2] = _baseCurrency;
_assets[3] = _baseAssimilator;
_assets[4] = _baseCurrency;
|
_assets[0] = _baseCurrency;
_assets[1] = _baseAssimilator;
_assets[2] = _baseCurrency;
_assets[3] = _baseAssimilator;
_assets[4] = _baseCurrency;
| 41,183
|
65
|
// Called by a system administrator to add an owner.Reverts if `_ownerAddress` already has owner role _ownerAddress approved ownerreturn added boolean indicating whether the role was granted /
|
function addOwner(address _ownerAddress) external onlySysAdmin {
owners.add(_ownerAddress);
require(owners.has(_ownerAddress));
}
|
function addOwner(address _ownerAddress) external onlySysAdmin {
owners.add(_ownerAddress);
require(owners.has(_ownerAddress));
}
| 9,081
|
2
|
// Interface of the Prime membership contract /
|
interface IPrime {
/// @notice Member status enum
enum MemberStatus {
PENDING,
WHITELISTED,
BLACKLISTED
}
/// @notice A record of member info
struct Member {
uint256 riskScore;
MemberStatus status;
bool created;
}
/**
* @notice Check membership status for a given `_member`
* @param _member The address of member
* @return Boolean flag containing membership status
*/
function isMember(address _member) external view returns (bool);
/**
* @notice Check Stablecoin existence for a given `asset` address
* @param asset The address of asset
* @return Boolean flag containing asset availability
*/
function isAssetAvailable(address asset) external view returns (bool);
/**
* @notice Get membership info for a given `_member`
* @param _member The address of member
* @return The member info struct
*/
function membershipOf(address _member) external view returns (Member memory);
/**
* @notice Returns current protocol rate value
* @return The protocol rate as a mantissa between [0, 1e18]
*/
function spreadRate() external view returns (uint256);
/**
* @notice Returns current originated fee value
* @return originated fee rate as a mantissa between [0, 1e18]
*/
function originationRate() external view returns (uint256);
/**
* @notice Returns current rolling increment fee
* @return rolling fee rate as a mantissa between [0, 1e18]
*/
function incrementPerRoll() external view returns (uint256);
/**
* @notice Returns current protocol fee collector address
* @return address of protocol fee collector
*/
function treasury() external view returns (address);
/**
* @notice Returns current penalty rate for 1 year
* @return penalty fee rate as a mantissa between [0, 1e18]
*/
function penaltyRatePerYear() external view returns (uint256);
}
|
interface IPrime {
/// @notice Member status enum
enum MemberStatus {
PENDING,
WHITELISTED,
BLACKLISTED
}
/// @notice A record of member info
struct Member {
uint256 riskScore;
MemberStatus status;
bool created;
}
/**
* @notice Check membership status for a given `_member`
* @param _member The address of member
* @return Boolean flag containing membership status
*/
function isMember(address _member) external view returns (bool);
/**
* @notice Check Stablecoin existence for a given `asset` address
* @param asset The address of asset
* @return Boolean flag containing asset availability
*/
function isAssetAvailable(address asset) external view returns (bool);
/**
* @notice Get membership info for a given `_member`
* @param _member The address of member
* @return The member info struct
*/
function membershipOf(address _member) external view returns (Member memory);
/**
* @notice Returns current protocol rate value
* @return The protocol rate as a mantissa between [0, 1e18]
*/
function spreadRate() external view returns (uint256);
/**
* @notice Returns current originated fee value
* @return originated fee rate as a mantissa between [0, 1e18]
*/
function originationRate() external view returns (uint256);
/**
* @notice Returns current rolling increment fee
* @return rolling fee rate as a mantissa between [0, 1e18]
*/
function incrementPerRoll() external view returns (uint256);
/**
* @notice Returns current protocol fee collector address
* @return address of protocol fee collector
*/
function treasury() external view returns (address);
/**
* @notice Returns current penalty rate for 1 year
* @return penalty fee rate as a mantissa between [0, 1e18]
*/
function penaltyRatePerYear() external view returns (uint256);
}
| 41,852
|
22
|
// Calculate the preset indexes for ordering
|
bool underlyingFirst = _underlying < _bond;
baseIndex = underlyingFirst ? 0 : 1;
bondIndex = underlyingFirst ? 1 : 0;
|
bool underlyingFirst = _underlying < _bond;
baseIndex = underlyingFirst ? 0 : 1;
bondIndex = underlyingFirst ? 1 : 0;
| 71,195
|
58
|
// This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding({_hashTypedDataV4})./ solhint-disable var-name-mixedcase / Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to invalidate the cached domain separator if the chain id changes.
|
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
|
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
| 2,234
|
252
|
// Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. a a FixedPoint.Signed. b a FixedPoint.Signed.return the product of `a` and `b`. /
|
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
|
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
| 8,156
|
25
|
// modifier to scope access to a set of roles (uses msg.sender as addr) _roles the names of the roles to scope access to @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this /
|
// modifier onlyRoles(string[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
|
// modifier onlyRoles(string[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
| 6,331
|
326
|
// Get the underlying price of a cToken assetcToken The cToken to get the underlying price of return The underlying asset price mantissa (scaled by 1e18).Zero means the price is unavailable./
|
function getUnderlyingPrice(CToken cToken) external view returns (uint);
|
function getUnderlyingPrice(CToken cToken) external view returns (uint);
| 25,477
|
7
|
// Mapping of account => assetId => pendingWithdrawAmount
|
mapping(address => mapping(uint32 => uint256)) public pendingWithdraws;
|
mapping(address => mapping(uint32 => uint256)) public pendingWithdraws;
| 43,197
|
38
|
// (exchangeRate - rateAnchor)rateScalar
|
(exchangeRate.sub(rateAnchor)).mulInRatePrecision(rateScalar)
);
|
(exchangeRate.sub(rateAnchor)).mulInRatePrecision(rateScalar)
);
| 40,145
|
69
|
// tracking for purchasers
|
mapping (address => uint256) public purchases;
|
mapping (address => uint256) public purchases;
| 30,415
|
4
|
// Logged when the TTL of a node changes
|
event NewTTL(bytes32 indexed node, uint64 ttl);
|
event NewTTL(bytes32 indexed node, uint64 ttl);
| 3,670
|
27
|
// ============ External Imports ============
|
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
/**
* @title UpgradeBeaconProxy
* @notice
* Proxy contract which delegates all logic, including initialization,
* to an implementation contract.
* The implementation contract is stored within an Upgrade Beacon contract;
* the implementation contract can be changed by performing an upgrade on the Upgrade Beacon contract.
* The Upgrade Beacon contract for this Proxy is immutably specified at deployment.
* @dev This implementation combines the gas savings of keeping the UpgradeBeacon address outside of contract storage
* found in 0age's implementation:
* https://github.com/dharma-eng/dharma-smart-wallet/blob/master/contracts/proxies/smart-wallet/UpgradeBeaconProxyV1.sol
* With the added safety checks that the UpgradeBeacon and implementation are contracts at time of deployment
* found in OpenZeppelin's implementation:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/beacon/BeaconProxy.sol
*/
contract UpgradeBeaconProxy {
// ============ Immutables ============
// Upgrade Beacon address is immutable (therefore not kept in contract storage)
address private immutable upgradeBeacon;
// ============ Constructor ============
/**
* @notice Validate that the Upgrade Beacon is a contract, then set its
* address immutably within this contract.
* Validate that the implementation is also a contract,
* Then call the initialization function defined at the implementation.
* The deployment will revert and pass along the
* revert reason if the initialization function reverts.
* @param _upgradeBeacon Address of the Upgrade Beacon to be stored immutably in the contract
* @param _initializationCalldata Calldata supplied when calling the initialization function
*/
constructor(address _upgradeBeacon, bytes memory _initializationCalldata) payable {
// Validate the Upgrade Beacon is a contract
require(Address.isContract(_upgradeBeacon), "beacon !contract");
// set the Upgrade Beacon
upgradeBeacon = _upgradeBeacon;
// Validate the implementation is a contract
address _implementation = _getImplementation(_upgradeBeacon);
require(Address.isContract(_implementation), "beacon implementation !contract");
// Call the initialization function on the implementation
if (_initializationCalldata.length > 0) {
_initialize(_implementation, _initializationCalldata);
}
}
// ============ External Functions ============
/**
* @notice Forwards all calls with data to _fallback()
* No public functions are declared on the contract, so all calls hit fallback
*/
fallback() external payable {
_fallback();
}
/**
* @notice Forwards all calls with no data to _fallback()
*/
receive() external payable {
_fallback();
}
// ============ Private Functions ============
/**
* @notice Call the initialization function on the implementation
* Used at deployment to initialize the proxy
* based on the logic for initialization defined at the implementation
* @param _implementation - Contract to which the initalization is delegated
* @param _initializationCalldata - Calldata supplied when calling the initialization function
*/
function _initialize(address _implementation, bytes memory _initializationCalldata) private {
// Delegatecall into the implementation, supplying initialization calldata.
(bool _ok, ) = _implementation.delegatecall(_initializationCalldata);
// Revert and include revert data if delegatecall to implementation reverts.
if (!_ok) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
/**
* @notice Delegates function calls to the implementation contract returned by the Upgrade Beacon
*/
function _fallback() private {
_delegate(_getImplementation());
}
/**
* @notice Delegate function execution to the implementation contract
* @dev This is a low level function that doesn't return to its internal
* call site. It will return whatever is returned by the implementation to the
* external caller, reverting and returning the revert data if implementation
* reverts.
* @param _implementation - Address to which the function execution is delegated
*/
function _delegate(address _implementation) private {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Delegatecall to the implementation, supplying calldata and gas.
// Out and outsize are set to zero - instead, use the return buffer.
let result := delegatecall(gas(), _implementation, 0, calldatasize(), 0, 0)
// Copy the returned data from the return buffer.
returndatacopy(0, 0, returndatasize())
switch result
// Delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @notice Call the Upgrade Beacon to get the current implementation contract address
* @return _implementation Address of the current implementation.
*/
function _getImplementation() private view returns (address _implementation) {
_implementation = _getImplementation(upgradeBeacon);
}
/**
* @notice Call the Upgrade Beacon to get the current implementation contract address
* @dev _upgradeBeacon is passed as a parameter so that
* we can also use this function in the constructor,
* where we can't access immutable variables.
* @param _upgradeBeacon Address of the UpgradeBeacon storing the current implementation
* @return _implementation Address of the current implementation.
*/
function _getImplementation(address _upgradeBeacon) private view returns (address _implementation) {
// Get the current implementation address from the upgrade beacon.
(bool _ok, bytes memory _returnData) = _upgradeBeacon.staticcall("");
// Revert and pass along revert message if call to upgrade beacon reverts.
require(_ok, string(_returnData));
// Set the implementation to the address returned from the upgrade beacon.
_implementation = abi.decode(_returnData, (address));
}
}
|
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
/**
* @title UpgradeBeaconProxy
* @notice
* Proxy contract which delegates all logic, including initialization,
* to an implementation contract.
* The implementation contract is stored within an Upgrade Beacon contract;
* the implementation contract can be changed by performing an upgrade on the Upgrade Beacon contract.
* The Upgrade Beacon contract for this Proxy is immutably specified at deployment.
* @dev This implementation combines the gas savings of keeping the UpgradeBeacon address outside of contract storage
* found in 0age's implementation:
* https://github.com/dharma-eng/dharma-smart-wallet/blob/master/contracts/proxies/smart-wallet/UpgradeBeaconProxyV1.sol
* With the added safety checks that the UpgradeBeacon and implementation are contracts at time of deployment
* found in OpenZeppelin's implementation:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/beacon/BeaconProxy.sol
*/
contract UpgradeBeaconProxy {
// ============ Immutables ============
// Upgrade Beacon address is immutable (therefore not kept in contract storage)
address private immutable upgradeBeacon;
// ============ Constructor ============
/**
* @notice Validate that the Upgrade Beacon is a contract, then set its
* address immutably within this contract.
* Validate that the implementation is also a contract,
* Then call the initialization function defined at the implementation.
* The deployment will revert and pass along the
* revert reason if the initialization function reverts.
* @param _upgradeBeacon Address of the Upgrade Beacon to be stored immutably in the contract
* @param _initializationCalldata Calldata supplied when calling the initialization function
*/
constructor(address _upgradeBeacon, bytes memory _initializationCalldata) payable {
// Validate the Upgrade Beacon is a contract
require(Address.isContract(_upgradeBeacon), "beacon !contract");
// set the Upgrade Beacon
upgradeBeacon = _upgradeBeacon;
// Validate the implementation is a contract
address _implementation = _getImplementation(_upgradeBeacon);
require(Address.isContract(_implementation), "beacon implementation !contract");
// Call the initialization function on the implementation
if (_initializationCalldata.length > 0) {
_initialize(_implementation, _initializationCalldata);
}
}
// ============ External Functions ============
/**
* @notice Forwards all calls with data to _fallback()
* No public functions are declared on the contract, so all calls hit fallback
*/
fallback() external payable {
_fallback();
}
/**
* @notice Forwards all calls with no data to _fallback()
*/
receive() external payable {
_fallback();
}
// ============ Private Functions ============
/**
* @notice Call the initialization function on the implementation
* Used at deployment to initialize the proxy
* based on the logic for initialization defined at the implementation
* @param _implementation - Contract to which the initalization is delegated
* @param _initializationCalldata - Calldata supplied when calling the initialization function
*/
function _initialize(address _implementation, bytes memory _initializationCalldata) private {
// Delegatecall into the implementation, supplying initialization calldata.
(bool _ok, ) = _implementation.delegatecall(_initializationCalldata);
// Revert and include revert data if delegatecall to implementation reverts.
if (!_ok) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
/**
* @notice Delegates function calls to the implementation contract returned by the Upgrade Beacon
*/
function _fallback() private {
_delegate(_getImplementation());
}
/**
* @notice Delegate function execution to the implementation contract
* @dev This is a low level function that doesn't return to its internal
* call site. It will return whatever is returned by the implementation to the
* external caller, reverting and returning the revert data if implementation
* reverts.
* @param _implementation - Address to which the function execution is delegated
*/
function _delegate(address _implementation) private {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Delegatecall to the implementation, supplying calldata and gas.
// Out and outsize are set to zero - instead, use the return buffer.
let result := delegatecall(gas(), _implementation, 0, calldatasize(), 0, 0)
// Copy the returned data from the return buffer.
returndatacopy(0, 0, returndatasize())
switch result
// Delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @notice Call the Upgrade Beacon to get the current implementation contract address
* @return _implementation Address of the current implementation.
*/
function _getImplementation() private view returns (address _implementation) {
_implementation = _getImplementation(upgradeBeacon);
}
/**
* @notice Call the Upgrade Beacon to get the current implementation contract address
* @dev _upgradeBeacon is passed as a parameter so that
* we can also use this function in the constructor,
* where we can't access immutable variables.
* @param _upgradeBeacon Address of the UpgradeBeacon storing the current implementation
* @return _implementation Address of the current implementation.
*/
function _getImplementation(address _upgradeBeacon) private view returns (address _implementation) {
// Get the current implementation address from the upgrade beacon.
(bool _ok, bytes memory _returnData) = _upgradeBeacon.staticcall("");
// Revert and pass along revert message if call to upgrade beacon reverts.
require(_ok, string(_returnData));
// Set the implementation to the address returned from the upgrade beacon.
_implementation = abi.decode(_returnData, (address));
}
}
| 6,198
|
16
|
// Writes an option for the given ask. /
|
function writeOption(
|
function writeOption(
| 25,051
|
1,326
|
// Compute the reward and add to the cumulative reward.
|
FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
|
FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
| 1,996
|
257
|
// 查询某个tokenId是否有效,由是否存在、过期时间判断
|
function isValid(uint256 tokenId) external view returns (bool);
|
function isValid(uint256 tokenId) external view returns (bool);
| 41,534
|
316
|
// Initializes crypto alpaca contract. _alpa ALPA ERC20 contract address _devAddress dev address. _stakingAddress staking address. /
|
constructor(
IERC20 _alpa,
IGeneScience _geneScience,
address _devAddress,
address _stakingAddress
|
constructor(
IERC20 _alpa,
IGeneScience _geneScience,
address _devAddress,
address _stakingAddress
| 22,889
|
294
|
// contracts/Governance.sol
|
pragma solidity ^0.8.0;
|
pragma solidity ^0.8.0;
| 11,953
|
70
|
// the global fee growth of the input token
|
uint256 feeGrowthGlobalX128;
|
uint256 feeGrowthGlobalX128;
| 2,407
|
2
|
// Pi bundle marketplace contract address;
|
address public bundleMarketplace;
|
address public bundleMarketplace;
| 32,682
|
65
|
// NOMINATE OWNERSHIP back to owner for aforementioned contracts
|
nominateAll();
|
nominateAll();
| 26,587
|
60
|
// Increments the total number of uncommitted storage slots. /
|
function incrementTotalUncommittedContractStorage()
override
public
authenticated
|
function incrementTotalUncommittedContractStorage()
override
public
authenticated
| 67,491
|
126
|
// Issuable The Issuable contract defines the issuer role who can perform certain kind of actionseven if he is not the owner.An issuer can transfer his role to a new address. /
|
contract Issuable is Ownable, SupportsInterfaceWithLookup {
bytes32 public constant ISSUER_ROLE = keccak256("ISSUER_ROLE");
/**
* @dev Throws if called by any account that's not a issuer.
*/
modifier onlyIssuer() {
require(isIssuer(_msgSender()), 'Issuable: caller is not the issuer');
_;
}
modifier onlyOwnerOrIssuer() {
require(_msgSender() == owner() || isIssuer(_msgSender()), 'Issuable: caller is not the issuer or the owner');
_;
}
/**
* @dev getter to determine if address has issuer role
*/
function isIssuer(address _operator) public view returns (bool) {
return hasRole(ISSUER_ROLE, _operator);
}
/**
* @dev add a new issuer address
* @param _operator address
*/
function addIssuer(address _operator) public onlyOwner {
grantRole(ISSUER_ROLE, _operator);
}
/**
* @dev remove an address from issuers
* @param _operator address
*/
function removeIssuer(address _operator) public onlyOwner {
revokeRole(ISSUER_ROLE, _operator);
}
/**
* @dev Allows the current issuer to transfer his role to a newIssuer.
* @param _newIssuer The address to transfer the issuer role to.
*/
function transferIssuer(address _newIssuer) public onlyIssuer {
require(_newIssuer != address(0));
revokeRole(ISSUER_ROLE, _msgSender());
grantRole(ISSUER_ROLE, _newIssuer);
}
}
|
contract Issuable is Ownable, SupportsInterfaceWithLookup {
bytes32 public constant ISSUER_ROLE = keccak256("ISSUER_ROLE");
/**
* @dev Throws if called by any account that's not a issuer.
*/
modifier onlyIssuer() {
require(isIssuer(_msgSender()), 'Issuable: caller is not the issuer');
_;
}
modifier onlyOwnerOrIssuer() {
require(_msgSender() == owner() || isIssuer(_msgSender()), 'Issuable: caller is not the issuer or the owner');
_;
}
/**
* @dev getter to determine if address has issuer role
*/
function isIssuer(address _operator) public view returns (bool) {
return hasRole(ISSUER_ROLE, _operator);
}
/**
* @dev add a new issuer address
* @param _operator address
*/
function addIssuer(address _operator) public onlyOwner {
grantRole(ISSUER_ROLE, _operator);
}
/**
* @dev remove an address from issuers
* @param _operator address
*/
function removeIssuer(address _operator) public onlyOwner {
revokeRole(ISSUER_ROLE, _operator);
}
/**
* @dev Allows the current issuer to transfer his role to a newIssuer.
* @param _newIssuer The address to transfer the issuer role to.
*/
function transferIssuer(address _newIssuer) public onlyIssuer {
require(_newIssuer != address(0));
revokeRole(ISSUER_ROLE, _msgSender());
grantRole(ISSUER_ROLE, _newIssuer);
}
}
| 5,347
|
11
|
// Loads the resolver address from storage
|
function _resolver()
public
view
|
function _resolver()
public
view
| 10,098
|
22
|
// Event emitted when the block time is updated. Contains the old and new block time values. /
|
event BlockTimeChanged(uint8 oldBlockTime, uint8 newBlocktime);
|
event BlockTimeChanged(uint8 oldBlockTime, uint8 newBlocktime);
| 25,661
|
127
|
// Clears the currently set whitelisted dispatcher wallet, effectively disabling callingthe `executeOrderBookTrade`, `executePoolTrade`, `executeHybridTrade`, `withdraw`,`executeAddLiquidity`, and `executeRemoveLiquidity` functions until a new wallet is set with`setDispatcher` /
|
function removeDispatcher() external onlyAdmin {
_dispatcherWallet = address(0x0);
}
|
function removeDispatcher() external onlyAdmin {
_dispatcherWallet = address(0x0);
}
| 26,834
|
6
|
// mapping(uint256 => Stake) public swords; mapping(uint256 => Stake) public daggers;
|
mapping(address => uint256) public addressToShieldsStaked;
|
mapping(address => uint256) public addressToShieldsStaked;
| 14,006
|
192
|
// Convert a principal amount to a token amount given an index. /
|
function parToWei(
Types.Par memory input,
Index memory index
)
internal
pure
returns (Types.Wei memory)
|
function parToWei(
Types.Par memory input,
Index memory index
)
internal
pure
returns (Types.Wei memory)
| 23,798
|
676
|
// Exits USB from the pot
|
PotLike(pot).exit(pie);
|
PotLike(pot).exit(pie);
| 12,077
|
2
|
// Here the &39;Table&39; event is treated as an SQL table Each property is indexed and can be retrieved easily via web3.js
|
event Table(uint256 indexed _row, bytes32 indexed _column, bytes32 indexed _value);
|
event Table(uint256 indexed _row, bytes32 indexed _column, bytes32 indexed _value);
| 50,029
|
93
|
// Calculates the PMA Rate for the fiat currency specified - The rate is set every 10 minutes by our PMA server/ for the currencies specified in the smart contract./_fiatAmountInCents - payment amount in fiat CENTS so that is always integer/_currency - currency in which the payment needs to take place/ RATE CALCULATION EXAMPLE/ ------------------------/ RATE ==> 1 PMA = 0.01 USD$/ 1 USD$ = 1/0.01 PMA = 100 PMA/ Start the calculation from one ether - PMA Token has 18 decimals/ Multiply by the DECIMAL_FIXER (1e+10) to fix the multiplication of the rate/ Multiply with the fiat amount in cents/
|
function calculatePMAFromFiat(uint256 _fiatAmountInCents, string memory _currency)
internal
view
validConversionRate(_currency)
validAmount(_fiatAmountInCents)
|
function calculatePMAFromFiat(uint256 _fiatAmountInCents, string memory _currency)
internal
view
validConversionRate(_currency)
validAmount(_fiatAmountInCents)
| 8,272
|
9
|
// Blind bid, requires a minimum deposit of 1 eth
|
function bid(bytes32 blindedBind) external payable onlyActiveBid()
|
function bid(bytes32 blindedBind) external payable onlyActiveBid()
| 49,660
|
62
|
// Step 1: Mint sETH with WETH
|
_approve(weth, target, amount);
IEtherWrapper(target).mint(amount);
uint256 sethBal = seth.balanceOf(address(this));
|
_approve(weth, target, amount);
IEtherWrapper(target).mint(amount);
uint256 sethBal = seth.balanceOf(address(this));
| 35,041
|
15
|
// Emits a {WithDrawState} event. /
|
function disableWithdraw() external onlyRole(ESCROW_ROLE) {
require(
_withdrawState == WithdrawState.Enabled,
"withdraw state is already disabled"
);
_withdrawState = WithdrawState.Disabled;
emit WithdrawalState(_withdrawState);
}
|
function disableWithdraw() external onlyRole(ESCROW_ROLE) {
require(
_withdrawState == WithdrawState.Enabled,
"withdraw state is already disabled"
);
_withdrawState = WithdrawState.Disabled;
emit WithdrawalState(_withdrawState);
}
| 693
|
23
|
// Find the owner of an NFT.NFTs assigned to zero address are considered invalid, and queries about them do throw.id uint256The identifier for an NFT.return owneraddressThe address of the owner of the NFT. /
|
function ownerOf(uint256 id) external view returns (address owner) {
// Throw if `owner` is the zero address.
if ((owner = _ownerOf[id]) == address(0)) revert NotWrappedToken();
}
|
function ownerOf(uint256 id) external view returns (address owner) {
// Throw if `owner` is the zero address.
if ((owner = _ownerOf[id]) == address(0)) revert NotWrappedToken();
}
| 29,266
|
32
|
// builds the validation data structures, called for each transaction step of a transtive transactions/src the sender of a single transaction step/dest the recipient of a single transaction step/wad the amount being passed along a single transaction step
|
function buildValidationData(address src, address dest, uint wad) internal {
// the validation mapping has this format
// { address: {
// seen: whether this user is part of the transaction,
// sent: total amount sent by this user,
// received: total amount received by this user,
// }
// }
|
function buildValidationData(address src, address dest, uint wad) internal {
// the validation mapping has this format
// { address: {
// seen: whether this user is part of the transaction,
// sent: total amount sent by this user,
// received: total amount received by this user,
// }
// }
| 21,480
|
37
|
// refund ethers
|
refund();
|
refund();
| 26,849
|
218
|
// Stake DCASH tokens to MasterChef
|
function enterStaking(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
updatePool(0);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accDcashPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeDcashTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accDcashPerShare).div(1e12);
gem.mint(msg.sender, _amount);
emit Deposit(msg.sender, 0, _amount);
}
|
function enterStaking(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
updatePool(0);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accDcashPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeDcashTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accDcashPerShare).div(1e12);
gem.mint(msg.sender, _amount);
emit Deposit(msg.sender, 0, _amount);
}
| 25,493
|
16
|
// 3. Burn bought ARTH cash and mint bonds at the discounted price. TODO: Set the minting amount according to bond price. TODO: calculate premium basis size of the trade
|
IBasisAsset(cash).burnFrom(msg.sender, cashToConvert);
IBasisAsset(bond).mint(msg.sender, bondsToIssue);
emit BoughtBonds(msg.sender, amountInDai, cashToConvert, bondsToIssue);
return bondsToIssue;
|
IBasisAsset(cash).burnFrom(msg.sender, cashToConvert);
IBasisAsset(bond).mint(msg.sender, bondsToIssue);
emit BoughtBonds(msg.sender, amountInDai, cashToConvert, bondsToIssue);
return bondsToIssue;
| 24,926
|
29
|
// Transfer ETH amount from contract to owner's address.Can only be used if ICO is closedamount - ETH amount to transfer in Wei/
|
function safeWithdrawal(uint amount) external onlyOwner {
require(this.balance >= amount);
require(!isICOActive());
if (owner.send(amount)) {
FundTransfer(address(this), msg.sender, amount);
}
}
|
function safeWithdrawal(uint amount) external onlyOwner {
require(this.balance >= amount);
require(!isICOActive());
if (owner.send(amount)) {
FundTransfer(address(this), msg.sender, amount);
}
}
| 40,643
|
7
|
// add auth so we can exit the dai
|
if (vat.can(address(this), address(DAI_JOIN_ADDR)) == 0) {
vat.hope(DAI_JOIN_ADDR);
}
|
if (vat.can(address(this), address(DAI_JOIN_ADDR)) == 0) {
vat.hope(DAI_JOIN_ADDR);
}
| 29,887
|
89
|
// ======== DEPENDENCIES ======== // ======== STATE VARIABLES ======== // ======== CONSTRUCTOR ======== /
|
) {
require(_treasury != address(0));
treasury = IHadesTreasury(_treasury);
require(_ohmStaking != address(0));
ohmStaking = IStaking(_ohmStaking);
require(_ohmStakingHelper != address(0));
ohmStakingHelper = IStakingHelper(_ohmStakingHelper);
require(_dao!= address(0));
dao = _dao;
require(_ohm != address(0));
ohm = _ohm;
require(_sOhm != address(0));
sOhm = _sOhm;
timelockInBlocks = _timelockInBlocks;
principleStaked = 0;
daoFee = 5000; // 5000bps = 50%
}
|
) {
require(_treasury != address(0));
treasury = IHadesTreasury(_treasury);
require(_ohmStaking != address(0));
ohmStaking = IStaking(_ohmStaking);
require(_ohmStakingHelper != address(0));
ohmStakingHelper = IStakingHelper(_ohmStakingHelper);
require(_dao!= address(0));
dao = _dao;
require(_ohm != address(0));
ohm = _ohm;
require(_sOhm != address(0));
sOhm = _sOhm;
timelockInBlocks = _timelockInBlocks;
principleStaked = 0;
daoFee = 5000; // 5000bps = 50%
}
| 17,734
|
157
|
// Returns true if `self` starts with `needle`. self The slice to operate on. needle The slice to search for.return True if the slice starts with the provided text, false otherwise. /
|
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
|
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
| 12,609
|
37
|
// Calulcate the number of neightbours of _cellId for the old and the new owner, then double the number and multiply it by POINTS_PER_NEIGHBOUR.
|
oldOwnerScoreAdjustment = oldOwnerScoreAdjustment.add(calculateNumberOfNeighbours(_cellId, _oldOwner).mul(POINTS_PER_NEIGHBOUR).mul(2));
newOwnerScoreAdjustment = newOwnerScoreAdjustment.add(calculateNumberOfNeighbours(_cellId, _newOwner).mul(POINTS_PER_NEIGHBOUR).mul(2));
if (_oldOwner == address(0)) {
oldOwnerScoreAdjustment = 0;
}
|
oldOwnerScoreAdjustment = oldOwnerScoreAdjustment.add(calculateNumberOfNeighbours(_cellId, _oldOwner).mul(POINTS_PER_NEIGHBOUR).mul(2));
newOwnerScoreAdjustment = newOwnerScoreAdjustment.add(calculateNumberOfNeighbours(_cellId, _newOwner).mul(POINTS_PER_NEIGHBOUR).mul(2));
if (_oldOwner == address(0)) {
oldOwnerScoreAdjustment = 0;
}
| 45,843
|
103
|
// Statement to actually sign. ```js
|
//# statement = function() { this.STATEMENT().map(s => s.substr(28)) }
//# ```
/// Minimum duration after sale begins that bonus is active.
uint constant public BONUS_MIN_DURATION = 1 hours;
/// Minimum duration after sale begins that bonus is active.
uint constant public BONUS_MAX_DURATION = 12 hours;
/// Number of consecutive blocks where there must be no new interest before bonus ends.
uint constant public BONUS_LATCH = 2;
/// Number of Wei in one EUR, constant.
uint constant public EURWEI = 2000 szabo; // 500 eur ~ 1 eth
/// Initial auction length
uint constant public DEFAULT_AUCTION_LENGTH = 2 days;
/// Divisor of the token.
uint constant public DIVISOR = 1000;
}
|
//# statement = function() { this.STATEMENT().map(s => s.substr(28)) }
//# ```
/// Minimum duration after sale begins that bonus is active.
uint constant public BONUS_MIN_DURATION = 1 hours;
/// Minimum duration after sale begins that bonus is active.
uint constant public BONUS_MAX_DURATION = 12 hours;
/// Number of consecutive blocks where there must be no new interest before bonus ends.
uint constant public BONUS_LATCH = 2;
/// Number of Wei in one EUR, constant.
uint constant public EURWEI = 2000 szabo; // 500 eur ~ 1 eth
/// Initial auction length
uint constant public DEFAULT_AUCTION_LENGTH = 2 days;
/// Divisor of the token.
uint constant public DIVISOR = 1000;
}
| 50,343
|
23
|
// If there is no base URI, return the token URI.
|
if (bytes(base).length == 0) {
return _tokenURI;
}
|
if (bytes(base).length == 0) {
return _tokenURI;
}
| 275
|
199
|
// Sale data
|
enum Sale{NON, WHITELIST, PUBLIC}
Sale public sale;
uint256 public immutable whitelistCost = 0.05 ether;
uint256 public immutable publicCost = 0.065 ether;
uint256 public maxSupply = 500;
uint256 public maxNFTPerWalletPublic = 10;
uint256 public maxNFTPerWalletWhitelist = 3;
bool public revealed = false;
string public baseURI;
address public artistWallet = 0x61c78036fea782d625D3Eb81E4E79ddD2520F258;
address public virtunesWallet = 0x7DF507111c7477c76e147B4978c9Dff7835B7556;
constructor(
string memory _name,
string memory _symbol,
string memory _uri
) ERC721A(_name, _symbol) {
baseURI = _uri;
}
|
enum Sale{NON, WHITELIST, PUBLIC}
Sale public sale;
uint256 public immutable whitelistCost = 0.05 ether;
uint256 public immutable publicCost = 0.065 ether;
uint256 public maxSupply = 500;
uint256 public maxNFTPerWalletPublic = 10;
uint256 public maxNFTPerWalletWhitelist = 3;
bool public revealed = false;
string public baseURI;
address public artistWallet = 0x61c78036fea782d625D3Eb81E4E79ddD2520F258;
address public virtunesWallet = 0x7DF507111c7477c76e147B4978c9Dff7835B7556;
constructor(
string memory _name,
string memory _symbol,
string memory _uri
) ERC721A(_name, _symbol) {
baseURI = _uri;
}
| 13,740
|
45
|
// Token Base/Shared logic for token contracts
|
contract PPPCollection is ERC721, Ownable {
/// @notice The OpenSea OperatorFilterRegistry deployment
IOperatorFilterRegistry private constant OPERATOR_FILTER_REGISTRY =
IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);
uint256 private immutable MAX_SUPPLY;
address public royaltyReceiver;
address public minter;
address public metadataContract;
uint256 public royaltyFraction;
uint256 public royaltyDenominator = 100;
/// @notice Count of valid NFTs tracked by this contract
uint256 public totalSupply;
/// @notice Return the baseURI used for computing `tokenURI` values
string public baseURI;
error OnlyMinter();
error OperatorNotAllowed(address operator);
/// @dev This event emits when the metadata of a token is changed. Anyone aware of ERC-4906 can update cached
/// attributes related to a given `tokenId`.
event MetadataUpdate(uint256 tokenId);
/// @dev This event emits when the metadata of a range of tokens is changed. Anyone aware of ERC-4906 can update
/// cached attributes for tokens in the designated range.
event BatchMetadataUpdate(uint256 fromTokenId, uint256 toTokenId);
constructor(
string memory name,
string memory symbol,
string memory baseURI_,
uint256 maxSupply,
address royaltyReceiver_,
uint256 royaltyPercent
) ERC721(name, symbol) {
// CHECKS inputs
require(maxSupply > 0, "Max supply must not be zero");
require(royaltyReceiver_ != address(0), "Royalty receiver must not be the zero address");
require(royaltyPercent <= 100, "Royalty fraction must not be greater than 100%");
// EFFECTS
MAX_SUPPLY = maxSupply;
baseURI = baseURI_;
royaltyReceiver = royaltyReceiver_;
royaltyFraction = royaltyPercent;
// INTERACTIONS
if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {
// Subscribe to the "OpenSea Curated Subscription Address"
OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), 0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);
}
}
modifier onlyMinter() {
if (msg.sender != minter) revert OnlyMinter();
_;
}
// HOLDER FUNCTIONS
/// @notice Enable or disable approval for an `operator` to manage all assets belonging to the sender
/// @dev Emits the ApprovalForAll event. The contract MUST allow multiple operators per owner.
/// @param operator Address to add to the set of authorized operators
/// @param approved True to grant approval, false to revoke approval
function setApprovalForAll(address operator, bool approved) public virtual override {
// CHECKS inputs
if (approved && !operatorAllowed(operator)) revert OperatorNotAllowed(operator);
// CHECKS + EFFECTS
super.setApprovalForAll(operator, approved);
}
// MINTER FUNCTIONS
/// @notice Mint an unclaimed token to the given address
/// @dev Can only be called by the `minter` address
/// @param to The new token owner that will receive the minted token
/// @param tokenId The token being claimed. Reverts if invalid or already claimed.
function mint(address to, uint256 tokenId) external onlyMinter {
// CHECKS inputs
require(tokenId < MAX_SUPPLY, "Invalid token ID");
// CHECKS + EFFECTS (not _safeMint, so no interactions)
_mint(to, tokenId);
// More EFFECTS
unchecked {
totalSupply++;
}
}
// OWNER FUNCTIONS
/// @notice Set the `minter` address
/// @dev Can only be called by the contract `owner`
function setMinter(address minter_) external onlyOwner {
minter = minter_;
}
/// @notice Set the `royaltyReceiver` address
/// @dev Can only be called by the contract `owner`
function setRoyaltyReceiver(address royaltyReceiver_) external onlyOwner {
// CHECKS inputs
require(royaltyReceiver_ != address(0), "Royalty receiver must not be the zero address");
// EFFECTS
royaltyReceiver = royaltyReceiver_;
}
/// @notice Update the royalty fraction
/// @dev Can only be called by the contract `owner`
function setRoyaltyFraction(uint256 royaltyFraction_, uint256 royaltyDenominator_) external onlyOwner {
// CHECKS inputs
require(royaltyDenominator_ != 0, "Royalty denominator must not be zero");
require(royaltyFraction_ <= royaltyDenominator_, "Royalty fraction must not be greater than 100%");
// EFFECTS
royaltyFraction = royaltyFraction_;
royaltyDenominator = royaltyDenominator_;
}
/// @notice Update the baseURI for all metadata
/// @dev Can only be called by the contract `owner`. Emits an ERC-4906 event.
/// @param baseURI_ The new URI base. When specified, token URIs are created by concatenating the baseURI,
/// token ID, and ".json".
function updateBaseURI(string calldata baseURI_) external onlyOwner {
// CHECKS inputs
require(bytes(baseURI_).length > 0, "New base URI must be provided");
// EFFECTS
baseURI = baseURI_;
metadataContract = address(0);
emit BatchMetadataUpdate(0, MAX_SUPPLY - 1);
}
/// @notice Delegate all `tokenURI` calls to another contract
/// @dev Can only be called by the contract `owner`. Emits an ERC-4906 event.
/// @param delegate The contract that will handle `tokenURI` responses
function delegateTokenURIs(address delegate) external onlyOwner {
// CHECKS inputs
require(delegate != address(0), "New metadata delegate must not be the zero address");
require(delegate.code.length > 0, "New metadata delegate must be a contract");
// EFFECTS
baseURI = "";
metadataContract = delegate;
emit BatchMetadataUpdate(0, MAX_SUPPLY - 1);
}
// VIEW FUNCTIONS
/// @notice The URI for the given token
/// @dev Throws if `tokenId` is not valid or has not been minted
function tokenURI(uint256 tokenId) public view override returns (string memory) {
_requireMinted(tokenId);
if (bytes(baseURI).length > 0) {
return string(abi.encodePacked(baseURI, Strings.toString(tokenId), ".json"));
}
if (address(metadataContract) != address(0)) {
return IERC721Metadata(metadataContract).tokenURI(tokenId);
}
revert("tokenURI not configured");
}
/// @notice Return whether the given tokenId has been minted yet
function exists(uint256 tokenId) external view returns (bool) {
return _exists(tokenId);
}
/// @notice Calculate how much royalty is owed and to whom
/// @param salePrice - the sale price of the NFT asset
/// @return receiver - address of where the royalty payment should be sent
/// @return royaltyAmount - the royalty payment amount for salePrice
function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {
receiver = royaltyReceiver;
// Use OpenZeppelin math utils for full precision multiply and divide without overflow
royaltyAmount = Math.mulDiv(salePrice, royaltyFraction, royaltyDenominator, Math.Rounding.Up);
}
/// @notice Query if a contract implements an interface
/// @dev Interface identification is specified in ERC-165. This function uses less than 30,000 gas.
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @return `true` if the contract implements `interfaceID` and `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceId) public pure virtual override returns (bool) {
return
interfaceId == 0x80ac58cd || // ERC-721 Non-Fungible Token Standard
interfaceId == 0x5b5e139f || // ERC-721 Non-Fungible Token Standard - metadata extension
interfaceId == 0x2a55205a || // ERC-2981 NFT Royalty Standard
interfaceId == 0x49064906 || // ERC-4906 Metadata Update Extension
interfaceId == 0x7f5828d0 || // ERC-173 Contract Ownership Standard
interfaceId == 0x01ffc9a7; // ERC-165 Standard Interface Detection
}
// PRIVATE FUNCTIONS
/// @dev OpenZeppelin hook that is called before any token transfer, including minting and burning
function _beforeTokenTransfer(address from, address to, uint256 id, uint256 quantity) internal virtual override {
if (from != address(0) && from != msg.sender && !operatorAllowed(msg.sender)) {
revert OperatorNotAllowed(msg.sender);
}
super._beforeTokenTransfer(from, to, id, quantity);
}
function operatorAllowed(address operator) internal view returns (bool) {
return
address(OPERATOR_FILTER_REGISTRY).code.length == 0 ||
OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator);
}
}
|
contract PPPCollection is ERC721, Ownable {
/// @notice The OpenSea OperatorFilterRegistry deployment
IOperatorFilterRegistry private constant OPERATOR_FILTER_REGISTRY =
IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);
uint256 private immutable MAX_SUPPLY;
address public royaltyReceiver;
address public minter;
address public metadataContract;
uint256 public royaltyFraction;
uint256 public royaltyDenominator = 100;
/// @notice Count of valid NFTs tracked by this contract
uint256 public totalSupply;
/// @notice Return the baseURI used for computing `tokenURI` values
string public baseURI;
error OnlyMinter();
error OperatorNotAllowed(address operator);
/// @dev This event emits when the metadata of a token is changed. Anyone aware of ERC-4906 can update cached
/// attributes related to a given `tokenId`.
event MetadataUpdate(uint256 tokenId);
/// @dev This event emits when the metadata of a range of tokens is changed. Anyone aware of ERC-4906 can update
/// cached attributes for tokens in the designated range.
event BatchMetadataUpdate(uint256 fromTokenId, uint256 toTokenId);
constructor(
string memory name,
string memory symbol,
string memory baseURI_,
uint256 maxSupply,
address royaltyReceiver_,
uint256 royaltyPercent
) ERC721(name, symbol) {
// CHECKS inputs
require(maxSupply > 0, "Max supply must not be zero");
require(royaltyReceiver_ != address(0), "Royalty receiver must not be the zero address");
require(royaltyPercent <= 100, "Royalty fraction must not be greater than 100%");
// EFFECTS
MAX_SUPPLY = maxSupply;
baseURI = baseURI_;
royaltyReceiver = royaltyReceiver_;
royaltyFraction = royaltyPercent;
// INTERACTIONS
if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {
// Subscribe to the "OpenSea Curated Subscription Address"
OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), 0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);
}
}
modifier onlyMinter() {
if (msg.sender != minter) revert OnlyMinter();
_;
}
// HOLDER FUNCTIONS
/// @notice Enable or disable approval for an `operator` to manage all assets belonging to the sender
/// @dev Emits the ApprovalForAll event. The contract MUST allow multiple operators per owner.
/// @param operator Address to add to the set of authorized operators
/// @param approved True to grant approval, false to revoke approval
function setApprovalForAll(address operator, bool approved) public virtual override {
// CHECKS inputs
if (approved && !operatorAllowed(operator)) revert OperatorNotAllowed(operator);
// CHECKS + EFFECTS
super.setApprovalForAll(operator, approved);
}
// MINTER FUNCTIONS
/// @notice Mint an unclaimed token to the given address
/// @dev Can only be called by the `minter` address
/// @param to The new token owner that will receive the minted token
/// @param tokenId The token being claimed. Reverts if invalid or already claimed.
function mint(address to, uint256 tokenId) external onlyMinter {
// CHECKS inputs
require(tokenId < MAX_SUPPLY, "Invalid token ID");
// CHECKS + EFFECTS (not _safeMint, so no interactions)
_mint(to, tokenId);
// More EFFECTS
unchecked {
totalSupply++;
}
}
// OWNER FUNCTIONS
/// @notice Set the `minter` address
/// @dev Can only be called by the contract `owner`
function setMinter(address minter_) external onlyOwner {
minter = minter_;
}
/// @notice Set the `royaltyReceiver` address
/// @dev Can only be called by the contract `owner`
function setRoyaltyReceiver(address royaltyReceiver_) external onlyOwner {
// CHECKS inputs
require(royaltyReceiver_ != address(0), "Royalty receiver must not be the zero address");
// EFFECTS
royaltyReceiver = royaltyReceiver_;
}
/// @notice Update the royalty fraction
/// @dev Can only be called by the contract `owner`
function setRoyaltyFraction(uint256 royaltyFraction_, uint256 royaltyDenominator_) external onlyOwner {
// CHECKS inputs
require(royaltyDenominator_ != 0, "Royalty denominator must not be zero");
require(royaltyFraction_ <= royaltyDenominator_, "Royalty fraction must not be greater than 100%");
// EFFECTS
royaltyFraction = royaltyFraction_;
royaltyDenominator = royaltyDenominator_;
}
/// @notice Update the baseURI for all metadata
/// @dev Can only be called by the contract `owner`. Emits an ERC-4906 event.
/// @param baseURI_ The new URI base. When specified, token URIs are created by concatenating the baseURI,
/// token ID, and ".json".
function updateBaseURI(string calldata baseURI_) external onlyOwner {
// CHECKS inputs
require(bytes(baseURI_).length > 0, "New base URI must be provided");
// EFFECTS
baseURI = baseURI_;
metadataContract = address(0);
emit BatchMetadataUpdate(0, MAX_SUPPLY - 1);
}
/// @notice Delegate all `tokenURI` calls to another contract
/// @dev Can only be called by the contract `owner`. Emits an ERC-4906 event.
/// @param delegate The contract that will handle `tokenURI` responses
function delegateTokenURIs(address delegate) external onlyOwner {
// CHECKS inputs
require(delegate != address(0), "New metadata delegate must not be the zero address");
require(delegate.code.length > 0, "New metadata delegate must be a contract");
// EFFECTS
baseURI = "";
metadataContract = delegate;
emit BatchMetadataUpdate(0, MAX_SUPPLY - 1);
}
// VIEW FUNCTIONS
/// @notice The URI for the given token
/// @dev Throws if `tokenId` is not valid or has not been minted
function tokenURI(uint256 tokenId) public view override returns (string memory) {
_requireMinted(tokenId);
if (bytes(baseURI).length > 0) {
return string(abi.encodePacked(baseURI, Strings.toString(tokenId), ".json"));
}
if (address(metadataContract) != address(0)) {
return IERC721Metadata(metadataContract).tokenURI(tokenId);
}
revert("tokenURI not configured");
}
/// @notice Return whether the given tokenId has been minted yet
function exists(uint256 tokenId) external view returns (bool) {
return _exists(tokenId);
}
/// @notice Calculate how much royalty is owed and to whom
/// @param salePrice - the sale price of the NFT asset
/// @return receiver - address of where the royalty payment should be sent
/// @return royaltyAmount - the royalty payment amount for salePrice
function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {
receiver = royaltyReceiver;
// Use OpenZeppelin math utils for full precision multiply and divide without overflow
royaltyAmount = Math.mulDiv(salePrice, royaltyFraction, royaltyDenominator, Math.Rounding.Up);
}
/// @notice Query if a contract implements an interface
/// @dev Interface identification is specified in ERC-165. This function uses less than 30,000 gas.
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @return `true` if the contract implements `interfaceID` and `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceId) public pure virtual override returns (bool) {
return
interfaceId == 0x80ac58cd || // ERC-721 Non-Fungible Token Standard
interfaceId == 0x5b5e139f || // ERC-721 Non-Fungible Token Standard - metadata extension
interfaceId == 0x2a55205a || // ERC-2981 NFT Royalty Standard
interfaceId == 0x49064906 || // ERC-4906 Metadata Update Extension
interfaceId == 0x7f5828d0 || // ERC-173 Contract Ownership Standard
interfaceId == 0x01ffc9a7; // ERC-165 Standard Interface Detection
}
// PRIVATE FUNCTIONS
/// @dev OpenZeppelin hook that is called before any token transfer, including minting and burning
function _beforeTokenTransfer(address from, address to, uint256 id, uint256 quantity) internal virtual override {
if (from != address(0) && from != msg.sender && !operatorAllowed(msg.sender)) {
revert OperatorNotAllowed(msg.sender);
}
super._beforeTokenTransfer(from, to, id, quantity);
}
function operatorAllowed(address operator) internal view returns (bool) {
return
address(OPERATOR_FILTER_REGISTRY).code.length == 0 ||
OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator);
}
}
| 35,538
|
188
|
// -------------------------------------------------------------------------/Gets all info for TOY Token `_uid`'s linked NFT./Throws if TOY Token `_uid` does not exist./_uid the UID of the TOY Token to view./ return NFT contract address, External NFT ID.-------------------------------------------------------------------------
|
function getLinkedNft(uint _uid)
external
view
mustExist(_uid)
returns (address, uint)
|
function getLinkedNft(uint _uid)
external
view
mustExist(_uid)
returns (address, uint)
| 29,897
|
6
|
// R4 - 3
|
uint constant internal B41L = 0xE1;
uint constant internal B41H = 0xEC;
|
uint constant internal B41L = 0xE1;
uint constant internal B41H = 0xEC;
| 41,676
|
3
|
// Checks whether the amount of tokens sold against the amount of tokens requested/is within a certain threshold. This ensures the caller gets a fair deal when/performing any token fee abstraction. Threshold is 95%. If fee abstraction costs more than/5% of the total transaction, we return false./requestedSellAmount The amount the user requested, or sent in to a payable function/tokenAmountSold The amount of the token that was sold after fee abstraction/ return bool of whether this is within an acceptable threshold
|
function isAcceptableThreshold(uint256 requestedSellAmount, uint256 tokenAmountSold)
internal
pure
returns (bool);
|
function isAcceptableThreshold(uint256 requestedSellAmount, uint256 tokenAmountSold)
internal
pure
returns (bool);
| 50,083
|
90
|
// if the auction was cancelled, everyone should be allowed to withdraw their funds
|
withdrawalAccount = msg.sender;
withdrawalAmount = auction.fundsByBidder(withdrawalAccount);
|
withdrawalAccount = msg.sender;
withdrawalAmount = auction.fundsByBidder(withdrawalAccount);
| 56,231
|
432
|
// Get the number of available onchain withdrawal slots./ return The number of slots available for withdrawals
|
function getNumAvailableWithdrawalSlots(
)
external
view
returns (uint);
|
function getNumAvailableWithdrawalSlots(
)
external
view
returns (uint);
| 26,542
|
0
|
// IERC1155721Inventory interface. /
|
interface IERC1155721Inventory is IERC1155Inventory, IERC1155, IERC721 {
/// @dev See {IERC721-isApprovedForAll(address,address)} and {IERC1155-isApprovedForAll(address,address)}
function isApprovedForAll(address tokenOwner, address operator) external view override(IERC721, IERC1155) returns (bool);
/// @dev See {IERC721-isApprovedForAll(address,address)} and {IERC1155-isApprovedForAll(address,address)}
function setApprovalForAll(address operator, bool approved) external override(IERC721, IERC1155);
/// @dev See {IERC721-ownerOf(uint256)} and {IERC1155Inventory-ownerOf(uint256)}.
function ownerOf(uint256 nftId) external view override(IERC721, IERC1155Inventory) returns (address);
/**
* @notice this documentation overrides {IERC1155Inventory-safeTransferFrom(address,address,uint256,uint256,bytes)}.
* Safely transfers some token.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `id` does not represent a token.
* @dev Reverts if `id` represents a non-fungible token and `value` is not 1.
* @dev Reverts if `id` represents a non-fungible token and is not owned by `from`.
* @dev Reverts if `id` represents a fungible token and `value` is 0.
* @dev Reverts if `id` represents a fungible token and `from` has an insufficient balance.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155received} fails or is refused.
* @dev Resets the ERC721 single token approval if `id` represents a non-fungible token.
* @dev Emits an {IERC721-Transfer} event if `id` represents a non-fungible token.
* @dev Emits an {IERC1155-TransferSingle} event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param id Identifier of the token to transfer.
* @param value Amount of token to transfer.
* @param data Optional data to pass to the receiver contract.
*/
// function safeTransferFrom(
// address from,
// address to,
// uint256 id,
// uint256 value,
// bytes calldata data
// ) external;
/**
* @notice this documentation overrides {IERC1155Inventory-safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)}.
* Safely transfers a batch of tokens.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if one of `ids` does not represent a token.
* @dev Reverts if one of `ids` represents a non-fungible token and `value` is not 1.
* @dev Reverts if one of `ids` represents a non-fungible token and is not owned by `from`.
* @dev Reverts if one of `ids` represents a fungible token and `value` is 0.
* @dev Reverts if one of `ids` represents a fungible token and `from` has an insufficient balance.
* @dev Reverts if one of `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155batchReceived} fails or is refused.
* @dev Resets the ERC721 single token approval for each transferred non-fungible token.
* @dev Emits an {IERC721-Transfer} event for each transferred non-fungible token.
* @dev Emits an {IERC1155-TransferBatch} event.
* @param from Current tokens owner.
* @param to Address of the new tokens owner.
* @param ids Identifiers of the tokens to transfer.
* @param values Amounts of tokens to transfer.
* @param data Optional data to pass to the receiver contract.
*/
// function safeBatchTransferFrom(
// address from,
// address to,
// uint256[] calldata ids,
// uint256[] calldata values,
// bytes calldata data
// ) external;
/**
* @notice this documentation overrides its IERC721 counterpart.
* Unsafely transfers a Non-Fungible Token.
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `nftId` is not owned by `from`.
* @dev Reverts if `to` is an IERC1155TokenReceiver contract which refuses the receiver call.
* @dev Resets the ERC721 single token approval.
* @dev Emits an {IERC721-Transfer} event.
* @dev Emits an {IERC1155-TransferSingle} event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param nftId Identifier of the token to transfer.
*/
// function transferFrom(
// address from,
// address to,
// uint256 nftId
// ) external;
/**
* @notice this documentation overrides its IERC721 counterpart.
* Safely transfers a Non-Fungible Token.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `nftId` is not owned by `from`.
* @dev Reverts if `to` is a contract which does not implement IERC1155TokenReceiver or IERC721Receiver.
* @dev Reverts if `to` is an IERC1155TokenReceiver or IERC721Receiver contract which refuses the transfer.
* @dev Resets the ERC721 single token approval.
* @dev Emits an {IERC721-Transfer} event.
* @dev Emits an {IERC1155-TransferSingle} event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param nftId Identifier of the token to transfer.
*/
// function safeTransferFrom(
// address from,
// address to,
// uint256 nftId
// ) external;
/**
* @notice this documentation overrides its IERC721 counterpart.
* Safely transfers a Non-Fungible Token.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `nftId` is not owned by `from`.
* @dev Reverts if `to` is a contract which does not implement IERC1155TokenReceiver or IERC721Receiver.
* @dev Reverts if `to` is an IERC1155TokenReceiver or IERC721Receiver contract which refuses the transfer.
* @dev Resets the ERC721 single token approval.
* @dev Emits an {IERC721-Transfer} event.
* @dev Emits an {IERC1155-TransferSingle} event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param nftId Identifier of the token to transfer.
* @param data Optional data to pass to the receiver contract.
*/
// function safeTransferFrom(
// address from,
// address to,
// uint256 nftId,
// bytes calldata data
// ) external;
}
|
interface IERC1155721Inventory is IERC1155Inventory, IERC1155, IERC721 {
/// @dev See {IERC721-isApprovedForAll(address,address)} and {IERC1155-isApprovedForAll(address,address)}
function isApprovedForAll(address tokenOwner, address operator) external view override(IERC721, IERC1155) returns (bool);
/// @dev See {IERC721-isApprovedForAll(address,address)} and {IERC1155-isApprovedForAll(address,address)}
function setApprovalForAll(address operator, bool approved) external override(IERC721, IERC1155);
/// @dev See {IERC721-ownerOf(uint256)} and {IERC1155Inventory-ownerOf(uint256)}.
function ownerOf(uint256 nftId) external view override(IERC721, IERC1155Inventory) returns (address);
/**
* @notice this documentation overrides {IERC1155Inventory-safeTransferFrom(address,address,uint256,uint256,bytes)}.
* Safely transfers some token.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `id` does not represent a token.
* @dev Reverts if `id` represents a non-fungible token and `value` is not 1.
* @dev Reverts if `id` represents a non-fungible token and is not owned by `from`.
* @dev Reverts if `id` represents a fungible token and `value` is 0.
* @dev Reverts if `id` represents a fungible token and `from` has an insufficient balance.
* @dev Reverts if `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155received} fails or is refused.
* @dev Resets the ERC721 single token approval if `id` represents a non-fungible token.
* @dev Emits an {IERC721-Transfer} event if `id` represents a non-fungible token.
* @dev Emits an {IERC1155-TransferSingle} event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param id Identifier of the token to transfer.
* @param value Amount of token to transfer.
* @param data Optional data to pass to the receiver contract.
*/
// function safeTransferFrom(
// address from,
// address to,
// uint256 id,
// uint256 value,
// bytes calldata data
// ) external;
/**
* @notice this documentation overrides {IERC1155Inventory-safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)}.
* Safely transfers a batch of tokens.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if one of `ids` does not represent a token.
* @dev Reverts if one of `ids` represents a non-fungible token and `value` is not 1.
* @dev Reverts if one of `ids` represents a non-fungible token and is not owned by `from`.
* @dev Reverts if one of `ids` represents a fungible token and `value` is 0.
* @dev Reverts if one of `ids` represents a fungible token and `from` has an insufficient balance.
* @dev Reverts if one of `to` is a contract and the call to {IERC1155TokenReceiver-onERC1155batchReceived} fails or is refused.
* @dev Resets the ERC721 single token approval for each transferred non-fungible token.
* @dev Emits an {IERC721-Transfer} event for each transferred non-fungible token.
* @dev Emits an {IERC1155-TransferBatch} event.
* @param from Current tokens owner.
* @param to Address of the new tokens owner.
* @param ids Identifiers of the tokens to transfer.
* @param values Amounts of tokens to transfer.
* @param data Optional data to pass to the receiver contract.
*/
// function safeBatchTransferFrom(
// address from,
// address to,
// uint256[] calldata ids,
// uint256[] calldata values,
// bytes calldata data
// ) external;
/**
* @notice this documentation overrides its IERC721 counterpart.
* Unsafely transfers a Non-Fungible Token.
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `nftId` is not owned by `from`.
* @dev Reverts if `to` is an IERC1155TokenReceiver contract which refuses the receiver call.
* @dev Resets the ERC721 single token approval.
* @dev Emits an {IERC721-Transfer} event.
* @dev Emits an {IERC1155-TransferSingle} event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param nftId Identifier of the token to transfer.
*/
// function transferFrom(
// address from,
// address to,
// uint256 nftId
// ) external;
/**
* @notice this documentation overrides its IERC721 counterpart.
* Safely transfers a Non-Fungible Token.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `nftId` is not owned by `from`.
* @dev Reverts if `to` is a contract which does not implement IERC1155TokenReceiver or IERC721Receiver.
* @dev Reverts if `to` is an IERC1155TokenReceiver or IERC721Receiver contract which refuses the transfer.
* @dev Resets the ERC721 single token approval.
* @dev Emits an {IERC721-Transfer} event.
* @dev Emits an {IERC1155-TransferSingle} event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param nftId Identifier of the token to transfer.
*/
// function safeTransferFrom(
// address from,
// address to,
// uint256 nftId
// ) external;
/**
* @notice this documentation overrides its IERC721 counterpart.
* Safely transfers a Non-Fungible Token.
* @dev Reverts if `to` is the zero address.
* @dev Reverts if the sender is not approved.
* @dev Reverts if `nftId` is not owned by `from`.
* @dev Reverts if `to` is a contract which does not implement IERC1155TokenReceiver or IERC721Receiver.
* @dev Reverts if `to` is an IERC1155TokenReceiver or IERC721Receiver contract which refuses the transfer.
* @dev Resets the ERC721 single token approval.
* @dev Emits an {IERC721-Transfer} event.
* @dev Emits an {IERC1155-TransferSingle} event.
* @param from Current token owner.
* @param to Address of the new token owner.
* @param nftId Identifier of the token to transfer.
* @param data Optional data to pass to the receiver contract.
*/
// function safeTransferFrom(
// address from,
// address to,
// uint256 nftId,
// bytes calldata data
// ) external;
}
| 26,976
|
95
|
// IERC721 and IERC721Upgradeable returns the same interface ID Should restrict IERC721Upgradeable cause unknown contract can upgrade and integrate malicious implementation
|
require(
_skip || IERC721(_contractNFT).supportsInterface(
type(IERC721).interfaceId
),
"SporesRegistry: Invalid interface"
);
supportedNFT721[_contractNFT] = true;
|
require(
_skip || IERC721(_contractNFT).supportsInterface(
type(IERC721).interfaceId
),
"SporesRegistry: Invalid interface"
);
supportedNFT721[_contractNFT] = true;
| 67,048
|
191
|
// View how much the Vault would like to pull back from the Strategy,based on its present performance (since its last report). Can be used todetermine expectedReturn in your Strategy. /
|
function debtOutstanding() external view returns (uint256);
|
function debtOutstanding() external view returns (uint256);
| 3,143
|
13
|
// Tokens user will get according to the price /
|
) internal view returns (uint256) {
return ((_amount * tokenDecimal * (10 ** 8)) /
((10 ** 8) * uint256(_price)));
}
|
) internal view returns (uint256) {
return ((_amount * tokenDecimal * (10 ** 8)) /
((10 ** 8) * uint256(_price)));
}
| 23,713
|
7
|
// The easiest way to bubble the revert reason is using memory via assembly solhint-disable no-inline-assembly/ @solidity memory-safe-assembly
|
assembly {
let returndata_size := mload(returnedData)
revert(add(32, returnedData), returndata_size)
}
|
assembly {
let returndata_size := mload(returnedData)
revert(add(32, returnedData), returndata_size)
}
| 22,976
|
107
|
// Spend tokens to acquire ETH /
|
function performSell(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint256 amountToFill,
uint8 v,
bytes32 r,
bytes32 s
|
function performSell(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint256 amountToFill,
uint8 v,
bytes32 r,
bytes32 s
| 40,521
|
45
|
// require there to be unverified assets
|
require(unverifiedAssets.length > 0, "no assets unverified");
|
require(unverifiedAssets.length > 0, "no assets unverified");
| 49,665
|
33
|
// pragma solidity ^0.4.13; // import "ds-auth/auth.sol"; // import "ds-note/note.sol"; /
|
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped);
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
|
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped);
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
| 2,322
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.