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
17
// transfer the token from address of this contract to address of the user (executing the withdrawToken() function)
tokenContract.transfer(to, _amount);
tokenContract.transfer(to, _amount);
8,951
288
// ============ OWNER-ONLY ADMIN FUNCTIONS ============
function ownerMint(address _receiver, uint256 _numberOfDrivers) external onlyOwner
function ownerMint(address _receiver, uint256 _numberOfDrivers) external onlyOwner
36,670
142
// Take a KLIMA-BCT LP mint, with depositor being msg.sender,/
function takeKLIMABCTMint() external nonReentrant { unstakeKLIMA(); createKLIMABCTLP(); uint256 balanceLP = IERC20(KLIMABCTLPtokens).balanceOf(address(this)); require(balanceLP > 0, "KLIMAZap : No KLIMA-BCT LP tokens balance"); uint maxprice = IKLIMABondDepository(KLIMABCTBond).bondPrice(); IKLIMABondDepository(KLIMABCTBond).deposit(balanceLP,maxprice,msg.sender); }
function takeKLIMABCTMint() external nonReentrant { unstakeKLIMA(); createKLIMABCTLP(); uint256 balanceLP = IERC20(KLIMABCTLPtokens).balanceOf(address(this)); require(balanceLP > 0, "KLIMAZap : No KLIMA-BCT LP tokens balance"); uint maxprice = IKLIMABondDepository(KLIMABCTBond).bondPrice(); IKLIMABondDepository(KLIMABCTBond).deposit(balanceLP,maxprice,msg.sender); }
17,032
3
// Struct storing variables used in calculation in removeLiquidityImbalance function to avoid stack too deep error
struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; LPToken lpToken; uint256 totalSupply; uint256 preciseA; uint256 baseVirtualPrice; uint256[] scaleMultipliers; uint256[] newBalances; }
struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; LPToken lpToken; uint256 totalSupply; uint256 preciseA; uint256 baseVirtualPrice; uint256[] scaleMultipliers; uint256[] newBalances; }
56,596
6
// Convert the given slot identifier to strike price./ident The slot identifier, can be with or without the offset.
function getStrike(uint ident) public pure returns (uint) { uint slot = ident & ((1 << 16) - 1); // only consider the last 16 bits uint prefix = slot % 900; // maximum value is 899 uint magnitude = slot / 900; // maximum value is 72 if (magnitude == 0) { require(prefix >= 800, 'bad prefix'); return prefix - 800; } else { return (100 + prefix) * (10**(magnitude - 1)); // never overflow } }
function getStrike(uint ident) public pure returns (uint) { uint slot = ident & ((1 << 16) - 1); // only consider the last 16 bits uint prefix = slot % 900; // maximum value is 899 uint magnitude = slot / 900; // maximum value is 72 if (magnitude == 0) { require(prefix >= 800, 'bad prefix'); return prefix - 800; } else { return (100 + prefix) * (10**(magnitude - 1)); // never overflow } }
14,264
20
// Global constructor – these variables will not change with further proxy deploys/Marked as an initializer to prevent storage being used of base implementation. Can only be init'd by a proxy./_zoraERC721TransferHelper Transfer helper/_factoryUpgradeGate Factory upgrade gate address/_marketFilterDAOAddress Market filter DAO address/_mintFeeAmount Mint fee amount in wei/_mintFeeRecipient Mint fee recipient address
constructor( address _zoraERC721TransferHelper, IFactoryUpgradeGate _factoryUpgradeGate, address _marketFilterDAOAddress, uint256 _mintFeeAmount, address payable _mintFeeRecipient
constructor( address _zoraERC721TransferHelper, IFactoryUpgradeGate _factoryUpgradeGate, address _marketFilterDAOAddress, uint256 _mintFeeAmount, address payable _mintFeeRecipient
10,180
2
// compute total voting power
Gov.setEquityTokenTotalVotingPower(_t, token, shareCapital); transitionTo(state);
Gov.setEquityTokenTotalVotingPower(_t, token, shareCapital); transitionTo(state);
25,603
2
// Address of the RariFundManager. /
address private _rariFundManagerContract;
address private _rariFundManagerContract;
6,411
7
// Minting
function mint( address to, uint256 tokenId, string memory uri
function mint( address to, uint256 tokenId, string memory uri
27,179
3
// Transfer `amount` tokens from `msg.sender` to `dst`dst The address of the destination accountamount The number of tokens to transfer return success Whether or not the transfer succeeded/
function transfer(address dst, uint256 amount) external returns (bool success);
function transfer(address dst, uint256 amount) external returns (bool success);
24,023
1
// failedWithdrawalIndexByWithdrawalIndex Chiado network deployed for the shapella the contract at commit https:github.com/gnosischain/deposit-contract/commit/13e155500b626612844e3d0fccc11b02b11ea785 This contract version was latter replaced with the contract at commit https:github.com/gnosischain/deposit-contract/pull/45/commits/8fe75d23497d720b12af9e75790a616dfb64ca6b The latter version leaves some storage slots orphan, which may cause problems in future updates This variables is added once to set storage slots 69,70,71 and map(68) values back to zero SBCDepositContract │ withdrawableAmount │67│t_mapping(t_address,t_uint256) │32 │ SBCDepositContractOld│ failedWithdrawalIndexByWithdrawalIndex │68│ t_mapping(t_uint64,t_uint256) │32 │ SBCDepositContractOld│ numberOfFailedWithdrawals│69│ t_uint256 │32 │ SBCDepositContractOld│nextWithdrawalIndex │70│ t_uint64│ 8 │ SBCDepositContractOld│failedWithdrawalsPointer│71│ t_uint256 │32 |
mapping(uint64 => uint256) public _deprecated_map_up_to_nextWithdrawalIndex; uint256 public _deprecated_slot_69; uint64 public _deprecated_slot_70_nextWithdrawalIndex; uint256 private _deprecated_slot_71;
mapping(uint64 => uint256) public _deprecated_map_up_to_nextWithdrawalIndex; uint256 public _deprecated_slot_69; uint64 public _deprecated_slot_70_nextWithdrawalIndex; uint256 private _deprecated_slot_71;
12,806
90
// if(n == 0 || n==1) { n = 0; } else if(n == 2 || n==3) { n = 1; }
postition = updatexGoldReferrer_FirstLevel(userAddress, users[referrerAddress].xGoldMatrix[level].secondLevelReferrals[n], level); postition = updatexGoldReferrer_SecondLevel(userAddress, users[referrerAddress].xGoldMatrix[level].secondLevelReferrals[n], level, postition); postition = updatexGoldReferrer_ThirdLevel(userAddress, users[referrerAddress].xGoldMatrix[level].secondLevelReferrals[n], level, postition); postition = updatexGoldReferrer_ForthLevel(userAddress, users[referrerAddress].xGoldMatrix[level].secondLevelReferrals[n], level, postition);
postition = updatexGoldReferrer_FirstLevel(userAddress, users[referrerAddress].xGoldMatrix[level].secondLevelReferrals[n], level); postition = updatexGoldReferrer_SecondLevel(userAddress, users[referrerAddress].xGoldMatrix[level].secondLevelReferrals[n], level, postition); postition = updatexGoldReferrer_ThirdLevel(userAddress, users[referrerAddress].xGoldMatrix[level].secondLevelReferrals[n], level, postition); postition = updatexGoldReferrer_ForthLevel(userAddress, users[referrerAddress].xGoldMatrix[level].secondLevelReferrals[n], level, postition);
5,517
71
// We ensure the minimum borrow rate >= DSR / (1 - reserve factor)
baseRatePerBlock = dsrPerBlock().mul(1e18).div(assumedOneMinusReserveFactorMantissa);
baseRatePerBlock = dsrPerBlock().mul(1e18).div(assumedOneMinusReserveFactorMantissa);
34,817
3
// For tracking the mercenaries visual traits
mapping (uint256 => bytes16[]) public visualTraits;
mapping (uint256 => bytes16[]) public visualTraits;
20,081
37
// Calculate the total platform token balance (i.e. 3CRV) that exist inthis contract or is staked in the Gauge (or in other words, the totalamount platform tokens we own).return totalPTokens Total amount of platform tokens in native decimals /
function _getTotalPTokens() internal view returns ( uint256 contractPTokens, uint256 gaugePTokens, uint256 totalPTokens )
function _getTotalPTokens() internal view returns ( uint256 contractPTokens, uint256 gaugePTokens, uint256 totalPTokens )
34,201
148
// LeekToken with Governance.
contract LeekToken is ERC20("LeekToken", "LEEK"), Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // @notice Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice LeekToken constructor with total supply 999999 Billion */ constructor() { _setupDecimals(9); uint256 totalSupply = 999999999999999 * 1e9; _mint(address(0xa9c95Ed01f85706Cac4206d34d61ad3b422F77D9), totalSupply); } /** * @notice Burn _amount of token * @param _amount of token to burn */ function burn(uint256 _amount) public { _burn(_msgSender(), _amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal override { _moveDelegates(_delegates[from], _delegates[to], amount); } /** * @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), "delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "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, "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 Leek (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, "_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 LeekToken is ERC20("LeekToken", "LEEK"), Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // @notice Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice LeekToken constructor with total supply 999999 Billion */ constructor() { _setupDecimals(9); uint256 totalSupply = 999999999999999 * 1e9; _mint(address(0xa9c95Ed01f85706Cac4206d34d61ad3b422F77D9), totalSupply); } /** * @notice Burn _amount of token * @param _amount of token to burn */ function burn(uint256 _amount) public { _burn(_msgSender(), _amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal override { _moveDelegates(_delegates[from], _delegates[to], amount); } /** * @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), "delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "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, "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 Leek (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, "_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; } }
62,358
1
// Emitted when relays are added by a relayManager
event RelayWorkersAdded( address indexed relayManager, address[] newRelayWorkers, uint256 workersCount );
event RelayWorkersAdded( address indexed relayManager, address[] newRelayWorkers, uint256 workersCount );
40,928
451
// set warmup period for new stakers _warmupPeriod uint /
function setWarmup(uint256 _warmupPeriod) external onlyOwner { warmupPeriod = _warmupPeriod; }
function setWarmup(uint256 _warmupPeriod) external onlyOwner { warmupPeriod = _warmupPeriod; }
31,654
18
// Checks if the specified Tier exists tier_ The Tier that is being checked /
function tierExists(uint256 tier_) external view returns (bool);
function tierExists(uint256 tier_) external view returns (bool);
40,963
41
// Crowdsale expired
if (now > end) { throw; }
if (now > end) { throw; }
26,894
21
// Mint a new token. recipient recipient address. tokenURI token URI of a new token. /
function _mint( address recipient, string memory tokenURI ) internal virtual
function _mint( address recipient, string memory tokenURI ) internal virtual
30,144
13
// determine if addr has role _operator address _role the name of the rolereturn bool /
function hasRole(address _operator, string _role) public view returns (bool)
function hasRole(address _operator, string _role) public view returns (bool)
18,713
108
// Array holding all stakes
Stake[] public stakes;
Stake[] public stakes;
18,009
198
// MasterChef is the master of Sashimi. He can make Sashimi and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once SASHIMI is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SASHIMIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSashimiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSashimiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SASHIMIs to distribute per block. uint256 lastRewardBlock; // Last block number that SASHIMIs distribution occurs. uint256 accSashimiPerShare; // Accumulated SASHIMIs per share, times 1e12. See below. } // The SASHIMI TOKEN! SashimiToken public sashimi; // Block number when bonus SASHIMI period ends. uint256 public bonusEndBlock; // SASHIMI tokens created per block. uint256 public sashimiPerBlock; // Bonus muliplier for early sashimi makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SASHIMI mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( SashimiToken _sashimi, uint256 _sashimiPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { sashimi = _sashimi; sashimiPerBlock = _sashimiPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSashimiPerShare: 0 })); } // Update the given pool's SASHIMI allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending SASHIMIs on frontend. function pendingSashimi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSashimiPerShare = pool.accSashimiPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sashimiReward = multiplier.mul(sashimiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSashimiPerShare = accSashimiPerShare.add(sashimiReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSashimiPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sashimiReward = multiplier.mul(sashimiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sashimi.mint(address(this), sashimiReward); pool.accSashimiPerShare = pool.accSashimiPerShare.add(sashimiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SASHIMI allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSashimiPerShare).div(1e12).sub(user.rewardDebt); safeSashimiTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSashimiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSashimiPerShare).div(1e12).sub(user.rewardDebt); safeSashimiTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSashimiPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sashimi transfer function, just in case if rounding error causes pool to not have enough SASHIMIs. function safeSashimiTransfer(address _to, uint256 _amount) internal { uint256 sashimiBal = sashimi.balanceOf(address(this)); if (_amount > sashimiBal) { sashimi.transfer(_to, sashimiBal); } else { sashimi.transfer(_to, _amount); } } }
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SASHIMIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSashimiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSashimiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SASHIMIs to distribute per block. uint256 lastRewardBlock; // Last block number that SASHIMIs distribution occurs. uint256 accSashimiPerShare; // Accumulated SASHIMIs per share, times 1e12. See below. } // The SASHIMI TOKEN! SashimiToken public sashimi; // Block number when bonus SASHIMI period ends. uint256 public bonusEndBlock; // SASHIMI tokens created per block. uint256 public sashimiPerBlock; // Bonus muliplier for early sashimi makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SASHIMI mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( SashimiToken _sashimi, uint256 _sashimiPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { sashimi = _sashimi; sashimiPerBlock = _sashimiPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSashimiPerShare: 0 })); } // Update the given pool's SASHIMI allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending SASHIMIs on frontend. function pendingSashimi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSashimiPerShare = pool.accSashimiPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sashimiReward = multiplier.mul(sashimiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSashimiPerShare = accSashimiPerShare.add(sashimiReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSashimiPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sashimiReward = multiplier.mul(sashimiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sashimi.mint(address(this), sashimiReward); pool.accSashimiPerShare = pool.accSashimiPerShare.add(sashimiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SASHIMI allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSashimiPerShare).div(1e12).sub(user.rewardDebt); safeSashimiTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSashimiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSashimiPerShare).div(1e12).sub(user.rewardDebt); safeSashimiTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSashimiPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sashimi transfer function, just in case if rounding error causes pool to not have enough SASHIMIs. function safeSashimiTransfer(address _to, uint256 _amount) internal { uint256 sashimiBal = sashimi.balanceOf(address(this)); if (_amount > sashimiBal) { sashimi.transfer(_to, sashimiBal); } else { sashimi.transfer(_to, _amount); } } }
17,372
16
// Allows contract `owner` to set `mintCost`. /
function ownerSetMintCost(uint256 _mintCost) external payable ownerHasPermission(Permissions.setMintCost) onlyOwner
function ownerSetMintCost(uint256 _mintCost) external payable ownerHasPermission(Permissions.setMintCost) onlyOwner
25,923
38
// EAS - Ethereum Attestation Service /
contract EAS is IEAS { error AccessDenied(); error AlreadyRevoked(); error InvalidAttestation(); error InvalidExpirationTime(); error InvalidOffset(); error InvalidRegistry(); error InvalidSchema(); error InvalidVerifier(); error NotFound(); error NotPayable(); string public constant VERSION = "0.8"; // A terminator used when concatenating and hashing multiple fields. string private constant HASH_TERMINATOR = "@"; // The AS global registry. IASRegistry private immutable _asRegistry; // The EIP712 verifier used to verify signed attestations. IEIP712Verifier private immutable _eip712Verifier; // A mapping between attestations and their related attestations. mapping(bytes32 => bytes32[]) private _relatedAttestations; // A mapping between an account and its received attestations. mapping(address => mapping(bytes32 => bytes32[])) private _receivedAttestations; // A mapping between an account and its sent attestations. mapping(address => mapping(bytes32 => bytes32[])) private _sentAttestations; // A mapping between a schema and its attestations. mapping(bytes32 => bytes32[]) private _schemaAttestations; // The global mapping between attestations and their UUIDs. mapping(bytes32 => Attestation) private _db; // The global counter for the total number of attestations. uint256 private _attestationsCount; /** * @dev Creates a new EAS instance. * * @param registry The address of the global AS registry. * @param verifier The address of the EIP712 verifier. */ constructor(IASRegistry registry, IEIP712Verifier verifier) { if (address(registry) == address(0x0)) { revert InvalidRegistry(); } if (address(verifier) == address(0x0)) { revert InvalidVerifier(); } _asRegistry = registry; _eip712Verifier = verifier; } /** * @inheritdoc IEAS */ function getASRegistry() external view returns (IASRegistry) { return _asRegistry; } /** * @inheritdoc IEAS */ function getEIP712Verifier() external view returns (IEIP712Verifier) { return _eip712Verifier; } /** * @inheritdoc IEAS */ function getAttestationsCount() external view returns (uint256) { return _attestationsCount; } /** * @inheritdoc IEAS */ function attest( address recipient, bytes32 schema, uint256 expirationTime, bytes32 refUUID, bytes calldata data ) public payable virtual returns (bytes32) { return _attest(recipient, schema, expirationTime, refUUID, data, msg.sender); } /** * @inheritdoc IEAS */ function attestByDelegation( address recipient, bytes32 schema, uint256 expirationTime, bytes32 refUUID, bytes calldata data, address attester, uint8 v, bytes32 r, bytes32 s ) public payable virtual returns (bytes32) { _eip712Verifier.attest(recipient, schema, expirationTime, refUUID, data, attester, v, r, s); return _attest(recipient, schema, expirationTime, refUUID, data, attester); } /** * @inheritdoc IEAS */ function revoke(bytes32 uuid) public virtual { return _revoke(uuid, msg.sender); } /** * @inheritdoc IEAS */ function revokeByDelegation( bytes32 uuid, address attester, uint8 v, bytes32 r, bytes32 s ) public virtual { _eip712Verifier.revoke(uuid, attester, v, r, s); _revoke(uuid, attester); } /** * @inheritdoc IEAS */ function getAttestation(bytes32 uuid) external view returns (Attestation memory) { return _db[uuid]; } /** * @inheritdoc IEAS */ function isAttestationValid(bytes32 uuid) public view returns (bool) { return _db[uuid].uuid != 0; } /** * @inheritdoc IEAS */ function getReceivedAttestationUUIDs( address recipient, bytes32 schema, uint256 start, uint256 length, bool reverseOrder ) external view returns (bytes32[] memory) { return _sliceUUIDs(_receivedAttestations[recipient][schema], start, length, reverseOrder); } /** * @inheritdoc IEAS */ function getReceivedAttestationUUIDsCount(address recipient, bytes32 schema) external view returns (uint256) { return _receivedAttestations[recipient][schema].length; } /** * @inheritdoc IEAS */ function getSentAttestationUUIDs( address attester, bytes32 schema, uint256 start, uint256 length, bool reverseOrder ) external view returns (bytes32[] memory) { return _sliceUUIDs(_sentAttestations[attester][schema], start, length, reverseOrder); } /** * @inheritdoc IEAS */ function getSentAttestationUUIDsCount(address recipient, bytes32 schema) external view returns (uint256) { return _sentAttestations[recipient][schema].length; } /** * @inheritdoc IEAS */ function getRelatedAttestationUUIDs( bytes32 uuid, uint256 start, uint256 length, bool reverseOrder ) external view returns (bytes32[] memory) { return _sliceUUIDs(_relatedAttestations[uuid], start, length, reverseOrder); } /** * @inheritdoc IEAS */ function getRelatedAttestationUUIDsCount(bytes32 uuid) external view returns (uint256) { return _relatedAttestations[uuid].length; } /** * @inheritdoc IEAS */ function getSchemaAttestationUUIDs( bytes32 schema, uint256 start, uint256 length, bool reverseOrder ) external view returns (bytes32[] memory) { return _sliceUUIDs(_schemaAttestations[schema], start, length, reverseOrder); } /** * @inheritdoc IEAS */ function getSchemaAttestationUUIDsCount(bytes32 schema) external view returns (uint256) { return _schemaAttestations[schema].length; } /** * @dev Attests to a specific AS. * * @param recipient The recipient of the attestation. * @param schema The UUID of the AS. * @param expirationTime The expiration time of the attestation. * @param refUUID An optional related attestation's UUID. * @param data Additional custom data. * @param attester The attesting account. * * @return The UUID of the new attestation. */ function _attest( address recipient, bytes32 schema, uint256 expirationTime, bytes32 refUUID, bytes calldata data, address attester ) private returns (bytes32) { if (expirationTime <= block.timestamp) { revert InvalidExpirationTime(); } ASRecord memory asRecord = _asRegistry.getAS(schema); if (asRecord.uuid == EMPTY_UUID) { revert InvalidSchema(); } IASResolver resolver = asRecord.resolver; if (address(resolver) != address(0x0)) { if (msg.value != 0 && !resolver.isPayable()) { revert NotPayable(); } if (!resolver.resolve{value: msg.value}(recipient, asRecord.schema, data, expirationTime, attester)) { revert InvalidAttestation(); } } Attestation memory attestation = Attestation({ uuid: EMPTY_UUID, schema: schema, recipient: recipient, attester: attester, time: block.timestamp, expirationTime: expirationTime, revocationTime: 0, refUUID: refUUID, data: data }); bytes32 uuid = _getUUID(attestation); attestation.uuid = uuid; _receivedAttestations[recipient][schema].push(uuid); _sentAttestations[attester][schema].push(uuid); _schemaAttestations[schema].push(uuid); _db[uuid] = attestation; _attestationsCount++; if (refUUID != 0) { if (!isAttestationValid(refUUID)) { revert NotFound(); } _relatedAttestations[refUUID].push(uuid); } emit Attested(recipient, attester, uuid, schema); return uuid; }
contract EAS is IEAS { error AccessDenied(); error AlreadyRevoked(); error InvalidAttestation(); error InvalidExpirationTime(); error InvalidOffset(); error InvalidRegistry(); error InvalidSchema(); error InvalidVerifier(); error NotFound(); error NotPayable(); string public constant VERSION = "0.8"; // A terminator used when concatenating and hashing multiple fields. string private constant HASH_TERMINATOR = "@"; // The AS global registry. IASRegistry private immutable _asRegistry; // The EIP712 verifier used to verify signed attestations. IEIP712Verifier private immutable _eip712Verifier; // A mapping between attestations and their related attestations. mapping(bytes32 => bytes32[]) private _relatedAttestations; // A mapping between an account and its received attestations. mapping(address => mapping(bytes32 => bytes32[])) private _receivedAttestations; // A mapping between an account and its sent attestations. mapping(address => mapping(bytes32 => bytes32[])) private _sentAttestations; // A mapping between a schema and its attestations. mapping(bytes32 => bytes32[]) private _schemaAttestations; // The global mapping between attestations and their UUIDs. mapping(bytes32 => Attestation) private _db; // The global counter for the total number of attestations. uint256 private _attestationsCount; /** * @dev Creates a new EAS instance. * * @param registry The address of the global AS registry. * @param verifier The address of the EIP712 verifier. */ constructor(IASRegistry registry, IEIP712Verifier verifier) { if (address(registry) == address(0x0)) { revert InvalidRegistry(); } if (address(verifier) == address(0x0)) { revert InvalidVerifier(); } _asRegistry = registry; _eip712Verifier = verifier; } /** * @inheritdoc IEAS */ function getASRegistry() external view returns (IASRegistry) { return _asRegistry; } /** * @inheritdoc IEAS */ function getEIP712Verifier() external view returns (IEIP712Verifier) { return _eip712Verifier; } /** * @inheritdoc IEAS */ function getAttestationsCount() external view returns (uint256) { return _attestationsCount; } /** * @inheritdoc IEAS */ function attest( address recipient, bytes32 schema, uint256 expirationTime, bytes32 refUUID, bytes calldata data ) public payable virtual returns (bytes32) { return _attest(recipient, schema, expirationTime, refUUID, data, msg.sender); } /** * @inheritdoc IEAS */ function attestByDelegation( address recipient, bytes32 schema, uint256 expirationTime, bytes32 refUUID, bytes calldata data, address attester, uint8 v, bytes32 r, bytes32 s ) public payable virtual returns (bytes32) { _eip712Verifier.attest(recipient, schema, expirationTime, refUUID, data, attester, v, r, s); return _attest(recipient, schema, expirationTime, refUUID, data, attester); } /** * @inheritdoc IEAS */ function revoke(bytes32 uuid) public virtual { return _revoke(uuid, msg.sender); } /** * @inheritdoc IEAS */ function revokeByDelegation( bytes32 uuid, address attester, uint8 v, bytes32 r, bytes32 s ) public virtual { _eip712Verifier.revoke(uuid, attester, v, r, s); _revoke(uuid, attester); } /** * @inheritdoc IEAS */ function getAttestation(bytes32 uuid) external view returns (Attestation memory) { return _db[uuid]; } /** * @inheritdoc IEAS */ function isAttestationValid(bytes32 uuid) public view returns (bool) { return _db[uuid].uuid != 0; } /** * @inheritdoc IEAS */ function getReceivedAttestationUUIDs( address recipient, bytes32 schema, uint256 start, uint256 length, bool reverseOrder ) external view returns (bytes32[] memory) { return _sliceUUIDs(_receivedAttestations[recipient][schema], start, length, reverseOrder); } /** * @inheritdoc IEAS */ function getReceivedAttestationUUIDsCount(address recipient, bytes32 schema) external view returns (uint256) { return _receivedAttestations[recipient][schema].length; } /** * @inheritdoc IEAS */ function getSentAttestationUUIDs( address attester, bytes32 schema, uint256 start, uint256 length, bool reverseOrder ) external view returns (bytes32[] memory) { return _sliceUUIDs(_sentAttestations[attester][schema], start, length, reverseOrder); } /** * @inheritdoc IEAS */ function getSentAttestationUUIDsCount(address recipient, bytes32 schema) external view returns (uint256) { return _sentAttestations[recipient][schema].length; } /** * @inheritdoc IEAS */ function getRelatedAttestationUUIDs( bytes32 uuid, uint256 start, uint256 length, bool reverseOrder ) external view returns (bytes32[] memory) { return _sliceUUIDs(_relatedAttestations[uuid], start, length, reverseOrder); } /** * @inheritdoc IEAS */ function getRelatedAttestationUUIDsCount(bytes32 uuid) external view returns (uint256) { return _relatedAttestations[uuid].length; } /** * @inheritdoc IEAS */ function getSchemaAttestationUUIDs( bytes32 schema, uint256 start, uint256 length, bool reverseOrder ) external view returns (bytes32[] memory) { return _sliceUUIDs(_schemaAttestations[schema], start, length, reverseOrder); } /** * @inheritdoc IEAS */ function getSchemaAttestationUUIDsCount(bytes32 schema) external view returns (uint256) { return _schemaAttestations[schema].length; } /** * @dev Attests to a specific AS. * * @param recipient The recipient of the attestation. * @param schema The UUID of the AS. * @param expirationTime The expiration time of the attestation. * @param refUUID An optional related attestation's UUID. * @param data Additional custom data. * @param attester The attesting account. * * @return The UUID of the new attestation. */ function _attest( address recipient, bytes32 schema, uint256 expirationTime, bytes32 refUUID, bytes calldata data, address attester ) private returns (bytes32) { if (expirationTime <= block.timestamp) { revert InvalidExpirationTime(); } ASRecord memory asRecord = _asRegistry.getAS(schema); if (asRecord.uuid == EMPTY_UUID) { revert InvalidSchema(); } IASResolver resolver = asRecord.resolver; if (address(resolver) != address(0x0)) { if (msg.value != 0 && !resolver.isPayable()) { revert NotPayable(); } if (!resolver.resolve{value: msg.value}(recipient, asRecord.schema, data, expirationTime, attester)) { revert InvalidAttestation(); } } Attestation memory attestation = Attestation({ uuid: EMPTY_UUID, schema: schema, recipient: recipient, attester: attester, time: block.timestamp, expirationTime: expirationTime, revocationTime: 0, refUUID: refUUID, data: data }); bytes32 uuid = _getUUID(attestation); attestation.uuid = uuid; _receivedAttestations[recipient][schema].push(uuid); _sentAttestations[attester][schema].push(uuid); _schemaAttestations[schema].push(uuid); _db[uuid] = attestation; _attestationsCount++; if (refUUID != 0) { if (!isAttestationValid(refUUID)) { revert NotFound(); } _relatedAttestations[refUUID].push(uuid); } emit Attested(recipient, attester, uuid, schema); return uuid; }
30,711
16
// Register an investor's redemption request, after checking that 1) the requested amount exceeds the minimum redemption amount and 2) the investor can't redeem more than the shares they own
function requestRedemption(address _addr, uint _shares) onlyFund constant returns (uint, uint)
function requestRedemption(address _addr, uint _shares) onlyFund constant returns (uint, uint)
48,470
88
// -- if the proposal passed send the creator back their Proposal Deposit,if the proposal was not successful, then thats the price you pay for submitting stupid things to the board.
if(proposals[_proposalID].proposalPassed == true){
if(proposals[_proposalID].proposalPassed == true){
14,809
31
// Initializes the debt token. name The name of the token symbol The symbol of the token decimals The decimals of the token /
function initialize( uint8 decimals, string memory name, string memory symbol
function initialize( uint8 decimals, string memory name, string memory symbol
16,065
26
// Function to check the amount of tokens than an owner allowed to a spender._owner address The address which owns the funds._spender address The address which will spend the funds. return A uint specifying the amount of tokens still available for the spender./
function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; }
function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; }
29,884
149
// Returns the downcasted uint112 from uint256, reverting onoverflow (when the input is greater than largest uint112). Counterpart to Solidity's `uint112` operator. Requirements: - input must fit into 112 bits _Available since v4.7._ /
function toUint112(uint256 value) internal pure returns (uint112) { require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits"); return uint112(value); }
function toUint112(uint256 value) internal pure returns (uint112) { require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits"); return uint112(value); }
929
14
// From: sha3_c.c State variables in 'storage' Moved from local vars in KeccakF1600_StatePermute() to here in order to avoid stack overflow
uint64 private Aba; uint64 private Abe; uint64 private Abi; uint64 private Abo; uint64 private Abu; // [60*8=480 bytes] uint64 private Aga; uint64 private Age; uint64 private Agi; uint64 private Ago; uint64 private Agu; uint64 private Aka; uint64 private Ake; uint64 private Aki; uint64 private Ako; uint64 private Aku; uint64 private Ama; uint64 private Ame; uint64 private Ami; uint64 private Amo; uint64 private Amu; uint64 private Asa; uint64 private Ase; uint64 private Asi; uint64 private Aso; uint64 private Asu; uint64 private BCa; uint64 private BCe; uint64 private BCi; uint64 private BCo; uint64 private BCu; uint64 private Da ; uint64 private De ; uint64 private Di ; uint64 private Do ; uint64 private Du ; uint64 private Eba; uint64 private Ebe; uint64 private Ebi; uint64 private Ebo; uint64 private Ebu; uint64 private Ega; uint64 private Ege; uint64 private Egi; uint64 private Ego; uint64 private Egu; uint64 private Eka; uint64 private Eke; uint64 private Eki; uint64 private Eko; uint64 private Eku;
uint64 private Aba; uint64 private Abe; uint64 private Abi; uint64 private Abo; uint64 private Abu; // [60*8=480 bytes] uint64 private Aga; uint64 private Age; uint64 private Agi; uint64 private Ago; uint64 private Agu; uint64 private Aka; uint64 private Ake; uint64 private Aki; uint64 private Ako; uint64 private Aku; uint64 private Ama; uint64 private Ame; uint64 private Ami; uint64 private Amo; uint64 private Amu; uint64 private Asa; uint64 private Ase; uint64 private Asi; uint64 private Aso; uint64 private Asu; uint64 private BCa; uint64 private BCe; uint64 private BCi; uint64 private BCo; uint64 private BCu; uint64 private Da ; uint64 private De ; uint64 private Di ; uint64 private Do ; uint64 private Du ; uint64 private Eba; uint64 private Ebe; uint64 private Ebi; uint64 private Ebo; uint64 private Ebu; uint64 private Ega; uint64 private Ege; uint64 private Egi; uint64 private Ego; uint64 private Egu; uint64 private Eka; uint64 private Eke; uint64 private Eki; uint64 private Eko; uint64 private Eku;
47,293
349
// Internal-only function that removes an existing admin.
function _removeAdmin(address _account) private { require(_isAdmin[_account], "provided account is not an admin"); _isAdmin[_account] = false; _adminCount--; emit RemovedAdmin(msg.sender, _account); }
function _removeAdmin(address _account) private { require(_isAdmin[_account], "provided account is not an admin"); _isAdmin[_account] = false; _adminCount--; emit RemovedAdmin(msg.sender, _account); }
43,765
127
// When executing a liqudation, the price of the asset has to be calculated at a discount in order for it to be profitable for the liquidator. This function will get the current oracle price for the asset and find the discounted price./
function calculateLiquidationPrice() public view returns (Decimal.D256 memory)
function calculateLiquidationPrice() public view returns (Decimal.D256 memory)
38,557
22
// Majority denied
if (_countDenied >= (tempTotalAuditors/2)) { return "Denied"; }
if (_countDenied >= (tempTotalAuditors/2)) { return "Denied"; }
41,259
3
// Called by bZx after interest should be paid to a lender/Assume the interest token has already been transfered to/this contract before this function is called./loanOrder The loanOrder object/lender The lender/amountOwed The amount interest to pay/convert A boolean indicating if the interest should be converted to Ether/gasUsed The initial used gas, collected in a modifier in bZx, for optional gas refunds/ return Successful execution of the function
function didPayInterest( BZxObjects.LoanOrder memory loanOrder, address lender, uint amountOwed, bool convert, uint gasUsed) public returns (bool);
function didPayInterest( BZxObjects.LoanOrder memory loanOrder, address lender, uint amountOwed, bool convert, uint gasUsed) public returns (bool);
27,402
63
// return true if crowdsale event has ended or cap reached
function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; bool passedEndTime = now > endTime; return passedEndTime || capReached; }
function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; bool passedEndTime = now > endTime; return passedEndTime || capReached; }
43,575
235
// See {IERC20Permit-permit}. /
function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
50,196
32
// Sets the rewards that farmers have earned.Can only be called by the current [governor](/docs/protocol/governance). farmers Array of farmers to set. rewards Array of rewards to set. /
function setFarmedRewards(address[] calldata farmers, uint256[] calldata rewards) external override onlyGovernance { require(farmers.length == rewards.length, "length mismatch"); for(uint256 i = 0; i < farmers.length; i++) { farmedRewards[farmers[i]] = rewards[i]; } }
function setFarmedRewards(address[] calldata farmers, uint256[] calldata rewards) external override onlyGovernance { require(farmers.length == rewards.length, "length mismatch"); for(uint256 i = 0; i < farmers.length; i++) { farmedRewards[farmers[i]] = rewards[i]; } }
37,247
6
// CRITICAL CONTRACT PARAMETERSPausable library is simple enough to integrate into this contract
bool public paused = false; uint8 _layer; address _signer; address _arbPartner; IArbPartner _arbPartnerInterface; IInbox _inbox; //Inbox for L1 IOutbox _outbox; //Outbox for L2 HungryBunz _hbContract; //Layer-local main contract INom _nom; //Layer-local Nom contract
bool public paused = false; uint8 _layer; address _signer; address _arbPartner; IArbPartner _arbPartnerInterface; IInbox _inbox; //Inbox for L1 IOutbox _outbox; //Outbox for L2 HungryBunz _hbContract; //Layer-local main contract INom _nom; //Layer-local Nom contract
39,919
361
// update user record
user.tokenAmount += addedAmount; user.totalWeight += stakeWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
user.tokenAmount += addedAmount; user.totalWeight += stakeWeight; user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
50,732
18
// updates the swap path for a given pair can only be called by YieldWolf contract which already performs the required validations and logging /
function setSwapPath( address _token0, address _token1, address[] calldata _path
function setSwapPath( address _token0, address _token1, address[] calldata _path
22,975
36
// Require that a typed memory view be valid. Returns the view for easy chaining. memView The viewreturnbytes29 - The validated view /
function assertValid(bytes29 memView) internal pure returns (bytes29) { require(isValid(memView), "Validity assertion failed"); return memView; }
function assertValid(bytes29 memView) internal pure returns (bytes29) { require(isValid(memView), "Validity assertion failed"); return memView; }
16,857
35
// отсылаем эфир за купленное молоко
uint a=milkcost*milk_to_sale; msg.sender.transfer(milkcost*milk_to_sale);
uint a=milkcost*milk_to_sale; msg.sender.transfer(milkcost*milk_to_sale);
58,404
69
// Swaps to a flexible amount, from an exact input amount/ @inheritdoc ISwapper
function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom
function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom
37,060
8
// Approve and then communicate the approved contract in a single tx /
returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } }
returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } }
8,034
11
// Returns the address of the resolver for the specified node. node The specified node.return address of the resolver. /
function resolver(bytes32 node) public virtual override view returns (address) { return records[node].resolver; }
function resolver(bytes32 node) public virtual override view returns (address) { return records[node].resolver; }
11,421
8
// Saving assets original amount/ This amount is in the same unit used in allocation strategy
uint256 public savingAssetOrignalAmount;
uint256 public savingAssetOrignalAmount;
30,521
9
// MATH /
using SafeMath for uint256;
using SafeMath for uint256;
12,267
95
// Get how much SF will be distributed after taxing a specific collateral type collateralType Collateral type to compute the taxation outcome forreturn The newly accumulated rate as well as the delta between the new and the last accumulated rates /
function taxSingleOutcome(bytes32 collateralType) public view returns (uint256, int256) { (, uint256 lastAccumulatedRate) = safeEngine.collateralTypes(collateralType); uint256 newlyAccumulatedRate = rmultiply( rpow( addition( globalStabilityFee, collateralTypes[collateralType].stabilityFee ), subtract( now, collateralTypes[collateralType].updateTime ), RAY), lastAccumulatedRate); return (newlyAccumulatedRate, deduct(newlyAccumulatedRate, lastAccumulatedRate)); }
function taxSingleOutcome(bytes32 collateralType) public view returns (uint256, int256) { (, uint256 lastAccumulatedRate) = safeEngine.collateralTypes(collateralType); uint256 newlyAccumulatedRate = rmultiply( rpow( addition( globalStabilityFee, collateralTypes[collateralType].stabilityFee ), subtract( now, collateralTypes[collateralType].updateTime ), RAY), lastAccumulatedRate); return (newlyAccumulatedRate, deduct(newlyAccumulatedRate, lastAccumulatedRate)); }
33,467
17
// ========== PUBLIC FUNCTIONS ========== / There needs to be a time interval that this can be called. Otherwise it can be called multiple times per expansion.
uint256 public last_call_time; // Last time the refreshCollateralRatio function was called
uint256 public last_call_time; // Last time the refreshCollateralRatio function was called
32,046
36
// Otherwise, the contribution helped us reach the funding cap. We should take what we can until the funding cap is reached, and refund the rest.
uint256 eligibleAmount = fundingCap - startAmount;
uint256 eligibleAmount = fundingCap - startAmount;
39,429
161
// received amount
uint256 amountReceived = address(this).balance;
uint256 amountReceived = address(this).balance;
23,117
3
// ERC20-tokens: cUSD and cEUR
IERC20 private immutable cUSD; IERC20 private immutable cEUR;
IERC20 private immutable cUSD; IERC20 private immutable cEUR;
24,463
3
// synth type
uint8 public synthType;
uint8 public synthType;
5,464
4,742
// 2372
entry "civicminded" : ENG_ADJECTIVE
entry "civicminded" : ENG_ADJECTIVE
18,984
89
// Log Users withdraw
event Withdraw(address indexed userAddrs, address indexed asset, uint256 amount);
event Withdraw(address indexed userAddrs, address indexed asset, uint256 amount);
79,006
8
// Renamed dividends to rewards. (OLD) Many functions in this contract were taken from this repository:which is an example implementation of ERC 2222, the draft for which can be found at This contract has been substantially modified from the original and does not comply with ERC 2222.Many functions were renamed as "rewards" rather than "funds" and the core functionality was separatedinto this abstract contract which can be inherited by anything tracking ownership of reward shares. /
abstract contract AbstractRewards is IAbstractRewards { using SafeCast for uint128; using SafeCast for uint256; using SafeCast for int256; /* ======== Constants ======== */ uint128 public constant POINTS_MULTIPLIER = type(uint128).max; /* ======== Internal Function References ======== */ function(address) view returns (uint256) private immutable getSharesOf; function() view returns (uint256) private immutable getTotalShares; /* ======== Storage ======== */ uint256 public pointsPerShare; mapping(address => int256) public pointsCorrection; mapping(address => uint256) public withdrawnRewards; constructor( function(address) view returns (uint256) getSharesOf_, function() view returns (uint256) getTotalShares_ ) { getSharesOf = getSharesOf_; getTotalShares = getTotalShares_; } /* ======== Public View Functions ======== */ /** * @dev Returns the total amount of rewards a given address is able to withdraw. * @param _account Address of a reward recipient * @return A uint256 representing the rewards `account` can withdraw */ function withdrawableRewardsOf(address _account) public view override returns (uint256) { return cumulativeRewardsOf(_account) - withdrawnRewards[_account]; } /** * @notice View the amount of rewards that an address has withdrawn. * @param _account The address of a token holder. * @return The amount of rewards that `account` has withdrawn. */ function withdrawnRewardsOf(address _account) public view override returns (uint256) { return withdrawnRewards[_account]; } /** * @notice View the amount of rewards that an address has earned in total. * @dev accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account) * = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER * @param _account The address of a token holder. * @return The amount of rewards that `account` has earned in total. */ function cumulativeRewardsOf(address _account) public view override returns (uint256) { return ((pointsPerShare * getSharesOf(_account)).toInt256() + pointsCorrection[_account]).toUint256() / POINTS_MULTIPLIER; } /* ======== Dividend Utility Functions ======== */ /** * @notice Distributes rewards to token holders. * @dev It reverts if the total shares is 0. * It emits the `RewardsDistributed` event if the amount to distribute is greater than 0. * About undistributed rewards: * In each distribution, there is a small amount which does not get distributed, * which is `(amount * POINTS_MULTIPLIER) % totalShares()`. * With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting * distributed in a distribution can be less than 1 (base unit). */ function _distributeRewards(uint256 _amount) internal { uint256 shares = getTotalShares(); require(shares > 0, "AbstractRewards._distributeRewards: total share supply is zero"); if (_amount > 0) { pointsPerShare = pointsPerShare + (_amount * POINTS_MULTIPLIER / shares); emit RewardsDistributed(msg.sender, _amount); } } /** * @notice Prepares collection of owed rewards * @dev It emits a `RewardsWithdrawn` event if the amount of withdrawn rewards is * greater than 0. */ function _prepareCollect(address _account) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableRewardsOf(_account); if (_withdrawableDividend > 0) { withdrawnRewards[_account] = withdrawnRewards[_account] + _withdrawableDividend; emit RewardsWithdrawn(_account, _withdrawableDividend); } return _withdrawableDividend; } function _correctPointsForTransfer(address _from, address _to, uint256 _shares) internal { int256 _magCorrection = (pointsPerShare * _shares).toInt256(); pointsCorrection[_from] = pointsCorrection[_from] + _magCorrection; pointsCorrection[_to] = pointsCorrection[_to] - _magCorrection; } /** * @dev Increases or decreases the points correction for `account` by * `shares*pointsPerShare`. */ function _correctPoints(address _account, int256 _shares) internal { pointsCorrection[_account] = pointsCorrection[_account] + (_shares * (int256(pointsPerShare))); } }
abstract contract AbstractRewards is IAbstractRewards { using SafeCast for uint128; using SafeCast for uint256; using SafeCast for int256; /* ======== Constants ======== */ uint128 public constant POINTS_MULTIPLIER = type(uint128).max; /* ======== Internal Function References ======== */ function(address) view returns (uint256) private immutable getSharesOf; function() view returns (uint256) private immutable getTotalShares; /* ======== Storage ======== */ uint256 public pointsPerShare; mapping(address => int256) public pointsCorrection; mapping(address => uint256) public withdrawnRewards; constructor( function(address) view returns (uint256) getSharesOf_, function() view returns (uint256) getTotalShares_ ) { getSharesOf = getSharesOf_; getTotalShares = getTotalShares_; } /* ======== Public View Functions ======== */ /** * @dev Returns the total amount of rewards a given address is able to withdraw. * @param _account Address of a reward recipient * @return A uint256 representing the rewards `account` can withdraw */ function withdrawableRewardsOf(address _account) public view override returns (uint256) { return cumulativeRewardsOf(_account) - withdrawnRewards[_account]; } /** * @notice View the amount of rewards that an address has withdrawn. * @param _account The address of a token holder. * @return The amount of rewards that `account` has withdrawn. */ function withdrawnRewardsOf(address _account) public view override returns (uint256) { return withdrawnRewards[_account]; } /** * @notice View the amount of rewards that an address has earned in total. * @dev accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account) * = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER * @param _account The address of a token holder. * @return The amount of rewards that `account` has earned in total. */ function cumulativeRewardsOf(address _account) public view override returns (uint256) { return ((pointsPerShare * getSharesOf(_account)).toInt256() + pointsCorrection[_account]).toUint256() / POINTS_MULTIPLIER; } /* ======== Dividend Utility Functions ======== */ /** * @notice Distributes rewards to token holders. * @dev It reverts if the total shares is 0. * It emits the `RewardsDistributed` event if the amount to distribute is greater than 0. * About undistributed rewards: * In each distribution, there is a small amount which does not get distributed, * which is `(amount * POINTS_MULTIPLIER) % totalShares()`. * With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting * distributed in a distribution can be less than 1 (base unit). */ function _distributeRewards(uint256 _amount) internal { uint256 shares = getTotalShares(); require(shares > 0, "AbstractRewards._distributeRewards: total share supply is zero"); if (_amount > 0) { pointsPerShare = pointsPerShare + (_amount * POINTS_MULTIPLIER / shares); emit RewardsDistributed(msg.sender, _amount); } } /** * @notice Prepares collection of owed rewards * @dev It emits a `RewardsWithdrawn` event if the amount of withdrawn rewards is * greater than 0. */ function _prepareCollect(address _account) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableRewardsOf(_account); if (_withdrawableDividend > 0) { withdrawnRewards[_account] = withdrawnRewards[_account] + _withdrawableDividend; emit RewardsWithdrawn(_account, _withdrawableDividend); } return _withdrawableDividend; } function _correctPointsForTransfer(address _from, address _to, uint256 _shares) internal { int256 _magCorrection = (pointsPerShare * _shares).toInt256(); pointsCorrection[_from] = pointsCorrection[_from] + _magCorrection; pointsCorrection[_to] = pointsCorrection[_to] - _magCorrection; } /** * @dev Increases or decreases the points correction for `account` by * `shares*pointsPerShare`. */ function _correctPoints(address _account, int256 _shares) internal { pointsCorrection[_account] = pointsCorrection[_account] + (_shares * (int256(pointsPerShare))); } }
16,461
887
// msg.sender sends Ether to repay an account's borrow in a cEther market The provided Ether is applied towards the borrow balance, any excess is refunded borrower The address of the borrower account to repay on behalf of cEther_ The address of the cEther contract to repay in /
function repayBehalfExplicit(address borrower, CEther cEther_) public payable { uint received = msg.value; uint borrows = cEther_.borrowBalanceCurrent(borrower); if (received > borrows) { cEther_.repayBorrowBehalf.value(borrows)(borrower); msg.sender.transfer(received - borrows); } else { cEther_.repayBorrowBehalf.value(received)(borrower); } }
function repayBehalfExplicit(address borrower, CEther cEther_) public payable { uint received = msg.value; uint borrows = cEther_.borrowBalanceCurrent(borrower); if (received > borrows) { cEther_.repayBorrowBehalf.value(borrows)(borrower); msg.sender.transfer(received - borrows); } else { cEther_.repayBorrowBehalf.value(received)(borrower); } }
37,562
12
// Phase 4
function flipGenesisState() public onlyOwner { genesisSale = !genesisSale; }
function flipGenesisState() public onlyOwner { genesisSale = !genesisSale; }
41,234
60
// Collect fees if they are set, reducing the number of tokens for the sender thus leaving more YBT in the TempusPool than there are minted TPS/TYS
uint256 tokenAmount = yieldTokenAmount; uint256 depositFees = feesConfig.depositPercent; if (depositFees != 0) { fee = tokenAmount.mulfV(depositFees, yieldBearingONE); tokenAmount -= fee; totalFees += fee; }
uint256 tokenAmount = yieldTokenAmount; uint256 depositFees = feesConfig.depositPercent; if (depositFees != 0) { fee = tokenAmount.mulfV(depositFees, yieldBearingONE); tokenAmount -= fee; totalFees += fee; }
60,985
124
// Verify that the tokenId is owned by given baseCFolio.
require( IERC1155(address(tradeFloor)).balanceOf( baseCFolio, cfolioItemTokenId ) == 1, 'CFHI: Access denied (CF)' );
require( IERC1155(address(tradeFloor)).balanceOf( baseCFolio, cfolioItemTokenId ) == 1, 'CFHI: Access denied (CF)' );
29,632
262
// token should be for sale
require(doorNFT.forSale);
require(doorNFT.forSale);
40,070
78
// Function to release tokens of a vesting id _vestingIdvesting Id /
function release(uint256 _vestingId) public { Vesting storage vesting = vestings[_vestingId]; require(beneficiaryAddress != address(0x0), INVALID_VESTING_ID); require(!vesting.released , VESTING_ALREADY_RELEASED); // solhint-disable-next-line not-rely-on-time require(block.timestamp >= vesting.releaseTime, NOT_VESTED); require(tokenAddress.balanceOf(address(this)) >= vesting.amount, INSUFFICIENT_BALANCE); vesting.released = true; tokensToVest = tokensToVest.sub(vesting.amount); tokenAddress.safeTransfer(beneficiaryAddress, vesting.amount); emit TokenVestingReleased(_vestingId, beneficiaryAddress, vesting.amount); }
function release(uint256 _vestingId) public { Vesting storage vesting = vestings[_vestingId]; require(beneficiaryAddress != address(0x0), INVALID_VESTING_ID); require(!vesting.released , VESTING_ALREADY_RELEASED); // solhint-disable-next-line not-rely-on-time require(block.timestamp >= vesting.releaseTime, NOT_VESTED); require(tokenAddress.balanceOf(address(this)) >= vesting.amount, INSUFFICIENT_BALANCE); vesting.released = true; tokensToVest = tokensToVest.sub(vesting.amount); tokenAddress.safeTransfer(beneficiaryAddress, vesting.amount); emit TokenVestingReleased(_vestingId, beneficiaryAddress, vesting.amount); }
53,119
176
// Sets the royalty information for a specific token id, overriding the global default. Requirements: - `tokenId` must be already minted.- `receiver` cannot be the zero address.- `feeNumerator` cannot be greater than the fee denominator. /
function _setTokenRoyalty( uint256 tokenId, address receiver, uint96 feeNumerator
function _setTokenRoyalty( uint256 tokenId, address receiver, uint96 feeNumerator
6,922
1,061
// increase rate by 3% too account for inaccuracy between sell/buy conversion
rate = rate + (rate / 30);
rate = rate + (rate / 30);
58,009
24
// Verifica frequencia
require (now > (lastTransfer + transferWait), "Speed bump activated, frequency exceeded"); lastTransfer = now;
require (now > (lastTransfer + transferWait), "Speed bump activated, frequency exceeded"); lastTransfer = now;
4,635
228
// Add a new vesting entry at a given time and quantity to an account's schedule. A call to this should be accompanied by either enough balance already availablein this contract, or a corresponding call to havven.endow(), to ensure that whenthe funds are withdrawn, there is enough balance, as well as correctly calculatingthe fees.This may only be called by the owner during the contract's setup period.Note; although this function could technically be used to produce unboundedarrays, it's only in the foundation's command to add to these lists. account The account to append a new vesting entry to. time The absolute unix
function appendVestingEntry(address account, uint time, uint quantity) public onlyOwner onlyDuringSetup
function appendVestingEntry(address account, uint time, uint quantity) public onlyOwner onlyDuringSetup
73,665
84
// ERC 20 Standard decrease Allowance
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool)
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool)
3,673
62
// A dual control contract. A general-purpose contract that implements dual control over co-operating contracts through a callback mechanism. This contract implements dual control through a 2-of-N threshold multi-signature scheme. The contract recognizes a set of N signers, and will unlock requests with signatures from any distinct pair of them. This contract signals the unlocking through a co-operative callback scheme. This contract also provides time lock and revocation features. Requests made by a 'primary' account have a default time lock applied. All other requests must pay a 1 ETH stake and have an extended time lock applied. A request that is
contract Custodian { // TYPES /** @dev The `Request` struct stores a pending unlocking. * `callbackAddress` and `callbackSelector` are the data required to * make a callback. The custodian completes the process by * calling `callbackAddress.call(callbackSelector, lockId)`, which * signals to the contract co-operating with the Custodian that * the 2-of-N signatures have been provided and verified. */ struct Request { bytes32 lockId; bytes4 callbackSelector; // bytes4 and address can be packed into 1 word address callbackAddress; uint256 idx; uint256 timestamp; bool extended; } // EVENTS /// @dev Emitted by successful `requestUnlock` calls. event Requested( bytes32 _lockId, address _callbackAddress, bytes4 _callbackSelector, uint256 _nonce, address _whitelistedAddress, bytes32 _requestMsgHash, uint256 _timeLockExpiry ); /// @dev Emitted by `completeUnlock` calls on requests in the time-locked state. event TimeLocked( uint256 _timeLockExpiry, bytes32 _requestMsgHash ); /// @dev Emitted by successful `completeUnlock` calls. event Completed( bytes32 _lockId, bytes32 _requestMsgHash, address _signer1, address _signer2 ); /// @dev Emitted by `completeUnlock` calls where the callback failed. event Failed( bytes32 _lockId, bytes32 _requestMsgHash, address _signer1, address _signer2 ); /// @dev Emitted by successful `extendRequestTimeLock` calls. event TimeLockExtended( uint256 _timeLockExpiry, bytes32 _requestMsgHash ); // MEMBERS /** @dev The count of all requests. * This value is used as a nonce, incorporated into the request hash. */ uint256 public requestCount; /// @dev The set of signers: signatures from two signers unlock a pending request. mapping (address => bool) public signerSet; /// @dev The map of request hashes to pending requests. mapping (bytes32 => Request) public requestMap; /// @dev The map of callback addresses to callback selectors to request indexes. mapping (address => mapping (bytes4 => uint256)) public lastCompletedIdxs; /** @dev The default period (in seconds) to time-lock requests. * All requests will be subject to this default time lock, and the duration * is fixed at contract creation. */ uint256 public defaultTimeLock; /** @dev The extended period (in seconds) to time-lock requests. * Requests not from the primary account are subject to this time lock. * The primary account may also elect to extend the time lock on requests * that originally received the default. */ uint256 public extendedTimeLock; /// @dev The primary account is the privileged account for making requests. address public primary; // CONSTRUCTOR constructor( address[] memory _signers, uint256 _defaultTimeLock, uint256 _extendedTimeLock, address _primary ) public { // check for at least two `_signers` require(_signers.length >= 2, "at least two `_signers`"); // validate time lock params require(_defaultTimeLock <= _extendedTimeLock, "valid timelock params"); defaultTimeLock = _defaultTimeLock; extendedTimeLock = _extendedTimeLock; primary = _primary; // explicitly initialize `requestCount` to zero requestCount = 0; // turn the array into a set for (uint i = 0; i < _signers.length; i++) { // no zero addresses or duplicates require(_signers[i] != address(0) && !signerSet[_signers[i]], "no zero addresses or duplicates"); signerSet[_signers[i]] = true; } } // MODIFIERS modifier onlyPrimary { require(msg.sender == primary, "only primary"); _; } modifier onlySigner { require(signerSet[msg.sender], "only signer"); _; } // METHODS /** @notice Requests an unlocking with a lock identifier and a callback. * * @dev If called by an account other than the primary a 1 ETH stake * must be paid. When the request is unlocked stake will be transferred to the message sender. * This is an anti-spam measure. As well as the callback * and the lock identifier parameters a 'whitelisted address' is required * for compatibility with existing signature schemes. * * @param _lockId The identifier of a pending request in a co-operating contract. * @param _callbackAddress The address of a co-operating contract. * @param _callbackSelector The function selector of a function within * the co-operating contract at address `_callbackAddress`. * @param _whitelistedAddress An address whitelisted in existing * offline control protocols. * * @return requestMsgHash The hash of a request message to be signed. */ function requestUnlock( bytes32 _lockId, address _callbackAddress, bytes4 _callbackSelector, address _whitelistedAddress ) public payable returns (bytes32 requestMsgHash) { require(msg.sender == primary || msg.value >= 1 ether, "sender is primary or stake is paid"); // disallow using a zero value for the callback address require(_callbackAddress != address(0), "no zero value for callback address"); uint256 requestIdx = ++requestCount; // compute a nonce value // - the blockhash prevents prediction of future nonces // - the address of this contract prevents conflicts with co-operating contracts using this scheme // - the counter prevents conflicts arising from multiple txs within the same block uint256 nonce = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), requestIdx))); requestMsgHash = keccak256( abi.encodePacked( nonce, _whitelistedAddress, uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) ) ); requestMap[requestMsgHash] = Request({ lockId: _lockId, callbackSelector: _callbackSelector, callbackAddress: _callbackAddress, idx: requestIdx, timestamp: block.timestamp, extended: false }); // compute the expiry time uint256 timeLockExpiry = block.timestamp; if (msg.sender == primary) { timeLockExpiry += defaultTimeLock; } else { timeLockExpiry += extendedTimeLock; // any sender that is not the creator will get the extended time lock requestMap[requestMsgHash].extended = true; } emit Requested(_lockId, _callbackAddress, _callbackSelector, nonce, _whitelistedAddress, requestMsgHash, timeLockExpiry); } /** @notice Completes a pending unlocking with two signatures. * * @dev Given a request message hash as two signatures of it from * two distinct signers in the signer set, this function completes the * unlocking of the pending request by executing the callback. * * @param _requestMsgHash The request message hash of a pending request. * @param _recoveryByte1 The public key recovery byte (27 or 28) * @param _ecdsaR1 The R component of an ECDSA signature (R, S) pair * @param _ecdsaS1 The S component of an ECDSA signature (R, S) pair * @param _recoveryByte2 The public key recovery byte (27 or 28) * @param _ecdsaR2 The R component of an ECDSA signature (R, S) pair * @param _ecdsaS2 The S component of an ECDSA signature (R, S) pair * * @return success True if the callback successfully executed. */ function completeUnlock( bytes32 _requestMsgHash, uint8 _recoveryByte1, bytes32 _ecdsaR1, bytes32 _ecdsaS1, uint8 _recoveryByte2, bytes32 _ecdsaR2, bytes32 _ecdsaS2 ) public onlySigner returns (bool success) { Request storage request = requestMap[_requestMsgHash]; // copy storage to locals before `delete` bytes32 lockId = request.lockId; address callbackAddress = request.callbackAddress; bytes4 callbackSelector = request.callbackSelector; // failing case of the lookup if the callback address is zero require(callbackAddress != address(0), "no zero value for callback address"); // reject confirms of earlier withdrawals buried under later confirmed withdrawals require(request.idx > lastCompletedIdxs[callbackAddress][callbackSelector], "reject confirms of earlier withdrawals buried under later confirmed withdrawals"); address signer1 = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)), _recoveryByte1, _ecdsaR1, _ecdsaS1 ); require(signerSet[signer1], "signer is set"); address signer2 = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)), _recoveryByte2, _ecdsaR2, _ecdsaS2 ); require(signerSet[signer2], "signer is set"); require(signer1 != signer2, "signers are different"); if (request.extended && ((block.timestamp - request.timestamp) < extendedTimeLock)) { emit TimeLocked(request.timestamp + extendedTimeLock, _requestMsgHash); return false; } else if ((block.timestamp - request.timestamp) < defaultTimeLock) { emit TimeLocked(request.timestamp + defaultTimeLock, _requestMsgHash); return false; } else { if (address(this).balance > 0) { // reward sender with anti-spam payments msg.sender.transfer(address(this).balance); } // raise the waterline for the last completed unlocking lastCompletedIdxs[callbackAddress][callbackSelector] = request.idx; // and delete the request delete requestMap[_requestMsgHash]; // invoke callback (success,) = (false, bytes(msg.data)); callbackAddress.call(abi.encodeWithSelector(callbackSelector, lockId)); //inject UNHANDLED EXCEPTION if (success) { emit Completed(lockId, _requestMsgHash, signer1, signer2); } else { emit Failed(lockId, _requestMsgHash, signer1, signer2); } } } /** @notice Reclaim the storage of a pending request that is uncompletable. * * @dev If a pending request shares the callback (address and selector) of * a later request has been completed, then the request can no longer * be completed. This function will reclaim the contract storage of the * pending request. * * @param _requestMsgHash The request message hash of a pending request. */ function deleteUncompletableRequest(bytes32 _requestMsgHash) public { Request storage request = requestMap[_requestMsgHash]; uint256 idx = request.idx; require(0 < idx && idx < lastCompletedIdxs[request.callbackAddress][request.callbackSelector], "there must be a completed latter request with same callback"); delete requestMap[_requestMsgHash]; } /** @notice Extend the time lock of a pending request. * * @dev Requests made by the primary account receive the default time lock. * This function allows the primary account to apply the extended time lock * to one its own requests. * * @param _requestMsgHash The request message hash of a pending request. */ function extendRequestTimeLock(bytes32 _requestMsgHash) public onlyPrimary { Request storage request = requestMap[_requestMsgHash]; // reject 1null1 results from the map lookup // this can only be the case if an unknown `_requestMsgHash` is received require(request.callbackAddress != address(0), "reject 1null1 results from the map lookup"); // `extendRequestTimeLock` must be idempotent require(request.extended != true, "`extendRequestTimeLock` must be idempotent"); // set the `extended` flag; note that this is never unset request.extended = true; emit TimeLockExtended(request.timestamp + extendedTimeLock, _requestMsgHash); } }
contract Custodian { // TYPES /** @dev The `Request` struct stores a pending unlocking. * `callbackAddress` and `callbackSelector` are the data required to * make a callback. The custodian completes the process by * calling `callbackAddress.call(callbackSelector, lockId)`, which * signals to the contract co-operating with the Custodian that * the 2-of-N signatures have been provided and verified. */ struct Request { bytes32 lockId; bytes4 callbackSelector; // bytes4 and address can be packed into 1 word address callbackAddress; uint256 idx; uint256 timestamp; bool extended; } // EVENTS /// @dev Emitted by successful `requestUnlock` calls. event Requested( bytes32 _lockId, address _callbackAddress, bytes4 _callbackSelector, uint256 _nonce, address _whitelistedAddress, bytes32 _requestMsgHash, uint256 _timeLockExpiry ); /// @dev Emitted by `completeUnlock` calls on requests in the time-locked state. event TimeLocked( uint256 _timeLockExpiry, bytes32 _requestMsgHash ); /// @dev Emitted by successful `completeUnlock` calls. event Completed( bytes32 _lockId, bytes32 _requestMsgHash, address _signer1, address _signer2 ); /// @dev Emitted by `completeUnlock` calls where the callback failed. event Failed( bytes32 _lockId, bytes32 _requestMsgHash, address _signer1, address _signer2 ); /// @dev Emitted by successful `extendRequestTimeLock` calls. event TimeLockExtended( uint256 _timeLockExpiry, bytes32 _requestMsgHash ); // MEMBERS /** @dev The count of all requests. * This value is used as a nonce, incorporated into the request hash. */ uint256 public requestCount; /// @dev The set of signers: signatures from two signers unlock a pending request. mapping (address => bool) public signerSet; /// @dev The map of request hashes to pending requests. mapping (bytes32 => Request) public requestMap; /// @dev The map of callback addresses to callback selectors to request indexes. mapping (address => mapping (bytes4 => uint256)) public lastCompletedIdxs; /** @dev The default period (in seconds) to time-lock requests. * All requests will be subject to this default time lock, and the duration * is fixed at contract creation. */ uint256 public defaultTimeLock; /** @dev The extended period (in seconds) to time-lock requests. * Requests not from the primary account are subject to this time lock. * The primary account may also elect to extend the time lock on requests * that originally received the default. */ uint256 public extendedTimeLock; /// @dev The primary account is the privileged account for making requests. address public primary; // CONSTRUCTOR constructor( address[] memory _signers, uint256 _defaultTimeLock, uint256 _extendedTimeLock, address _primary ) public { // check for at least two `_signers` require(_signers.length >= 2, "at least two `_signers`"); // validate time lock params require(_defaultTimeLock <= _extendedTimeLock, "valid timelock params"); defaultTimeLock = _defaultTimeLock; extendedTimeLock = _extendedTimeLock; primary = _primary; // explicitly initialize `requestCount` to zero requestCount = 0; // turn the array into a set for (uint i = 0; i < _signers.length; i++) { // no zero addresses or duplicates require(_signers[i] != address(0) && !signerSet[_signers[i]], "no zero addresses or duplicates"); signerSet[_signers[i]] = true; } } // MODIFIERS modifier onlyPrimary { require(msg.sender == primary, "only primary"); _; } modifier onlySigner { require(signerSet[msg.sender], "only signer"); _; } // METHODS /** @notice Requests an unlocking with a lock identifier and a callback. * * @dev If called by an account other than the primary a 1 ETH stake * must be paid. When the request is unlocked stake will be transferred to the message sender. * This is an anti-spam measure. As well as the callback * and the lock identifier parameters a 'whitelisted address' is required * for compatibility with existing signature schemes. * * @param _lockId The identifier of a pending request in a co-operating contract. * @param _callbackAddress The address of a co-operating contract. * @param _callbackSelector The function selector of a function within * the co-operating contract at address `_callbackAddress`. * @param _whitelistedAddress An address whitelisted in existing * offline control protocols. * * @return requestMsgHash The hash of a request message to be signed. */ function requestUnlock( bytes32 _lockId, address _callbackAddress, bytes4 _callbackSelector, address _whitelistedAddress ) public payable returns (bytes32 requestMsgHash) { require(msg.sender == primary || msg.value >= 1 ether, "sender is primary or stake is paid"); // disallow using a zero value for the callback address require(_callbackAddress != address(0), "no zero value for callback address"); uint256 requestIdx = ++requestCount; // compute a nonce value // - the blockhash prevents prediction of future nonces // - the address of this contract prevents conflicts with co-operating contracts using this scheme // - the counter prevents conflicts arising from multiple txs within the same block uint256 nonce = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), requestIdx))); requestMsgHash = keccak256( abi.encodePacked( nonce, _whitelistedAddress, uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) ) ); requestMap[requestMsgHash] = Request({ lockId: _lockId, callbackSelector: _callbackSelector, callbackAddress: _callbackAddress, idx: requestIdx, timestamp: block.timestamp, extended: false }); // compute the expiry time uint256 timeLockExpiry = block.timestamp; if (msg.sender == primary) { timeLockExpiry += defaultTimeLock; } else { timeLockExpiry += extendedTimeLock; // any sender that is not the creator will get the extended time lock requestMap[requestMsgHash].extended = true; } emit Requested(_lockId, _callbackAddress, _callbackSelector, nonce, _whitelistedAddress, requestMsgHash, timeLockExpiry); } /** @notice Completes a pending unlocking with two signatures. * * @dev Given a request message hash as two signatures of it from * two distinct signers in the signer set, this function completes the * unlocking of the pending request by executing the callback. * * @param _requestMsgHash The request message hash of a pending request. * @param _recoveryByte1 The public key recovery byte (27 or 28) * @param _ecdsaR1 The R component of an ECDSA signature (R, S) pair * @param _ecdsaS1 The S component of an ECDSA signature (R, S) pair * @param _recoveryByte2 The public key recovery byte (27 or 28) * @param _ecdsaR2 The R component of an ECDSA signature (R, S) pair * @param _ecdsaS2 The S component of an ECDSA signature (R, S) pair * * @return success True if the callback successfully executed. */ function completeUnlock( bytes32 _requestMsgHash, uint8 _recoveryByte1, bytes32 _ecdsaR1, bytes32 _ecdsaS1, uint8 _recoveryByte2, bytes32 _ecdsaR2, bytes32 _ecdsaS2 ) public onlySigner returns (bool success) { Request storage request = requestMap[_requestMsgHash]; // copy storage to locals before `delete` bytes32 lockId = request.lockId; address callbackAddress = request.callbackAddress; bytes4 callbackSelector = request.callbackSelector; // failing case of the lookup if the callback address is zero require(callbackAddress != address(0), "no zero value for callback address"); // reject confirms of earlier withdrawals buried under later confirmed withdrawals require(request.idx > lastCompletedIdxs[callbackAddress][callbackSelector], "reject confirms of earlier withdrawals buried under later confirmed withdrawals"); address signer1 = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)), _recoveryByte1, _ecdsaR1, _ecdsaS1 ); require(signerSet[signer1], "signer is set"); address signer2 = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)), _recoveryByte2, _ecdsaR2, _ecdsaS2 ); require(signerSet[signer2], "signer is set"); require(signer1 != signer2, "signers are different"); if (request.extended && ((block.timestamp - request.timestamp) < extendedTimeLock)) { emit TimeLocked(request.timestamp + extendedTimeLock, _requestMsgHash); return false; } else if ((block.timestamp - request.timestamp) < defaultTimeLock) { emit TimeLocked(request.timestamp + defaultTimeLock, _requestMsgHash); return false; } else { if (address(this).balance > 0) { // reward sender with anti-spam payments msg.sender.transfer(address(this).balance); } // raise the waterline for the last completed unlocking lastCompletedIdxs[callbackAddress][callbackSelector] = request.idx; // and delete the request delete requestMap[_requestMsgHash]; // invoke callback (success,) = (false, bytes(msg.data)); callbackAddress.call(abi.encodeWithSelector(callbackSelector, lockId)); //inject UNHANDLED EXCEPTION if (success) { emit Completed(lockId, _requestMsgHash, signer1, signer2); } else { emit Failed(lockId, _requestMsgHash, signer1, signer2); } } } /** @notice Reclaim the storage of a pending request that is uncompletable. * * @dev If a pending request shares the callback (address and selector) of * a later request has been completed, then the request can no longer * be completed. This function will reclaim the contract storage of the * pending request. * * @param _requestMsgHash The request message hash of a pending request. */ function deleteUncompletableRequest(bytes32 _requestMsgHash) public { Request storage request = requestMap[_requestMsgHash]; uint256 idx = request.idx; require(0 < idx && idx < lastCompletedIdxs[request.callbackAddress][request.callbackSelector], "there must be a completed latter request with same callback"); delete requestMap[_requestMsgHash]; } /** @notice Extend the time lock of a pending request. * * @dev Requests made by the primary account receive the default time lock. * This function allows the primary account to apply the extended time lock * to one its own requests. * * @param _requestMsgHash The request message hash of a pending request. */ function extendRequestTimeLock(bytes32 _requestMsgHash) public onlyPrimary { Request storage request = requestMap[_requestMsgHash]; // reject 1null1 results from the map lookup // this can only be the case if an unknown `_requestMsgHash` is received require(request.callbackAddress != address(0), "reject 1null1 results from the map lookup"); // `extendRequestTimeLock` must be idempotent require(request.extended != true, "`extendRequestTimeLock` must be idempotent"); // set the `extended` flag; note that this is never unset request.extended = true; emit TimeLockExtended(request.timestamp + extendedTimeLock, _requestMsgHash); } }
10,979
16
// Alex Stanoev/update product quantity by ID/check if index is valid and replace the old quantity with the newQuantity/ID of a product/newQuantity of a product
function update(bytes32 ID, uint newQuantity) public onlyValidProduct(ID) onlyOwner { // check if newQuantity param is different then current product quantity require(newQuantity != products[ID].quantity); // set product quantity to be equal to newQuantity param products[ID].quantity = newQuantity; // execute event UpdateProduct emit UpdateProduct(ID, newQuantity, msg.sender); }
function update(bytes32 ID, uint newQuantity) public onlyValidProduct(ID) onlyOwner { // check if newQuantity param is different then current product quantity require(newQuantity != products[ID].quantity); // set product quantity to be equal to newQuantity param products[ID].quantity = newQuantity; // execute event UpdateProduct emit UpdateProduct(ID, newQuantity, msg.sender); }
38,938
395
// The number of blocks that credit will be distributed over to depositors.
uint256 creditUnlockBlocks;
uint256 creditUnlockBlocks;
30,361
191
// Remember the initial block number // Read the previous values out of storage // Calculate the current borrow interest rate // Calculate the number of blocks elapsed since the last accrual //Calculate the interest accumulated into borrows and reserves and the new index: simpleInterestFactor = borrowRateblockDelta interestAccumulated = simpleInterestFactortotalBorrows totalBorrowsNew = interestAccumulated + totalBorrows totalReservesNew = interestAccumulatedreserveFactor + totalReserves borrowIndexNew = simpleInterestFactorborrowIndex + borrowIndex /
Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; uint[] memory res = new uint[](6);
Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; uint[] memory res = new uint[](6);
46,055
286
// The multiplication in the next line is necessary because when slicing multiples of 32 bytes (lengthmod == 0) the following copy loop was copying the origin's length and then ending prematurely not copying everything it should.
let mc := add( add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)) ) let end := add(mc, _length) for {
let mc := add( add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)) ) let end := add(mc, _length) for {
21,307
4
// Change reward address of the node operator `_id` to `_rewardAddress`/
function setNodeOperatorRewardAddress(uint256 _id, address _rewardAddress) external;
function setNodeOperatorRewardAddress(uint256 _id, address _rewardAddress) external;
27,715
434
// expmods_and_points.points[39] = -(g^76z).
mstore(add(expmodsAndPoints, 0x8a0), point)
mstore(add(expmodsAndPoints, 0x8a0), point)
77,639
2
// curve
address private constant SWAPS = 0xD1602F68CC7C4c7B59D686243EA35a9C73B0c6a2;
address private constant SWAPS = 0xD1602F68CC7C4c7B59D686243EA35a9C73B0c6a2;
46,070
355
// Update balance of the winner
balances[winningAddress] = balances[winningAddress].add(netWinnings);
balances[winningAddress] = balances[winningAddress].add(netWinnings);
55,270
43
// Reverts if beneficiary is not whitelisted. Can be used when extending this contract. _beneficiary the address which must be whitelisted by the KYC process in order to pass. /
modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; }
modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; }
7,734
315
// Setter for owner to stop the registries creation or not/locked the new state
function setLocked(bool locked) external onlyOwner { _locked = locked; }
function setLocked(bool locked) external onlyOwner { _locked = locked; }
44,365
2
// mapping that reference each Hashtro by their token id
mapping(uint256 => Hashtro) private _tokenDetails; // 0 -> however many get created mapping(uint256 => string) public tokenURI; string public name; string public symbol; uint256 public tokensInCirculation;
mapping(uint256 => Hashtro) private _tokenDetails; // 0 -> however many get created mapping(uint256 => string) public tokenURI; string public name; string public symbol; uint256 public tokensInCirculation;
57,971
131
// Get the current voting power for `_tokenId`/Adheres to the ERC20 `balanceOf` interface for Aragon compatibility/_tokenId NFT for lock/_t Epoch time to return voting power at/ return User voting power
function _balanceOfNFT(uint _tokenId, uint _t) internal view returns (uint) { uint _epoch = user_point_epoch[_tokenId]; if (_epoch == 0) { return 0; } else { Point memory last_point = user_point_history[_tokenId][_epoch]; last_point.bias -= last_point.slope * int128(int256(_t) - int256(last_point.ts)); if (last_point.bias < 0) { last_point.bias = 0; } return uint(int256(last_point.bias)); } }
function _balanceOfNFT(uint _tokenId, uint _t) internal view returns (uint) { uint _epoch = user_point_epoch[_tokenId]; if (_epoch == 0) { return 0; } else { Point memory last_point = user_point_history[_tokenId][_epoch]; last_point.bias -= last_point.slope * int128(int256(_t) - int256(last_point.ts)); if (last_point.bias < 0) { last_point.bias = 0; } return uint(int256(last_point.bias)); } }
25,779
1
// Define the ethFee variable
uint256 public ethFee = 0.08 ether;
uint256 public ethFee = 0.08 ether;
6,431
132
// Calculate the current borrow interest rate // Remember the initial block number // Calculate the number of blocks elapsed since the last accrual //Calculate the interest accumulated into borrows and reserves and the new index: simpleInterestFactor = borrowRateblockDelta interestAccumulated = simpleInterestFactortotalBorrows totalBorrowsNew = interestAccumulated + totalBorrows totalReservesNew = interestAccumulatedreserveFactor + totalReserves borrowIndexNew = simpleInterestFactorborrowIndex + borrowIndex /
(vars.mathErr, vars.simpleInterestFactor) = mulScalar(Exp({mantissa: vars.borrowRateMantissa}), vars.blockDelta);
(vars.mathErr, vars.simpleInterestFactor) = mulScalar(Exp({mantissa: vars.borrowRateMantissa}), vars.blockDelta);
6,006
8
// Return the current Dutch auction price and the current price step. /
function _currentAuctionPrice() internal view returns (uint256 price) { DutchAuctionInfo memory data = _dutchAuction; // copy auction settings from storage to memory uint256 elapsedTime = block.timestamp < data.startTime ? 0 : block.timestamp - data.startTime; // compute the elapsed time uint256 numSteps = elapsedTime/data.reductionTimestep; if(data.compoundReduction){ price = data.startPrice.decrementCompound_Mp5(data.reductionRate, numSteps); } else{ price = data.startPrice.decrementConstant_VfL(data.reductionRate, numSteps); } }
function _currentAuctionPrice() internal view returns (uint256 price) { DutchAuctionInfo memory data = _dutchAuction; // copy auction settings from storage to memory uint256 elapsedTime = block.timestamp < data.startTime ? 0 : block.timestamp - data.startTime; // compute the elapsed time uint256 numSteps = elapsedTime/data.reductionTimestep; if(data.compoundReduction){ price = data.startPrice.decrementCompound_Mp5(data.reductionRate, numSteps); } else{ price = data.startPrice.decrementConstant_VfL(data.reductionRate, numSteps); } }
14,883
134
// USDT代币地址
address constant USDT_TOKEN_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address constant USDT_TOKEN_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
26,633
10
// Set the provided address as the initial owner of the smart contract
_transferOwnership(ownerOfTheSmartContract); usdtToken = IERC20(_usdtTokenAddress);
_transferOwnership(ownerOfTheSmartContract); usdtToken = IERC20(_usdtTokenAddress);
23,426
233
// Gets the total number of positions, defined as the following:- Each component has a default position if its virtual unit is > 0- Each component's external positions module is counted as a position /
function _getPositionCount() internal view returns (uint256) { uint256 positionCount; for (uint256 i = 0; i < components.length; i++) { address component = components[i]; // Increment the position count if the default position is > 0 if (_defaultPositionVirtualUnit(component) > 0) { positionCount++; } // Increment the position count by each external position module address[] memory externalModules = _externalPositionModules(component); if (externalModules.length > 0) { positionCount = positionCount.add(externalModules.length); } } return positionCount; }
function _getPositionCount() internal view returns (uint256) { uint256 positionCount; for (uint256 i = 0; i < components.length; i++) { address component = components[i]; // Increment the position count if the default position is > 0 if (_defaultPositionVirtualUnit(component) > 0) { positionCount++; } // Increment the position count by each external position module address[] memory externalModules = _externalPositionModules(component); if (externalModules.length > 0) { positionCount = positionCount.add(externalModules.length); } } return positionCount; }
15,051
64
// TESTING
function mockTime(uint256 itemID, uint256 _newTime) public isOwner { marketItems[itemID].timeWhenRentStarted = _newTime; }
function mockTime(uint256 itemID, uint256 _newTime) public isOwner { marketItems[itemID].timeWhenRentStarted = _newTime; }
19,483
68
// make sure the mint didnt push maxScalingFactor too low
require(reethScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
require(reethScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
58,239
58
// send preferred token
function _send(uint256 wAmount, TYPE _to) internal { if (_to == TYPE.WRAPPED) { gOHM.safeTransfer(msg.sender, wAmount); } else if (_to == TYPE.STAKED) { newStaking.unwrap(msg.sender, wAmount); } else if (_to == TYPE.UNSTAKED) { newStaking.unstake(msg.sender, wAmount, false, false); } }
function _send(uint256 wAmount, TYPE _to) internal { if (_to == TYPE.WRAPPED) { gOHM.safeTransfer(msg.sender, wAmount); } else if (_to == TYPE.STAKED) { newStaking.unwrap(msg.sender, wAmount); } else if (_to == TYPE.UNSTAKED) { newStaking.unstake(msg.sender, wAmount, false, false); } }
7,106
121
// Unit of post fee. 0.0001 ether
uint constant DIMI_ETHER = 0.0001 ether; // 1 ether / 10000;
uint constant DIMI_ETHER = 0.0001 ether; // 1 ether / 10000;
36,769
18
// extend a lock with a new unlock date, _index and _lockID ensure the correct lock is changedthis prevents errors when a user performs multiple tx per block possibly with varying gas prices /
function relock(address _token, uint256 _index, uint256 _lockID, uint256 _unlock_date) external nonReentrant { require(_unlock_date < 10000000000, "TIMESTAMP INVALID"); // prevents errors when timestamp entered in milliseconds uint256 lockID = users[msg.sender].locksForToken[_token][_index]; TokenLock storage userLock = tokenLocks[_token][lockID]; require(lockID == _lockID && userLock.owner == msg.sender, "LOCK MISMATCH"); // ensures correct lock is affected require(userLock.unlockDate < _unlock_date, "UNLOCK BEFORE"); // If fee on relock enabled, then charge it if (gFees.feeOnRelock) { uint256 liquidityFee = userLock.amount.mul(gFees.liquidityFee).div(1000); uint256 amountLocked = userLock.amount.sub(liquidityFee); userLock.amount = amountLocked; // send univ2 fee to fee collector address IERC20(_token).safeTransfer(feeCollector, liquidityFee); } userLock.unlockDate = _unlock_date; }
function relock(address _token, uint256 _index, uint256 _lockID, uint256 _unlock_date) external nonReentrant { require(_unlock_date < 10000000000, "TIMESTAMP INVALID"); // prevents errors when timestamp entered in milliseconds uint256 lockID = users[msg.sender].locksForToken[_token][_index]; TokenLock storage userLock = tokenLocks[_token][lockID]; require(lockID == _lockID && userLock.owner == msg.sender, "LOCK MISMATCH"); // ensures correct lock is affected require(userLock.unlockDate < _unlock_date, "UNLOCK BEFORE"); // If fee on relock enabled, then charge it if (gFees.feeOnRelock) { uint256 liquidityFee = userLock.amount.mul(gFees.liquidityFee).div(1000); uint256 amountLocked = userLock.amount.sub(liquidityFee); userLock.amount = amountLocked; // send univ2 fee to fee collector address IERC20(_token).safeTransfer(feeCollector, liquidityFee); } userLock.unlockDate = _unlock_date; }
39,695
86
// Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. /
function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } }
function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } }
22,389
52
// Internal mint function. Checks max supply./_receiver The address to receive the RAD./_amount The amount of RAD to mint.
function _mint(address _receiver, uint256 _amount) internal override { require(totalSupply + _amount <= MAX_SUPPLY, "Radcoin: max supply exceeded"); super._mint(_receiver, _amount); }
function _mint(address _receiver, uint256 _amount) internal override { require(totalSupply + _amount <= MAX_SUPPLY, "Radcoin: max supply exceeded"); super._mint(_receiver, _amount); }
38,849
10
// Routes
address[] public outputToWrappedRoute; address[] public wrappedToLp0Route; address[] public wrappedToLp1Route; address[] customPath;
address[] public outputToWrappedRoute; address[] public wrappedToLp0Route; address[] public wrappedToLp1Route; address[] customPath;
7,672
143
// Returns the total quantity for a token ID_id uint256 ID of the token to query return amount of token in existence/
function totalSupply( uint256 _id
function totalSupply( uint256 _id
45,595
386
// --- Variables ---
uint256 internal storedIndex;
uint256 internal storedIndex;
30,951
5
// This contract can be deployed without modification, but it is intended as a templateto add more advanced bridge interaction to a custom ERC-721 contract /
contract ERC721Bridgable is IERC721Bridgable, BridgeMinters, ERC721AUpgradeable { using ECDSAUpgradeable for bytes32; using ECDSAUpgradeable for bytes; function __ERC721Bridgable_init( string memory _name, string memory _symbol, uint256 _maxBatch ) internal onlyInitializing { __ERC721A_init(_name, _symbol, _maxBatch); __BridgeMinters_init(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC721AUpgradeable, IERC165Upgradeable) returns (bool) { return super.supportsInterface(interfaceId) || interfaceId == type(IERC721Bridgable).interfaceId; } /** * @dev Create a new token, of a given ID * SHOULD only be callable by the bridge network * MUST revert if the token already exists * @param _recipient Recipient of newly minted item * @param _id ID of item to mint */ function bridgeMint( address _recipient, uint256 _id ) external virtual override onlyBridge { _mint(_recipient, _id); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
contract ERC721Bridgable is IERC721Bridgable, BridgeMinters, ERC721AUpgradeable { using ECDSAUpgradeable for bytes32; using ECDSAUpgradeable for bytes; function __ERC721Bridgable_init( string memory _name, string memory _symbol, uint256 _maxBatch ) internal onlyInitializing { __ERC721A_init(_name, _symbol, _maxBatch); __BridgeMinters_init(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC721AUpgradeable, IERC165Upgradeable) returns (bool) { return super.supportsInterface(interfaceId) || interfaceId == type(IERC721Bridgable).interfaceId; } /** * @dev Create a new token, of a given ID * SHOULD only be callable by the bridge network * MUST revert if the token already exists * @param _recipient Recipient of newly minted item * @param _id ID of item to mint */ function bridgeMint( address _recipient, uint256 _id ) external virtual override onlyBridge { _mint(_recipient, _id); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
17,886
10
// Check if given owner matches the component's owner. Check that given target matches component's contract address.
if (owner != _owner || contractAddress != _target) { return false; }
if (owner != _owner || contractAddress != _target) { return false; }
35,422