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
57
// override section
function supportsInterface(bytes4 interfaceId) public view override(ERC721A, AccessControl) returns (bool)
function supportsInterface(bytes4 interfaceId) public view override(ERC721A, AccessControl) returns (bool)
25,006
316
// Send Ether to BEther to mint /
function () external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); }
function () external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); }
1,607
8
// total borrow
mapping(address => uint256) normalizedTotalBorrow;
mapping(address => uint256) normalizedTotalBorrow;
39,851
95
// Creates and starts the airdrop/_tokenOWL The OWL token contract/_tokenGNO The GNO token contract/_endTime The unix epoch timestamp in seconds of the time airdrop ends
function OWLAirdrop(TokenOWL _tokenOWL, TokenGNO _tokenGNO, uint _endTime) public
function OWLAirdrop(TokenOWL _tokenOWL, TokenGNO _tokenGNO, uint _endTime) public
64,612
0
// Owner of this contract
address public owner;
address public owner;
18,642
129
// no lockups for this user
return true;
return true;
41,862
75
// Adds DMG to the already-existing farming season, if there is one. Else, this function reverts.dmgAmount The amount of DMG that will be added to the existing campaign. /
function addToFarmingSeason(
function addToFarmingSeason(
18,372
139
// Security - Emergency shutdown, most of operations are unavailable in emergency mode
bool public override emergencyShutdown;
bool public override emergencyShutdown;
45,431
50
// Add minter _minter minter /
function addMinter(address _minter) external onlyGov { minters[_minter] = true; }
function addMinter(address _minter) external onlyGov { minters[_minter] = true; }
9,134
171
// Mask of all 256 bits in packed address data except the 64 bits for `aux`.
uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
502
98
// Modifier that only allows calls from the launcher contract
modifier onlyLauncher() { require(msg.sender == launcher, ""); _; }
modifier onlyLauncher() { require(msg.sender == launcher, ""); _; }
2,789
48
// Getter function of the expiration date of an order
function getExpiration(uint256 id) public view returns(uint256 expiration){ Order memory o = orders[id]; uint256 exp = o.expirationDate; return exp; }
function getExpiration(uint256 id) public view returns(uint256 expiration){ Order memory o = orders[id]; uint256 exp = o.expirationDate; return exp; }
38,553
120
// Update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerDivToken * _amountOfDivTokens); payoutsTo_[_toAddress] += (int256) (profitPerDivToken * _amountOfDivTokens); uint length; assembly { length := extcodesize(_toAddress) }
payoutsTo_[_customerAddress] -= (int256) (profitPerDivToken * _amountOfDivTokens); payoutsTo_[_toAddress] += (int256) (profitPerDivToken * _amountOfDivTokens); uint length; assembly { length := extcodesize(_toAddress) }
16,602
4
// Spending approval for standard token pattern (see `token/EIP20.sol`)
contract DSApprovalDB is DSAuth, DSApprovalDBEvents { mapping(address => mapping( address=>uint)) _approvals; function setApproval( address holder, address spender, uint amount ) auth() { _approvals[holder][spender] = amount; Approval( holder, spender, amount ); } function getApproval( address holder, address spender ) returns (uint amount ) { return _approvals[holder][spender]; } }
contract DSApprovalDB is DSAuth, DSApprovalDBEvents { mapping(address => mapping( address=>uint)) _approvals; function setApproval( address holder, address spender, uint amount ) auth() { _approvals[holder][spender] = amount; Approval( holder, spender, amount ); } function getApproval( address holder, address spender ) returns (uint amount ) { return _approvals[holder][spender]; } }
46,958
80
// Withdraws sale commission, CFO-only functionality/_to Address for commission to be sent to
function withdrawCommission(address _to) external onlyCFO { uint256 balance = commissionBalance; address transferee = (_to == address(0)) ? cfoAddress : _to; commissionBalance = 0; if (balance > 0) { transferee.transfer(balance); } FundsWithdrawn(transferee, balance); }
function withdrawCommission(address _to) external onlyCFO { uint256 balance = commissionBalance; address transferee = (_to == address(0)) ? cfoAddress : _to; commissionBalance = 0; if (balance > 0) { transferee.transfer(balance); } FundsWithdrawn(transferee, balance); }
29,809
9
// Approves upgradeability to the new asset pool./ Allows governance to set a new asset pool so the underwriters/ can move their collateral tokens to a new asset pool without/ having to wait for the withdrawal delay./_newAssetPool New asset pool
function approveNewAssetPoolUpgrade(IAssetPoolUpgrade _newAssetPool) external onlyOwner
function approveNewAssetPoolUpgrade(IAssetPoolUpgrade _newAssetPool) external onlyOwner
48,220
149
// Struct and Enum
enum Side {BUY, SELL} enum PnlCalcOption {SPOT_PRICE, TWAP} /// @notice This struct records personal position information /// @param size denominated in amm.baseAsset /// @param margin isolated margin /// @param openNotional the quoteAsset value of position when opening position. the cost of the position /// @param lastUpdatedCumulativePremiumFraction for calculating funding payment, record at the moment every time when trader open/reduce/close position /// @param lastUpdatedCumulativeOvernightFeeRate for calculating holding fee, record at the moment every time when trader open/reduce/close position /// @param liquidityHistoryIndex /// @param blockNumber the block number of the last position struct Position { SignedDecimal.signedDecimal size; Decimal.decimal margin; Decimal.decimal openNotional; SignedDecimal.signedDecimal lastUpdatedCumulativePremiumFraction; Decimal.decimal lastUpdatedCumulativeOvernightFeeRate; uint256 liquidityHistoryIndex; uint256 blockNumber; }
enum Side {BUY, SELL} enum PnlCalcOption {SPOT_PRICE, TWAP} /// @notice This struct records personal position information /// @param size denominated in amm.baseAsset /// @param margin isolated margin /// @param openNotional the quoteAsset value of position when opening position. the cost of the position /// @param lastUpdatedCumulativePremiumFraction for calculating funding payment, record at the moment every time when trader open/reduce/close position /// @param lastUpdatedCumulativeOvernightFeeRate for calculating holding fee, record at the moment every time when trader open/reduce/close position /// @param liquidityHistoryIndex /// @param blockNumber the block number of the last position struct Position { SignedDecimal.signedDecimal size; Decimal.decimal margin; Decimal.decimal openNotional; SignedDecimal.signedDecimal lastUpdatedCumulativePremiumFraction; Decimal.decimal lastUpdatedCumulativeOvernightFeeRate; uint256 liquidityHistoryIndex; uint256 blockNumber; }
6,816
1,021
// https:etherscan.io/address/0x834Ef6c82D431Ac9A7A6B66325F185b2430780D7
address public constant new_FuturesMarketManager_contract = 0x834Ef6c82D431Ac9A7A6B66325F185b2430780D7;
address public constant new_FuturesMarketManager_contract = 0x834Ef6c82D431Ac9A7A6B66325F185b2430780D7;
34,478
193
// Executes a pending transfer for a wallet.The destination address is automatically added to the whitelist. The method can be called by anyone to enable orchestration._wallet The target wallet._token The token of the pending transfer. _to The destination address of the pending transfer._amount The amount of token to transfer of the pending transfer._block The block at which the pending transfer was created./
function executePendingTransfer( BaseWallet _wallet, address _token, address _to, uint _amount, bytes _data, uint _block ) public onlyWhenUnlocked(_wallet)
function executePendingTransfer( BaseWallet _wallet, address _token, address _to, uint _amount, bytes _data, uint _block ) public onlyWhenUnlocked(_wallet)
11,205
17
// libraries
import {Create2} from "@openzeppelin/contracts/utils/Create2.sol"; import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol"; import {BytesLib} from "solidity-bytes-utils/contracts/BytesLib.sol"; import {ErrorHandlerLib} from "@erc725/smart-contracts/contracts/utils/ErrorHandlerLib.sol"; /** * @dev UniversalFactory contract can be used to deploy CREATE2 contracts; normal contracts and minimal * proxies (EIP-1167) with the ability to deploy the same contract at the same address on different chains. * If the contract has a constructor, the arguments will be part of the byteCode * If the contract has an `initialize` function, the parameters of this function will be included in * the salt to ensure that the parameters of the contract should be the same on each chain. * * Security measures were taken to avoid deploying proxies from the `deployCreate2(..)` function * to prevent the problem mentioned above. * * This contract should be deployed using Nick's Method. * More information: https://weka.medium.com/how-to-send-ether-to-11-440-people-187e332566b7 */ contract UniversalFactory { using BytesLib for bytes; // The bytecode hash of EIP-1167 Minimal Proxy bytes32 private constant _MINIMAL_PROXY_BYTECODE_HASH_PT1 = 0x72307939328b75c6e301a012c75e0a4e690a99036b95f6e6f4f1b5aba02a9ce4; bytes32 private constant _MINIMAL_PROXY_BYTECODE_HASH_PT2 = 0x11a195f66c9175f46895bae2006d40848a680c7068b9fc4af248ff9a54a47e45; /** * @dev Throws if the `byteCode` passed to the function is the EIP-1167 Minimal Proxy bytecode */ modifier notMinimalProxy(bytes memory byteCode) virtual { if (byteCode.length == 55) { if ( keccak256(byteCode.slice(0, 20)) == _MINIMAL_PROXY_BYTECODE_HASH_PT1 && keccak256(byteCode.slice(40, 15)) == _MINIMAL_PROXY_BYTECODE_HASH_PT2 ) { revert("Minimal Proxies deployment not allowed"); } } _; } /** * @dev Returns the address where a contract will be stored if deployed via `CREATE2`. The address is * constructed using the parameters below. Any change in one of them will result in a new destination address. */ function calculateAddress( bytes32 byteCodeHash, bytes32 salt, bytes memory initializeCallData ) public view returns (address) { bytes32 generatedSalt = _generateSalt(initializeCallData, salt); return Create2.computeAddress(generatedSalt, byteCodeHash); } /** * @dev Returns the address of an EIP1167 proxy contract. The address is constructed using * the parameters below. Any change in one of them will result in a new destination address. */ function calculateProxyAddress( address baseContract, bytes32 salt, bytes memory initializeCallData ) public view returns (address) { bytes32 generatedSalt = _generateSalt(initializeCallData, salt); return Clones.predictDeterministicAddress(baseContract, generatedSalt); } /** * @dev Deploys a contract using `CREATE2`. The address where the contract will be deployed * can be known in advance via {calculateAddress}. The salt is a combination between an initializable * boolean, `salt` and the `initializeCallData` if the contract is initializable. This method allow users * to have the same contracts at the same address across different chains with the same parameters. * * Using the same `byteCode` and salt multiple time will revert, since * the contract cannot be deployed twice at the same address. * * Deploying a minimal proxy from this function will revert. */ function deployCreate2( bytes memory byteCode, bytes32 salt, bytes memory initializeCallData ) public payable notMinimalProxy(byteCode) returns (address contractCreated) { bytes32 generatedSalt = _generateSalt(initializeCallData, salt); contractCreated = Create2.deploy(msg.value, generatedSalt, byteCode); if (initializeCallData.length > 0) { // solhint-disable avoid-low-level-calls (bool success, bytes memory returnedData) = contractCreated.call(initializeCallData); if (!success) ErrorHandlerLib.revertWithParsedError(returnedData); } } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `baseContract`. * The address where the contract will be deployed can be known in advance via {calculateProxyAddress}. * * This function uses the CREATE2 opcode and a salt to deterministically deploy * the clone. The salt is a combination between an initializable boolean, `salt` * and the `initializeCallData` if the contract is initializable. This method allow users * to have the same contracts at the same address across different chains with the same parameters. * * Using the same `baseContract` and salt multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function deployCreate2Proxy( address baseContract, bytes32 salt, bytes memory initializeCallData ) public payable returns (address proxy) { bytes32 generatedSalt = _generateSalt(initializeCallData, salt); proxy = Clones.cloneDeterministic(baseContract, generatedSalt); if (initializeCallData.length > 0) { // solhint-disable avoid-low-level-calls (bool success, bytes memory returnedData) = proxy.call{value: msg.value}( initializeCallData ); if (!success) ErrorHandlerLib.revertWithParsedError(returnedData); } else { // Return value sent if (msg.value > 0) { // solhint-disable avoid-low-level-calls (bool success, bytes memory returnedData) = payable(msg.sender).call{ value: msg.value }(""); if (!success) ErrorHandlerLib.revertWithParsedError(returnedData); } } } /** internal functions */ /** * @dev Calculates the salt including the initializeCallData, or without but hashing it with a zero bytes padding. */ function _generateSalt(bytes memory initializeCallData, bytes32 salt) internal pure returns (bytes32) { bool initializable = initializeCallData.length > 0; if (initializable) { return keccak256(abi.encodePacked(initializable, initializeCallData, salt)); } else { return keccak256(abi.encodePacked(initializable, salt)); } } }
import {Create2} from "@openzeppelin/contracts/utils/Create2.sol"; import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol"; import {BytesLib} from "solidity-bytes-utils/contracts/BytesLib.sol"; import {ErrorHandlerLib} from "@erc725/smart-contracts/contracts/utils/ErrorHandlerLib.sol"; /** * @dev UniversalFactory contract can be used to deploy CREATE2 contracts; normal contracts and minimal * proxies (EIP-1167) with the ability to deploy the same contract at the same address on different chains. * If the contract has a constructor, the arguments will be part of the byteCode * If the contract has an `initialize` function, the parameters of this function will be included in * the salt to ensure that the parameters of the contract should be the same on each chain. * * Security measures were taken to avoid deploying proxies from the `deployCreate2(..)` function * to prevent the problem mentioned above. * * This contract should be deployed using Nick's Method. * More information: https://weka.medium.com/how-to-send-ether-to-11-440-people-187e332566b7 */ contract UniversalFactory { using BytesLib for bytes; // The bytecode hash of EIP-1167 Minimal Proxy bytes32 private constant _MINIMAL_PROXY_BYTECODE_HASH_PT1 = 0x72307939328b75c6e301a012c75e0a4e690a99036b95f6e6f4f1b5aba02a9ce4; bytes32 private constant _MINIMAL_PROXY_BYTECODE_HASH_PT2 = 0x11a195f66c9175f46895bae2006d40848a680c7068b9fc4af248ff9a54a47e45; /** * @dev Throws if the `byteCode` passed to the function is the EIP-1167 Minimal Proxy bytecode */ modifier notMinimalProxy(bytes memory byteCode) virtual { if (byteCode.length == 55) { if ( keccak256(byteCode.slice(0, 20)) == _MINIMAL_PROXY_BYTECODE_HASH_PT1 && keccak256(byteCode.slice(40, 15)) == _MINIMAL_PROXY_BYTECODE_HASH_PT2 ) { revert("Minimal Proxies deployment not allowed"); } } _; } /** * @dev Returns the address where a contract will be stored if deployed via `CREATE2`. The address is * constructed using the parameters below. Any change in one of them will result in a new destination address. */ function calculateAddress( bytes32 byteCodeHash, bytes32 salt, bytes memory initializeCallData ) public view returns (address) { bytes32 generatedSalt = _generateSalt(initializeCallData, salt); return Create2.computeAddress(generatedSalt, byteCodeHash); } /** * @dev Returns the address of an EIP1167 proxy contract. The address is constructed using * the parameters below. Any change in one of them will result in a new destination address. */ function calculateProxyAddress( address baseContract, bytes32 salt, bytes memory initializeCallData ) public view returns (address) { bytes32 generatedSalt = _generateSalt(initializeCallData, salt); return Clones.predictDeterministicAddress(baseContract, generatedSalt); } /** * @dev Deploys a contract using `CREATE2`. The address where the contract will be deployed * can be known in advance via {calculateAddress}. The salt is a combination between an initializable * boolean, `salt` and the `initializeCallData` if the contract is initializable. This method allow users * to have the same contracts at the same address across different chains with the same parameters. * * Using the same `byteCode` and salt multiple time will revert, since * the contract cannot be deployed twice at the same address. * * Deploying a minimal proxy from this function will revert. */ function deployCreate2( bytes memory byteCode, bytes32 salt, bytes memory initializeCallData ) public payable notMinimalProxy(byteCode) returns (address contractCreated) { bytes32 generatedSalt = _generateSalt(initializeCallData, salt); contractCreated = Create2.deploy(msg.value, generatedSalt, byteCode); if (initializeCallData.length > 0) { // solhint-disable avoid-low-level-calls (bool success, bytes memory returnedData) = contractCreated.call(initializeCallData); if (!success) ErrorHandlerLib.revertWithParsedError(returnedData); } } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `baseContract`. * The address where the contract will be deployed can be known in advance via {calculateProxyAddress}. * * This function uses the CREATE2 opcode and a salt to deterministically deploy * the clone. The salt is a combination between an initializable boolean, `salt` * and the `initializeCallData` if the contract is initializable. This method allow users * to have the same contracts at the same address across different chains with the same parameters. * * Using the same `baseContract` and salt multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function deployCreate2Proxy( address baseContract, bytes32 salt, bytes memory initializeCallData ) public payable returns (address proxy) { bytes32 generatedSalt = _generateSalt(initializeCallData, salt); proxy = Clones.cloneDeterministic(baseContract, generatedSalt); if (initializeCallData.length > 0) { // solhint-disable avoid-low-level-calls (bool success, bytes memory returnedData) = proxy.call{value: msg.value}( initializeCallData ); if (!success) ErrorHandlerLib.revertWithParsedError(returnedData); } else { // Return value sent if (msg.value > 0) { // solhint-disable avoid-low-level-calls (bool success, bytes memory returnedData) = payable(msg.sender).call{ value: msg.value }(""); if (!success) ErrorHandlerLib.revertWithParsedError(returnedData); } } } /** internal functions */ /** * @dev Calculates the salt including the initializeCallData, or without but hashing it with a zero bytes padding. */ function _generateSalt(bytes memory initializeCallData, bytes32 salt) internal pure returns (bytes32) { bool initializable = initializeCallData.length > 0; if (initializable) { return keccak256(abi.encodePacked(initializable, initializeCallData, salt)); } else { return keccak256(abi.encodePacked(initializable, salt)); } } }
5,009
107
// Available tokens to this issuance
function issuanceBalance(address issuance) internal view virtual returns (uint256);
function issuanceBalance(address issuance) internal view virtual returns (uint256);
79,208
61
//
* function approve(address spender, uint256 value) public whenNotPaused returns (bool) { * return super.approve(spender, value); * }
* function approve(address spender, uint256 value) public whenNotPaused returns (bool) { * return super.approve(spender, value); * }
4,447
371
// Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). /
function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } }
function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } }
80,073
6
// Allows current owner to transfer control of the contract to a newOwner.newOwner The address to transfer ownership to.newOwnerWallet The address to transfer ownership to./
function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner
function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner
19,948
127
// globalConstraintsRegisterPre indicate if a globalConstraints is registered as a pre global constraint
mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPre;
mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPre;
40,714
2
// base token /
function base() public view override returns (IERC20) { return base_; }
function base() public view override returns (IERC20) { return base_; }
14,855
84
// Function that lets user claim all rewards from all their nfts
function claimAllRewards() public { require(StakingNFT.balanceOf(_msgSender()) > 0, "User has no stake"); for(uint i = 0; i < StakingNFT.balanceOf(_msgSender()); i++) { uint _currentNFT = StakingNFT.tokenOfOwnerByIndex(_msgSender(), i); claimRewards(_currentNFT); } }
function claimAllRewards() public { require(StakingNFT.balanceOf(_msgSender()) > 0, "User has no stake"); for(uint i = 0; i < StakingNFT.balanceOf(_msgSender()); i++) { uint _currentNFT = StakingNFT.tokenOfOwnerByIndex(_msgSender(), i); claimRewards(_currentNFT); } }
31,306
73
// Refund state for each address
mapping(address => bool) public refunds;
mapping(address => bool) public refunds;
17,417
7
// magic economy numbers
uint256 ethPrice; uint256 minTime; uint256 maxTime; uint256 diffstep; uint256 maxClaims; uint256 maxQuantityPerClaim; uint256 maxClaimsPerAccount; bool validateerc20; bool allowPurchase; bool enabled;
uint256 ethPrice; uint256 minTime; uint256 maxTime; uint256 diffstep; uint256 maxClaims; uint256 maxQuantityPerClaim; uint256 maxClaimsPerAccount; bool validateerc20; bool allowPurchase; bool enabled;
46,796
6
// trigger notification of earnings to be splitearnings uint staking earnings for pool/
event NotifyEarnings(uint earnings);
event NotifyEarnings(uint earnings);
19,699
178
// Mapping for identity tokenIds that have previously claimed
mapping(uint256 => uint256) private _identityClaims;
mapping(uint256 => uint256) private _identityClaims;
20,484
21
// Pre Sale
if(now <= deadline1) { uint256 dateDif = deadline1.sub(now); if (dateDif <= 2 * 1 days) { price = price7; // Round 7 return true; } else if (dateDif <= 4 * 1 days) {
if(now <= deadline1) { uint256 dateDif = deadline1.sub(now); if (dateDif <= 2 * 1 days) { price = price7; // Round 7 return true; } else if (dateDif <= 4 * 1 days) {
35,084
73
// Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.Internal function without access restriction. /
function _transferOwnership(address newOwner) internal virtual override { delete _pendingOwner; super._transferOwnership(newOwner); }
function _transferOwnership(address newOwner) internal virtual override { delete _pendingOwner; super._transferOwnership(newOwner); }
25,324
192
// View function to see pending xrunes on frontend.
function pendingxrune(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accxrunePerShare = pool.accxrunePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 xruneReward = multiplier.mul(xrunePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accxrunePerShare = accxrunePerShare.add(xruneReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accxrunePerShare).div(1e12).sub(user.rewardDebt); }
function pendingxrune(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accxrunePerShare = pool.accxrunePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 xruneReward = multiplier.mul(xrunePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accxrunePerShare = accxrunePerShare.add(xruneReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accxrunePerShare).div(1e12).sub(user.rewardDebt); }
19,579
298
// Internal function for transferring Ether to a designated recipient.It will return true and emit an `EthWithdrawal` event if Ether wassuccessfully transferred - otherwise, it will return false and emit an`ExternalError` event. recipient address payable The account that will receive the Ether. amount uint256 The amount of Ether to transfer.return True if Ether was successfully transferred, else false. /
function _transferETH( address payable recipient, uint256 amount
function _transferETH( address payable recipient, uint256 amount
9,858
372
// Get current unstake lockup duration
function getDecreaseStakeLockupDuration() external view returns (uint256)
function getDecreaseStakeLockupDuration() external view returns (uint256)
3,243
20
// Test contract to test the external methods of AuxiliaryStake. /
contract TestAuxiliaryStake { /* Private Variables */ /* * Addresses and stakes are kept in storage as AuxiliaryStake expects * dynamic arrays as arguments and arrays in memory are always fixed size * in solidity. */ address private initialAddress = address(1337); address[] private initialAddresses; address[] private updateAddresses; uint256 private initialStake = uint256(1337); uint256[] private initialStakes; uint256[] private updateStakes; RevertProxy private proxy; AuxiliaryStake private stake; AuxiliaryStakeWrapper private wrapper; /* External Functions */ /** @notice Resetting the arrays for every test to run independent. */ function beforeEach() external { initialAddresses.length = 0; updateAddresses.length = 0; initialStakes.length = 0; updateStakes.length = 0; } function testUpdateBlock() external { constructContracts(); Assert.equal( stake.currentOstBlockHeight(), uint256(0), "OSTblock height after initialisation should be 0." ); Assert.equal( stake.totalStakes(uint256(0)), initialStake, "Total stake after initialisation should be 1337." ); updateAddresses.push(address(2)); updateStakes.push(uint256(19)); /* * Using the same proxy logic as in the test that is expected to fail * below. The reason is to make sure that the provided gas to the * proxy's execute method would be sufficient to not trigger an out-of- * gas error and have a false-positive test below when expecting a * revert. */ /* Priming the proxy. */ AuxiliaryStakeWrapper(address(proxy)).updateOstBlockHeight( updateAddresses, updateStakes ); /* Making the primed call from the proxy. */ bool result = proxy.execute.gas(200000)(); Assert.isTrue( result, "The stake contract must accept a valid new OSTblock." ); Assert.equal( stake.currentOstBlockHeight(), uint256(1), "OSTblock height after update should be 1." ); Assert.equal( stake.totalStakes(uint256(1)), uint256(1356), "Total stake after update should be 1356." ); Assert.equal( stake.totalStakes(uint256(0)), initialStake, "Initial total stake after update should still be initial." ); /* Validator from construction. */ validateValidator( initialAddress, initialStake, false, uint256(0), uint256(0) ); /* The start height after the first update should be 1. */ validateValidator( address(2), uint256(19), false, uint256(1), uint256(0) ); } function testUpdateBlockInvalidMessageSender() external { initialAddresses.push(initialAddress); initialStakes.push(initialStake); wrapper = new AuxiliaryStakeWrapper(); /* * Address 1 is not the wrapper, thus the wrapper is not allowed to * call the method and it should revert. */ stake = new AuxiliaryStake( address(1), initialAddresses, initialStakes ); wrapper.setAuxiliaryStake(address(stake)); proxy = new RevertProxy(address(wrapper)); updateAddresses.push(address(999)); updateStakes.push(uint256(344)); expectRevertOnUpdateOstBlockHeight( "The stake contract must revert if the caller is not the OSTblock gate." ); } function testUpdateBlockInputArraysMustBeOfSameLength() external { constructContracts(); updateAddresses.push(address(85)); updateAddresses.push(address(86)); updateStakes.push(uint256(344)); expectRevertOnUpdateOstBlockHeight( "The stake contract must revert if the addresses array is longer." ); /* The other array may also not be longer. */ updateStakes.push(uint256(345)); updateStakes.push(uint256(346)); expectRevertOnUpdateOstBlockHeight( "The stake contract must revert if the stakes array is longer." ); } function testUpdateBlockStakeMustBeGreaterZero() external { constructContracts(); updateAddresses.push(address(85)); updateStakes.push(uint256(0)); expectRevertOnUpdateOstBlockHeight( "The stake contract must revert if the stake is zero." ); } function testUpdateBlockValidatorAddressMustNotBeZero() external { constructContracts(); updateAddresses.push(address(0)); updateStakes.push(uint256(30000)); expectRevertOnUpdateOstBlockHeight( "The stake contract must revert if the address is zero." ); } function testUpdateBlockUpdateOstBlockWithRepeatedValidator() external { constructContracts(); updateStakes.push(uint256(344)); expectRevertOnUpdateOstBlockHeight( "The stake contract must revert if a validator address already exists." ); } /* Private Functions */ /** * @notice Helper method to construct the contracts with default values and * dependencies. */ function constructContracts() private { initialAddresses.push(initialAddress); initialStakes.push(initialStake); wrapper = new AuxiliaryStakeWrapper(); stake = new AuxiliaryStake( address(wrapper), initialAddresses, initialStakes ); wrapper.setAuxiliaryStake(address(stake)); proxy = new RevertProxy(address(wrapper)); } /** * @notice Does a `updateOstBlockHeight()` call with the RevertProxy and * expects the method under test to revert. * * @param _errorMessage The message to print if the contract does not * revert. */ function expectRevertOnUpdateOstBlockHeight(string _errorMessage) private { /* Priming the proxy. */ AuxiliaryStakeWrapper(address(proxy)).updateOstBlockHeight( updateAddresses, updateStakes ); expectRevert(_errorMessage); } /** * @notice Using the RevertProxy to make the currently primed call. Expects * the primed call to revert in the method under test. * * @param _errorMessage The message to print if the contract does not * revert. */ function expectRevert(string _errorMessage) private { /* Making the primed call from the proxy. */ bool result = proxy.execute.gas(200000)(); Assert.isFalse( result, _errorMessage ); } /** * @notice Gets a validator from the AuxiliaryStake address based on the * expected address and then compares all fields to their expected * values. Fails the test if any field does not match. * * @param _expectedAddress The expected address of the validator. * @param _expectedStake The expected stake of the validator. * @param _expectedEnded The expected ended of the validator. * @param _expectedStartHeight The expected start height of the validator. * @param _expectedEndHeight The expected end height of the validator. */ function validateValidator( address _expectedAddress, uint256 _expectedStake, bool _expectedEnded, uint256 _expectedStartHeight, uint256 _expectedEndHeight ) private { address vAuxAddress; uint256 vStake; bool vEnded; uint256 vStartHeight; uint256 vEndHeight; ( vAuxAddress, vStake, vEnded, vStartHeight, vEndHeight ) = stake.validators(_expectedAddress); Assert.equal( vAuxAddress, _expectedAddress, "Did not store the correct address of the validator." ); Assert.equal( vStake, _expectedStake, "Did not store the correct stake of the validator." ); Assert.equal( vEnded, _expectedEnded, "Did not store the correct ended of the validator." ); Assert.equal( vStartHeight, _expectedStartHeight, "Did not store the correct start height of the validator." ); Assert.equal( vEndHeight, _expectedEndHeight, "Did not store the correct end height of the validator." ); } }
contract TestAuxiliaryStake { /* Private Variables */ /* * Addresses and stakes are kept in storage as AuxiliaryStake expects * dynamic arrays as arguments and arrays in memory are always fixed size * in solidity. */ address private initialAddress = address(1337); address[] private initialAddresses; address[] private updateAddresses; uint256 private initialStake = uint256(1337); uint256[] private initialStakes; uint256[] private updateStakes; RevertProxy private proxy; AuxiliaryStake private stake; AuxiliaryStakeWrapper private wrapper; /* External Functions */ /** @notice Resetting the arrays for every test to run independent. */ function beforeEach() external { initialAddresses.length = 0; updateAddresses.length = 0; initialStakes.length = 0; updateStakes.length = 0; } function testUpdateBlock() external { constructContracts(); Assert.equal( stake.currentOstBlockHeight(), uint256(0), "OSTblock height after initialisation should be 0." ); Assert.equal( stake.totalStakes(uint256(0)), initialStake, "Total stake after initialisation should be 1337." ); updateAddresses.push(address(2)); updateStakes.push(uint256(19)); /* * Using the same proxy logic as in the test that is expected to fail * below. The reason is to make sure that the provided gas to the * proxy's execute method would be sufficient to not trigger an out-of- * gas error and have a false-positive test below when expecting a * revert. */ /* Priming the proxy. */ AuxiliaryStakeWrapper(address(proxy)).updateOstBlockHeight( updateAddresses, updateStakes ); /* Making the primed call from the proxy. */ bool result = proxy.execute.gas(200000)(); Assert.isTrue( result, "The stake contract must accept a valid new OSTblock." ); Assert.equal( stake.currentOstBlockHeight(), uint256(1), "OSTblock height after update should be 1." ); Assert.equal( stake.totalStakes(uint256(1)), uint256(1356), "Total stake after update should be 1356." ); Assert.equal( stake.totalStakes(uint256(0)), initialStake, "Initial total stake after update should still be initial." ); /* Validator from construction. */ validateValidator( initialAddress, initialStake, false, uint256(0), uint256(0) ); /* The start height after the first update should be 1. */ validateValidator( address(2), uint256(19), false, uint256(1), uint256(0) ); } function testUpdateBlockInvalidMessageSender() external { initialAddresses.push(initialAddress); initialStakes.push(initialStake); wrapper = new AuxiliaryStakeWrapper(); /* * Address 1 is not the wrapper, thus the wrapper is not allowed to * call the method and it should revert. */ stake = new AuxiliaryStake( address(1), initialAddresses, initialStakes ); wrapper.setAuxiliaryStake(address(stake)); proxy = new RevertProxy(address(wrapper)); updateAddresses.push(address(999)); updateStakes.push(uint256(344)); expectRevertOnUpdateOstBlockHeight( "The stake contract must revert if the caller is not the OSTblock gate." ); } function testUpdateBlockInputArraysMustBeOfSameLength() external { constructContracts(); updateAddresses.push(address(85)); updateAddresses.push(address(86)); updateStakes.push(uint256(344)); expectRevertOnUpdateOstBlockHeight( "The stake contract must revert if the addresses array is longer." ); /* The other array may also not be longer. */ updateStakes.push(uint256(345)); updateStakes.push(uint256(346)); expectRevertOnUpdateOstBlockHeight( "The stake contract must revert if the stakes array is longer." ); } function testUpdateBlockStakeMustBeGreaterZero() external { constructContracts(); updateAddresses.push(address(85)); updateStakes.push(uint256(0)); expectRevertOnUpdateOstBlockHeight( "The stake contract must revert if the stake is zero." ); } function testUpdateBlockValidatorAddressMustNotBeZero() external { constructContracts(); updateAddresses.push(address(0)); updateStakes.push(uint256(30000)); expectRevertOnUpdateOstBlockHeight( "The stake contract must revert if the address is zero." ); } function testUpdateBlockUpdateOstBlockWithRepeatedValidator() external { constructContracts(); updateStakes.push(uint256(344)); expectRevertOnUpdateOstBlockHeight( "The stake contract must revert if a validator address already exists." ); } /* Private Functions */ /** * @notice Helper method to construct the contracts with default values and * dependencies. */ function constructContracts() private { initialAddresses.push(initialAddress); initialStakes.push(initialStake); wrapper = new AuxiliaryStakeWrapper(); stake = new AuxiliaryStake( address(wrapper), initialAddresses, initialStakes ); wrapper.setAuxiliaryStake(address(stake)); proxy = new RevertProxy(address(wrapper)); } /** * @notice Does a `updateOstBlockHeight()` call with the RevertProxy and * expects the method under test to revert. * * @param _errorMessage The message to print if the contract does not * revert. */ function expectRevertOnUpdateOstBlockHeight(string _errorMessage) private { /* Priming the proxy. */ AuxiliaryStakeWrapper(address(proxy)).updateOstBlockHeight( updateAddresses, updateStakes ); expectRevert(_errorMessage); } /** * @notice Using the RevertProxy to make the currently primed call. Expects * the primed call to revert in the method under test. * * @param _errorMessage The message to print if the contract does not * revert. */ function expectRevert(string _errorMessage) private { /* Making the primed call from the proxy. */ bool result = proxy.execute.gas(200000)(); Assert.isFalse( result, _errorMessage ); } /** * @notice Gets a validator from the AuxiliaryStake address based on the * expected address and then compares all fields to their expected * values. Fails the test if any field does not match. * * @param _expectedAddress The expected address of the validator. * @param _expectedStake The expected stake of the validator. * @param _expectedEnded The expected ended of the validator. * @param _expectedStartHeight The expected start height of the validator. * @param _expectedEndHeight The expected end height of the validator. */ function validateValidator( address _expectedAddress, uint256 _expectedStake, bool _expectedEnded, uint256 _expectedStartHeight, uint256 _expectedEndHeight ) private { address vAuxAddress; uint256 vStake; bool vEnded; uint256 vStartHeight; uint256 vEndHeight; ( vAuxAddress, vStake, vEnded, vStartHeight, vEndHeight ) = stake.validators(_expectedAddress); Assert.equal( vAuxAddress, _expectedAddress, "Did not store the correct address of the validator." ); Assert.equal( vStake, _expectedStake, "Did not store the correct stake of the validator." ); Assert.equal( vEnded, _expectedEnded, "Did not store the correct ended of the validator." ); Assert.equal( vStartHeight, _expectedStartHeight, "Did not store the correct start height of the validator." ); Assert.equal( vEndHeight, _expectedEndHeight, "Did not store the correct end height of the validator." ); } }
4,394
21
// Initialize PERMIT_TYPEHASH for permit function
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
5,694
128
// Accepts the given amount of collateral token as a deposit and/ mints at least a minAmountToMint underwriter tokens representing/ pool's ownership./Before calling this function, collateral token needs to have the/required amount accepted to transfer to the asset pool./amountToDeposit Collateral tokens amount that a user deposits to/the asset pool/minAmountToMint Underwriter minimal tokens amount that a user/expects to receive in exchange for the deposited/collateral tokens/ return The amount of minted underwriter tokens
function depositWithMin(uint256 amountToDeposit, uint256 minAmountToMint) external override returns (uint256)
function depositWithMin(uint256 amountToDeposit, uint256 minAmountToMint) external override returns (uint256)
61,529
120
// Clear approvals
_approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId);
_approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId);
40,511
1
// The values being non-zero value makes deployment a bit more expensive, but in exchange the refund on every call to nonReentrant will be lower in amount. Since refunds are capped to a percentage of the total transaction's gas, it is best to keep them low in cases like this one, to increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; }
uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; }
41,066
177
// minimum amount of block time (seconds) required for an update in reserve ratio
function setMinimumRefreshTime(uint256 val_) external ethLPGov returns (bool)
function setMinimumRefreshTime(uint256 val_) external ethLPGov returns (bool)
10,017
53
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
return Unsigned(a.rawValue.mul(b));
3,535
104
// Increments on state change, used for easier off chain tracking of changes
uint public updateCounter;
uint public updateCounter;
57,693
201
// See {ERC721A-_startTokenId}.
function _startTokenId() internal view virtual override returns (uint256) { return 1; }
function _startTokenId() internal view virtual override returns (uint256) { return 1; }
32,004
7
// freeze the amount of tokens of an account_target the owner of some amount of tokens _name the user name of the _target _value the amount of the tokens _frozenEndTime the end time of the lock period, unit is second _releasePeriod the locking period, unit is second /
function freeze(address _target, string _name, uint256 _value, uint256 _frozenEndTime, uint256 _releasePeriod) onlyOwner public returns (bool) { //require(_tokenAddr != address(0)); require(_target != address(0)); require(_value > 0); require(_frozenEndTime > 0); if (!lockedStorage.isExisted(_target)) { lockedStorage.addAccount(_target, _name, _value); // add new account } // each time the new locked time will be added to the backend require(lockedStorage.addLockedTime(_target, _value, _frozenEndTime, _releasePeriod)); require(lockedStorage.freezeTokens(_target, true, _value)); return true; }
function freeze(address _target, string _name, uint256 _value, uint256 _frozenEndTime, uint256 _releasePeriod) onlyOwner public returns (bool) { //require(_tokenAddr != address(0)); require(_target != address(0)); require(_value > 0); require(_frozenEndTime > 0); if (!lockedStorage.isExisted(_target)) { lockedStorage.addAccount(_target, _name, _value); // add new account } // each time the new locked time will be added to the backend require(lockedStorage.addLockedTime(_target, _value, _frozenEndTime, _releasePeriod)); require(lockedStorage.freezeTokens(_target, true, _value)); return true; }
28,273
18
// If called before the ICO, cancel caller's participation in the sale.
if (!bought_tokens) {
if (!bought_tokens) {
53,370
109
// Overload of {ECDSA-recover} that receives the `v`,`r` and `s` signature fields separately. /
function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; }
function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; }
4,415
1
// USER CLAIM REWARDS // claim all rewards from all markets for a single user /
function claimRewardsAllMarkets(address _account) external pure returns (bool) { claimRewardSingleMarketTrA(0, _account); claimRewardSingleMarketTrB(0, _account); return true; }
function claimRewardsAllMarkets(address _account) external pure returns (bool) { claimRewardSingleMarketTrA(0, _account); claimRewardSingleMarketTrB(0, _account); return true; }
71,691
30
// Remove an allowed depositor depositor address /
function removeDepositor(address depositor) external onlyOwner { require(numberOfAllowedDepositors > 0, "Permissioned::removeDepositor, no allowed depositors"); require(allowedDepositors[depositor] == true, "Permissioned::removeDepositor, not allowed"); allowedDepositors[depositor] = false; numberOfAllowedDepositors = numberOfAllowedDepositors.sub(1); emit RemoveDepositor(depositor); }
function removeDepositor(address depositor) external onlyOwner { require(numberOfAllowedDepositors > 0, "Permissioned::removeDepositor, no allowed depositors"); require(allowedDepositors[depositor] == true, "Permissioned::removeDepositor, not allowed"); allowedDepositors[depositor] = false; numberOfAllowedDepositors = numberOfAllowedDepositors.sub(1); emit RemoveDepositor(depositor); }
32,152
31
// See {IERC20-allowance}. /
function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; }
function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; }
4,984
287
// calculates number of keys received given X eth _curEth current amount of eth in contract _newEth eth being spentreturn amount of ticket purchased / /
{ return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); }
{ return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); }
47,751
6
// How long we should wait before swap numerator
uint256 public NUMERATOR_SWAP_WAIT = 4383 days; // 12 normal years + 3 leap days;
uint256 public NUMERATOR_SWAP_WAIT = 4383 days; // 12 normal years + 3 leap days;
12,607
5
// pre sale / sale states:
function preSaleState() external view returns (bool) { return _isPreRelease; }
function preSaleState() external view returns (bool) { return _isPreRelease; }
19,131
49
// return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) { bool nonZeroPurchase = msg.value != 0; return nonZeroPurchase; }
function validPurchase() internal view returns (bool) { bool nonZeroPurchase = msg.value != 0; return nonZeroPurchase; }
31,006
28
// Appends a byte array to the end of the buffer. Reverts if doing so would exceed the capacity of the buffer. buf The buffer to append to. data The data to append.return The original buffer. /
function append(buffer memory buf, bytes data) internal constant returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; }
function append(buffer memory buf, bytes data) internal constant returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; }
9,593
140
// Update the swapAndWithdrawEnabled.Can only be called by the current operator. /
function updateSwapAndLiquifyEnabled(bool _enabled) public onlyOperator { swapAndWithdrawEnabled = _enabled; }
function updateSwapAndLiquifyEnabled(bool _enabled) public onlyOperator { swapAndWithdrawEnabled = _enabled; }
25,134
23
// Construct a new Button token account The initial account to grant all the tokens minter_ The account with minting ability mintingAllowedAfter_ The timestamp after which minting may occur /
constructor( address account, address minter_, uint256 mintingAllowedAfter_
constructor( address account, address minter_, uint256 mintingAllowedAfter_
20,069
86
// capRec[] memory cz = new capRec[](caps.length);
require(capsInEther.length == timesInHours.length); capz.length = 0; for (uint i = 0; i < capsInEther.length; i++) { capRec memory cr; cr.time = timesInHours[i]; cr.amount = capsInEther[i]; capz.push(cr); }
require(capsInEther.length == timesInHours.length); capz.length = 0; for (uint i = 0; i < capsInEther.length; i++) { capRec memory cr; cr.time = timesInHours[i]; cr.amount = capsInEther[i]; capz.push(cr); }
38,185
54
// Conversion rate is in WAD
uint256 _underlyingAmount = _withdrawAmount.mul(WAD).div(_conversionRate());
uint256 _underlyingAmount = _withdrawAmount.mul(WAD).div(_conversionRate());
61,342
58
// hard cap for this tier has not been reached
require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage);
require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage);
2,529
4
// roundabout way of verifying this 1. this address must have the code for 'supportsInterface' (ERC165), and, 2. this address must return true given the hash of the interface for ERC20
if (!candidateContract.supportsInterface(InterfaceSignature_ERC20)) revert(); tokenAddress = candidateContract;
if (!candidateContract.supportsInterface(InterfaceSignature_ERC20)) revert(); tokenAddress = candidateContract;
9,577
97
// Returns the number of unlocked tokens a given userId has available. this is a `view`-only way to determine how many tokens are still locked(info.totalTokensLocked is only accurate after processing lockups which changes state) /
function getLockedTokenCount(address _userId) external view returns (uint lockedTokens)
function getLockedTokenCount(address _userId) external view returns (uint lockedTokens)
41,729
94
// upgrades the implementation of the proxy requirements: - the caller must be the admin of the contract /
function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); }
function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); }
1,633
141
// Return 0 reward if the user has not staked tokens
if (!holders.contains(_holder)) return 0;
if (!holders.contains(_holder)) return 0;
2,554
57
// A permanent NULL node (0x0) in the circular double linked list. NULL.next is the head, and NULL.previous is the tail./
address public constant NULL = 0x0;
address public constant NULL = 0x0;
6,246
9
// send profit
weth.transfer(attacker, weth.balanceOf(address(this))); if (false) { sender; amount0; amount1; }
weth.transfer(attacker, weth.balanceOf(address(this))); if (false) { sender; amount0; amount1; }
2,865
101
// Fallback function that allows to increase _completedAmount if the foundation should ever withdraw more than required to refund rejected swaps amount amount to increase _completedAmount by /
function topupCompletedAmount(uint256 amount) external
function topupCompletedAmount(uint256 amount) external
36,829
4
// Event for deposits. sender The sender amount The amount /
event Deposited(MarginLiquidityPoolInterface pool, address indexed sender, uint256 amount);
event Deposited(MarginLiquidityPoolInterface pool, address indexed sender, uint256 amount);
50,976
3
// allow change of ownership (simple version without events)
function changeOwner(address _owner) external { require(msg.sender == owner); owner = _owner; }
function changeOwner(address _owner) external { require(msg.sender == owner); owner = _owner; }
12,108
0
// ---------------------------------------------------------------------------- Bonus List interface ----------------------------------------------------------------------------
contract RegistryInterface { function isInRegistry(address account) public view returns (bool); }
contract RegistryInterface { function isInRegistry(address account) public view returns (bool); }
16,845
44
// 检测账户余额是否够用
require(balances[_from] >= _value);
require(balances[_from] >= _value);
2,865
4
// Each voter struct is stored in an address
mapping(address => Voter) public voters;
mapping(address => Voter) public voters;
37,109
32
// Initialize ------------------------------------------------------------------ /
function initialize(address _manager, address _migrator) external initializer { _setupRole(MANAGER_ROLE, _manager); _setupRole(MIGRATOR_ROLE, _migrator); }
function initialize(address _manager, address _migrator) external initializer { _setupRole(MANAGER_ROLE, _manager); _setupRole(MIGRATOR_ROLE, _migrator); }
28,760
2
// the actual ETH/USD conversion rate, after adjusting the extra 0s.
return ethAmountInUsd;
return ethAmountInUsd;
12,301
45
// updatePrice: Update level price function invokes by owner /
function updatePrice(uint _level,uint _amount) public onlyOwner { levelPrice[_level] = _amount; }
function updatePrice(uint _level,uint _amount) public onlyOwner { levelPrice[_level] = _amount; }
28,111
2
// The address allowed to notify and update rewards.
address public rewardsDistributor;
address public rewardsDistributor;
13,375
501
// Less efficient than the CREATE2 method below
function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = IUniswapV2Factory(factory).getPair(token0, token1); }
function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = IUniswapV2Factory(factory).getPair(token0, token1); }
12,256
68
// Modifier for accessibility to add deposit.
modifier onlyAccessDeposit { require(msg.sender == owner || depositAccess[msg.sender] == true); _; }
modifier onlyAccessDeposit { require(msg.sender == owner || depositAccess[msg.sender] == true); _; }
11,922
45
// Allow listing depositManager to send deposit
function sendDeposit(uint listingID, address target, uint value, bytes32 ipfsHash) public { Listing storage listing = listings[listingID]; require(listing.depositManager == msg.sender, "depositManager must call"); require(listing.deposit >= value, "Value too high"); listing.deposit -= value; require(tokenAddr.transfer(target, value), "Transfer failed"); emit ListingArbitrated(target, listingID, ipfsHash); }
function sendDeposit(uint listingID, address target, uint value, bytes32 ipfsHash) public { Listing storage listing = listings[listingID]; require(listing.depositManager == msg.sender, "depositManager must call"); require(listing.deposit >= value, "Value too high"); listing.deposit -= value; require(tokenAddr.transfer(target, value), "Transfer failed"); emit ListingArbitrated(target, listingID, ipfsHash); }
44,407
11
// The Water Project - double check
_charity == address(0x060697E9d4EEa886EbeCe57A974Facd53A40865B)
_charity == address(0x060697E9d4EEa886EbeCe57A974Facd53A40865B)
52,190
21
// Function to check the amount of tokens that 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 uint256 specifying the amount of tokens still available for the spender. /
function allowance( address owner, address spender ) public view returns (uint256)
function allowance( address owner, address spender ) public view returns (uint256)
18,146
9
// avsAddress.transfer(sender, avsTokensToReturn);
avsAddress.transfer( sender, st.stakedAVS.add( (avsTokensToReturn.sub(st.stakedAVS)).mul(98).div(100) ) ); emit AVSTokenOutcome( sender, (avsTokensToReturn.sub(st.stakedAVS)).mul(98).div(100), currDay
avsAddress.transfer( sender, st.stakedAVS.add( (avsTokensToReturn.sub(st.stakedAVS)).mul(98).div(100) ) ); emit AVSTokenOutcome( sender, (avsTokensToReturn.sub(st.stakedAVS)).mul(98).div(100), currDay
30,292
19
// returns current impl/
function getImplementation() public view returns (address) { // no need to check _storage, 0x0.getAddress will fail anyway. return _storage.getAddress(__IMPL__); }
function getImplementation() public view returns (address) { // no need to check _storage, 0x0.getAddress will fail anyway. return _storage.getAddress(__IMPL__); }
14,577
225
// Update the address of Sushiswap Router Can only be called by the owner _sushiswapRouter Address of Sushiswap Router /
function setSushiswapRouter(address _sushiswapRouter) public onlyOwner { require(_sushiswapRouter != address(0), "0x0"); emit ChangedAddress( "SUSHISWAP_ROUTER", address(sushiswapRouter), _sushiswapRouter ); sushiswapRouter = IUniswapRouter(_sushiswapRouter); }
function setSushiswapRouter(address _sushiswapRouter) public onlyOwner { require(_sushiswapRouter != address(0), "0x0"); emit ChangedAddress( "SUSHISWAP_ROUTER", address(sushiswapRouter), _sushiswapRouter ); sushiswapRouter = IUniswapRouter(_sushiswapRouter); }
14,471
3
// A descriptive name for a collection of NFTs. /
string internal _name;
string internal _name;
28,031
17
// Only manager is able to call this function Sets the foundation address newFoundation The new foundation address /
function setFoundation(address newFoundation) external onlyManager { require(newFoundation != address(0), "Unit Protocol: ZERO_ADDRESS"); foundation = newFoundation; }
function setFoundation(address newFoundation) external onlyManager { require(newFoundation != address(0), "Unit Protocol: ZERO_ADDRESS"); foundation = newFoundation; }
39,334
188
// gets the max tip in the in the requestQ[51] array and its index within the array??
uint256 newRequestId = TellorGettersLibrary.getTopRequestID(self);
uint256 newRequestId = TellorGettersLibrary.getTopRequestID(self);
15,421
4
// assign the end block
endBlock = _endBlock;
endBlock = _endBlock;
30,245
0
// Administrable/ Contains all the roles mapped to wether an account holds it or not /
mapping(bytes32 => mapping(address => bool)) internal _roles;
mapping(bytes32 => mapping(address => bool)) internal _roles;
32,858
269
// Reserve 100 cactus for team - Giveaways/Prizes etc
uint public cactusReserve = 100; event cactusNameChange(address _by, uint _tokenId, string _name); event licenseisLocked(string _licenseText);
uint public cactusReserve = 100; event cactusNameChange(address _by, uint _tokenId, string _name); event licenseisLocked(string _licenseText);
17,522
182
// Emitted when funds are reclaimed from the LoanToken contract loanToken LoanToken from which funds were reclaimed amount Amount repaid /
event Reclaimed(address indexed pool, address loanToken, uint256 amount);
event Reclaimed(address indexed pool, address loanToken, uint256 amount);
7,465
10
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value);
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value);
313
37
// This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.implement alternative mechanisms to perform token transfer, such as signature-based. Requirements: - `from` cannot be the zero address.- `to` cannot be the zero address.- `tokenId` token must exist and be owned by `from`.- If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. Emits a {Transfer} event. /
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer"); }
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer"); }
20,914
135
// complement token address
function complementToken() external view returns(address); function mint(uint256 _collateralAmount) external; function mintTo(address _recipient, uint256 _collateralAmount) external; function refund(uint256 _tokenAmount) external; function refundTo(address _recipient, uint256 _tokenAmount) external;
function complementToken() external view returns(address); function mint(uint256 _collateralAmount) external; function mintTo(address _recipient, uint256 _collateralAmount) external; function refund(uint256 _tokenAmount) external; function refundTo(address _recipient, uint256 _tokenAmount) external;
37,592
137
// return party_a and party_b accountA address of account 'A' accountB address of account 'B' /
function getParties(address accountA, address accountB) internal pure returns (address, address) { if (isPartyA(accountA, accountB)) { return (accountA, accountB); } else { return (accountB, accountA); } }
function getParties(address accountA, address accountB) internal pure returns (address, address) { if (isPartyA(accountA, accountB)) { return (accountA, accountB); } else { return (accountB, accountA); } }
20,015
270
// This makes calls to contracts that execute arbitrary logic First, it gives the logic contract some tokens Then, it gives msg.senders tokens for fees Then, it calls an arbitrary function on the logic contract invalidationId and invalidationNonce are used for replay prevention. They can be used to implement a per-token nonce by setting the token address as the invalidationId and incrementing the nonce each call. They can be used for nonce-free replay prevention by using a different invalidationId for each call.
function submitLogicCall(
function submitLogicCall(
7,855
92
// sells the token for all reserve tokens using the same percentage for example, if the holder sells 10% of the supply, then they will receive 10% of each reserve token balance in return note that the function can be called also when conversions are disabled _amountamount to liquidate (in the smart token)/
function liquidate(uint256 _amount) public protected multipleReservesOnly
function liquidate(uint256 _amount) public protected multipleReservesOnly
40,924
45
// Inserts a batch into the chain of batches. _transactionRoot Root of the transaction tree for this batch. _batchSize Number of elements in the batch. _numQueuedTransactions Number of queue transactions in the batch. _timestamp The latest batch timestamp. _blockNumber The latest batch blockNumber. /
function _appendBatch( bytes32 _transactionRoot, uint256 _batchSize, uint256 _numQueuedTransactions, uint40 _timestamp, uint40 _blockNumber
function _appendBatch( bytes32 _transactionRoot, uint256 _batchSize, uint256 _numQueuedTransactions, uint40 _timestamp, uint40 _blockNumber
48,343
120
// Global operators mappings / Mapping from (operator, tokenHolder) to authorized status. [TOKEN-HOLDER-SPECIFIC]
mapping(address => mapping(address => bool)) internal _authorizedOperator;
mapping(address => mapping(address => bool)) internal _authorizedOperator;
33,723