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
236
// Modifier for contractor functions
modifier onlyContractor {if (msg.sender != recipient) throw; _;} // Modifier for client functions modifier onlyClient {if (msg.sender != Client()) throw; _;} // Constructor function function PassContractor( address _creator, PassProject _passProject, address _recipient, bool _restore) { if (address(_passProject) == 0) throw; creator = _creator; if (_recipient == 0) _recipient = _creator; recipient = _recipient; passProject = _passProject; if (!_restore) smartContractStartDate = now; proposals.length = 1; }
modifier onlyContractor {if (msg.sender != recipient) throw; _;} // Modifier for client functions modifier onlyClient {if (msg.sender != Client()) throw; _;} // Constructor function function PassContractor( address _creator, PassProject _passProject, address _recipient, bool _restore) { if (address(_passProject) == 0) throw; creator = _creator; if (_recipient == 0) _recipient = _creator; recipient = _recipient; passProject = _passProject; if (!_restore) smartContractStartDate = now; proposals.length = 1; }
7,547
89
// Transfer sold Token to marketingWallet
IERC20(marketingWalletToken).transfer(marketingAddress, IERC20(marketingWalletToken).balanceOf(address(this)));
IERC20(marketingWalletToken).transfer(marketingAddress, IERC20(marketingWalletToken).balanceOf(address(this)));
42,299
5
// Number of blocks to wait before being able to collectRedemption()
uint256 public redemption_delay = 1;
uint256 public redemption_delay = 1;
32,251
52
// used to draw grandpot results weightRange = roundWeightgrandpot / (grandpot - initGrandPot) grandPot = initGrandPot + round investedSum(for grandPot)
function getWeightRange(uint256 grandPot, uint256 initGrandPot, uint256 curRWeight) public pure returns(uint256)
function getWeightRange(uint256 grandPot, uint256 initGrandPot, uint256 curRWeight) public pure returns(uint256)
49,409
8
// Un-stake any available user funds from the contract.May only be called by fund owner.
* Emits an {Unstaked} event. * * Requirements: * - 48hr grace period between requesting unlock and unstaking */ function unstake() external denyReentrant { StakeData storage stakeData = stakeholders[msg.sender]; require(stakeData.amountStaked > 0, "must have staked funds"); require(stakeData.numUnlockRequests > 0, "must request unlock to unstake"); uint256 currentTime = block.timestamp; uint256 amountUnstaked = getAmountUnstaked(stakeData, currentTime.sub(48 hours)); require(amountUnstaked > 0, "no funds available for unstaking"); stakeData.amountStaked = stakeData.amountStaked.sub(amountUnstaked); stakeData.amountRequestedForUnlock = stakeData.amountRequestedForUnlock.sub(amountUnstaked); bool success = tether.approve(address(this), amountUnstaked); require(success, "approve failed"); success = tether.transferFrom(address(this), msg.sender, amountUnstaked); require(success, "transferFrom failed"); emit Unstaked(msg.sender, amountUnstaked, currentTime); }
* Emits an {Unstaked} event. * * Requirements: * - 48hr grace period between requesting unlock and unstaking */ function unstake() external denyReentrant { StakeData storage stakeData = stakeholders[msg.sender]; require(stakeData.amountStaked > 0, "must have staked funds"); require(stakeData.numUnlockRequests > 0, "must request unlock to unstake"); uint256 currentTime = block.timestamp; uint256 amountUnstaked = getAmountUnstaked(stakeData, currentTime.sub(48 hours)); require(amountUnstaked > 0, "no funds available for unstaking"); stakeData.amountStaked = stakeData.amountStaked.sub(amountUnstaked); stakeData.amountRequestedForUnlock = stakeData.amountRequestedForUnlock.sub(amountUnstaked); bool success = tether.approve(address(this), amountUnstaked); require(success, "approve failed"); success = tether.transferFrom(address(this), msg.sender, amountUnstaked); require(success, "transferFrom failed"); emit Unstaked(msg.sender, amountUnstaked, currentTime); }
28,352
9
// Return the length of a `ShortString`. /
function byteLength(ShortString sstr) internal pure returns (uint256) { uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF; if (result > 31) { revert InvalidShortString(); } return result; }
function byteLength(ShortString sstr) internal pure returns (uint256) { uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF; if (result > 31) { revert InvalidShortString(); } return result; }
2,132
24
// Sets receivers of fees for early withdrawal _feeReceiver: Address of fee receiver /
function setFeeReceiver(address _feeReceiver) public onlyOwner { require(_feeReceiver != address(0)); require(_feeReceiver != feeReceiver, "Already set"); feeReceiver = _feeReceiver; emit NewFeeReceiver(_feeReceiver); }
function setFeeReceiver(address _feeReceiver) public onlyOwner { require(_feeReceiver != address(0)); require(_feeReceiver != feeReceiver, "Already set"); feeReceiver = _feeReceiver; emit NewFeeReceiver(_feeReceiver); }
1,356
214
// update loan with new total loan amount, record accrued interests
_updateLoan(pynthLoan, loanAmountAfter, accruedInterestAfter, block.timestamp); emit LoanRepaid(_loanCreatorsAddress, _loanID, _repayAmount, loanAmountAfter);
_updateLoan(pynthLoan, loanAmountAfter, accruedInterestAfter, block.timestamp); emit LoanRepaid(_loanCreatorsAddress, _loanID, _repayAmount, loanAmountAfter);
3,834
42
// Copy over the first `submod` bytes of the new data as in case 1 above.
let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for {
let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for {
5,529
142
// Checks whether the limit has been reached
require( _userInfo[msg.sender][_pid].amountPool <= _poolInformation[_pid].limitPerUserInPaymentTokens, "Deposit: New amount above user limit" );
require( _userInfo[msg.sender][_pid].amountPool <= _poolInformation[_pid].limitPerUserInPaymentTokens, "Deposit: New amount above user limit" );
19,229
189
// Adjust the current reward per block
if (block.number >= periodEndBlock) { currentRewardPerBlock = reward / rewardDurationInBlocks; } else {
if (block.number >= periodEndBlock) { currentRewardPerBlock = reward / rewardDurationInBlocks; } else {
70,029
30
// Token description
string description;
string description;
50,866
148
// Verify a signed authorization for an increase in the allowancegranted to the spender and execute if valid owner Token owner's address (Authorizer) spender Spender's address increment Amount of increase in allowance validAfterThe time after which this is valid (unix time) validBefore The time before which this is valid (unix time) nonce Unique nonce v v of the signature r r of the signature s s of the signature /
function _increaseAllowanceWithAuthorization( address owner, address spender, uint256 increment, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s
function _increaseAllowanceWithAuthorization( address owner, address spender, uint256 increment, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s
36,606
486
// because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral)
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral)
1,747
159
// Request a new Citizen NFT from the owner of the smart contract./ You can request any number of NFTs and pay `citizenshipStampCostInWei` per NFT/ _citizenNumber Number of Citizen NFTs to request
function onlineApplicationForCitizenship(uint256 _citizenNumber) public payable nonReentrant
function onlineApplicationForCitizenship(uint256 _citizenNumber) public payable nonReentrant
13,206
595
// Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX/ in practice. It is possible to exceed that value during liquidation up to 14 potential assets.
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
63,202
14
// only emergency
function withdraw() public payable onlyOwner { msg.sender.transfer(this.balance); }
function withdraw() public payable onlyOwner { msg.sender.transfer(this.balance); }
48,504
14
// Returns if an address is whitelisted & hasn't minted a tokenproof Merkel tree proof_address Address to check/
function isEligibleWhitelist(bytes32[] calldata proof, address _address) external view returns (bool)
function isEligibleWhitelist(bytes32[] calldata proof, address _address) external view returns (bool)
9,101
1
// Reserve 1000 NFTs to team address.
_safeMint(reserve_address, reserve_amount); emit Minted(reserve_address, reserve_amount);
_safeMint(reserve_address, reserve_amount); emit Minted(reserve_address, reserve_amount);
27,664
155
// ============ Functions ============
function one() internal pure returns (D256 memory)
function one() internal pure returns (D256 memory)
40,389
170
// See {IERC1155-isApprovedForAll}. /
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; }
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; }
2,897
48
// Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirementon the return value: the return value is optional (but if data is returned, it must not be false). token The token targeted by the call. data The call data (encoded using abi.encode or one of its variants). /
function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } }
function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } }
35,425
160
// rebasing is not active initially. It can be activated at T+12 hours from deployment time/ boolean showing rebase activation status
bool public rebasingActive;
bool public rebasingActive;
12,719
30
// delete the last selector
ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector];
ds.facetFunctionSelectors[_oldFacetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector];
34,253
176
// Mapping for identity tokenIds that have previously claimed
mapping(uint256 => uint256) private _identityClaims;
mapping(uint256 => uint256) private _identityClaims;
16,953
67
// Not ideal but will only be a small number of units (and saves gas when buying units)
while (startId <= endId) { attackingPower += getUnitsAttack(attacker, startId, unitsOwned[attacker][startId]); stealingPower += getUnitsStealingCapacity(attacker, startId, unitsOwned[attacker][startId]); defendingPower += getUnitsDefense(defender, startId, unitsOwned[defender][startId]); startId++; }
while (startId <= endId) { attackingPower += getUnitsAttack(attacker, startId, unitsOwned[attacker][startId]); stealingPower += getUnitsStealingCapacity(attacker, startId, unitsOwned[attacker][startId]); defendingPower += getUnitsDefense(defender, startId, unitsOwned[defender][startId]); startId++; }
6,777
15
// Swap Dai for Eth
uniswapAmounts = uniswapV2Router02.swapExactTokensForETH( curveDyInDai, minETH, uniswapExchangePath, address(this), block.timestamp );
uniswapAmounts = uniswapV2Router02.swapExactTokensForETH( curveDyInDai, minETH, uniswapExchangePath, address(this), block.timestamp );
17,715
37
// If the message is version 0, then it's a migrated legacy withdrawal. We therefore need to check that the legacy version of the message has not already been relayed.
if (version == 0) { bytes32 oldHash = Hashing.hashCrossDomainMessageV0(_target, _sender, _message, _nonce); require( successfulMessages[oldHash] == false, "CrossDomainMessenger: legacy withdrawal already relayed" ); }
if (version == 0) { bytes32 oldHash = Hashing.hashCrossDomainMessageV0(_target, _sender, _message, _nonce); require( successfulMessages[oldHash] == false, "CrossDomainMessenger: legacy withdrawal already relayed" ); }
11,076
18
// Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whBTCer the operation succeeded.
* Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whBTCer the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this mBTCod brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/BTCereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whBTCer the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); }
* Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whBTCer the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this mBTCod brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/BTCereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whBTCer the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); }
39,470
24
// /Returns an array of all users who have interacted with the contract. return _userArray An array of addresses representing all the users who have interacted with the contract./
function getUserArray() public view returns(address[] memory _userArray){ return usersArray; }
function getUserArray() public view returns(address[] memory _userArray){ return usersArray; }
34,868
64
// Interface for `RelayHub`, the core contract of the GSN. Users should not need to interact with this contractdirectly. how to deploy an instance of `RelayHub` on your local test network. /
contract IRelayHub { // Relay management /** * @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller * of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay * cannot be its own owner. * * All Ether in this function call will be added to the relay's stake. * Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one. * * Emits a {Staked} event. */ function stake(address relayaddr, uint256 unstakeDelay) external payable; /** * @dev Emitted when a relay's stake or unstakeDelay are increased */ event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay); /** * @dev Registers the caller as a relay. * The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA). * * This function can be called multiple times, emitting new {RelayAdded} events. Note that the received * `transactionFee` is not enforced by {relayCall}. * * Emits a {RelayAdded} event. */ function registerRelay(uint256 transactionFee, string memory url) public; /** * @dev Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out * {RelayRemoved} events) lets a client discover the list of available relays. */ event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url); /** * @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed. * * Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be * callable. * * Emits a {RelayRemoved} event. */ function removeRelayByOwner(address relay) public; /** * @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable. */ event RelayRemoved(address indexed relay, uint256 unstakeTime); /** Deletes the relay from the system, and gives back its stake to the owner. * * Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called. * * Emits an {Unstaked} event. */ function unstake(address relay) public; /** * @dev Emitted when a relay is unstaked for, including the returned stake. */ event Unstaked(address indexed relay, uint256 stake); // States a relay can be in enum RelayState { Unknown, // The relay is unknown to the system: it has never been staked for Staked, // The relay has been staked for, but it is not yet active Registered, // The relay has registered itself, and is active (can relay calls) Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake } /** * @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function * to return an empty entry. */ function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state); // Balance management /** * @dev Deposits Ether for a contract, so that it can receive (and pay for) relayed transactions. * * Unused balance can only be withdrawn by the contract itself, by calling {withdraw}. * * Emits a {Deposited} event. */ function depositFor(address target) public payable; /** * @dev Emitted when {depositFor} is called, including the amount and account that was funded. */ event Deposited(address indexed recipient, address indexed from, uint256 amount); /** * @dev Returns an account's deposits. These can be either a contracts's funds, or a relay owner's revenue. */ function balanceOf(address target) external view returns (uint256); /** * Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and * contracts can use it to reduce their funding. * * Emits a {Withdrawn} event. */ function withdraw(uint256 amount, address payable dest) public; /** * @dev Emitted when an account withdraws funds from `RelayHub`. */ event Withdrawn(address indexed account, address indexed dest, uint256 amount); // Relaying /** * @dev Checks if the `RelayHub` will accept a relayed operation. * Multiple things must be true for this to happen: * - all arguments must be signed for by the sender (`from`) * - the sender's nonce must be the current one * - the recipient must accept this transaction (via {acceptRelayedCall}) * * Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error * code if it returns one in {acceptRelayedCall}. */ function canRelay( address relay, address from, address to, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes memory signature, bytes memory approvalData ) public view returns (uint256 status, bytes memory recipientContext); // Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values. enum PreconditionCheck { OK, // All checks passed, the call can be relayed WrongSignature, // The transaction to relay is not signed by requested sender WrongNonce, // The provided nonce has already been used by the sender AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code } /** * @dev Relays a transaction. * * For this to succeed, multiple conditions must be met: * - {canRelay} must `return PreconditionCheck.OK` * - the sender must be a registered relay * - the transaction's gas price must be larger or equal to the one that was requested by the sender * - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the * recipient) use all gas available to them * - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is * spent) * * If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded * function and {postRelayedCall} will be called in that order. * * Parameters: * - `from`: the client originating the request * - `to`: the target {IRelayRecipient} contract * - `encodedFunction`: the function call to relay, including data * - `transactionFee`: fee (%) the relay takes over actual gas cost * - `gasPrice`: gas price the client is willing to pay * - `gasLimit`: gas to forward when calling the encoded function * - `nonce`: client's nonce * - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses * - `approvalData`: dapp-specific data forwared to {acceptRelayedCall}. This value is *not* verified by the * `RelayHub`, but it still can be used for e.g. a signature. * * Emits a {TransactionRelayed} event. */ function relayCall( address from, address to, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes memory signature, bytes memory approvalData ) public; /** * @dev Emitted when an attempt to relay a call failed. * * This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The * actual relayed call was not executed, and the recipient not charged. * * The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values * over 10 are custom recipient error codes returned from {acceptRelayedCall}. */ event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason); /** * @dev Emitted when a transaction is relayed. * Useful when monitoring a relay's operation and relayed calls to a contract * * Note that the actual encoded function might be reverted: this is indicated in the `status` parameter. * * `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner. */ event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge); // Reason error codes for the TransactionRelayed event enum RelayCallStatus { OK, // The transaction was successfully relayed and execution successful - never included in the event RelayedCallFailed, // The transaction was relayed, but the relayed call failed PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing } /** * @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will * spend up to `relayedCallStipend` gas. */ function requiredGas(uint256 relayedCallStipend) public view returns (uint256); /** * @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee. */ function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) public view returns (uint256); // Relay penalization. // Any account can penalize relays, removing them from the system immediately, and rewarding the // reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it // still loses half of its stake. /** * @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and * different data (gas price, gas limit, etc. may be different). * * The (unsigned) transaction data and signature for both transactions must be provided. */ function penalizeRepeatedNonce(bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2) public; /** * @dev Penalize a relay that sent a transaction that didn't target `RelayHub`'s {registerRelay} or {relayCall}. */ function penalizeIllegalTransaction(bytes memory unsignedTx, bytes memory signature) public; /** * @dev Emitted when a relay is penalized. */ event Penalized(address indexed relay, address sender, uint256 amount); /** * @dev Returns an account's nonce in `RelayHub`. */ function getNonce(address from) external view returns (uint256); }
contract IRelayHub { // Relay management /** * @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller * of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay * cannot be its own owner. * * All Ether in this function call will be added to the relay's stake. * Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one. * * Emits a {Staked} event. */ function stake(address relayaddr, uint256 unstakeDelay) external payable; /** * @dev Emitted when a relay's stake or unstakeDelay are increased */ event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay); /** * @dev Registers the caller as a relay. * The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA). * * This function can be called multiple times, emitting new {RelayAdded} events. Note that the received * `transactionFee` is not enforced by {relayCall}. * * Emits a {RelayAdded} event. */ function registerRelay(uint256 transactionFee, string memory url) public; /** * @dev Emitted when a relay is registered or re-registerd. Looking at these events (and filtering out * {RelayRemoved} events) lets a client discover the list of available relays. */ event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url); /** * @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed. * * Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be * callable. * * Emits a {RelayRemoved} event. */ function removeRelayByOwner(address relay) public; /** * @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable. */ event RelayRemoved(address indexed relay, uint256 unstakeTime); /** Deletes the relay from the system, and gives back its stake to the owner. * * Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called. * * Emits an {Unstaked} event. */ function unstake(address relay) public; /** * @dev Emitted when a relay is unstaked for, including the returned stake. */ event Unstaked(address indexed relay, uint256 stake); // States a relay can be in enum RelayState { Unknown, // The relay is unknown to the system: it has never been staked for Staked, // The relay has been staked for, but it is not yet active Registered, // The relay has registered itself, and is active (can relay calls) Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake } /** * @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function * to return an empty entry. */ function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state); // Balance management /** * @dev Deposits Ether for a contract, so that it can receive (and pay for) relayed transactions. * * Unused balance can only be withdrawn by the contract itself, by calling {withdraw}. * * Emits a {Deposited} event. */ function depositFor(address target) public payable; /** * @dev Emitted when {depositFor} is called, including the amount and account that was funded. */ event Deposited(address indexed recipient, address indexed from, uint256 amount); /** * @dev Returns an account's deposits. These can be either a contracts's funds, or a relay owner's revenue. */ function balanceOf(address target) external view returns (uint256); /** * Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and * contracts can use it to reduce their funding. * * Emits a {Withdrawn} event. */ function withdraw(uint256 amount, address payable dest) public; /** * @dev Emitted when an account withdraws funds from `RelayHub`. */ event Withdrawn(address indexed account, address indexed dest, uint256 amount); // Relaying /** * @dev Checks if the `RelayHub` will accept a relayed operation. * Multiple things must be true for this to happen: * - all arguments must be signed for by the sender (`from`) * - the sender's nonce must be the current one * - the recipient must accept this transaction (via {acceptRelayedCall}) * * Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error * code if it returns one in {acceptRelayedCall}. */ function canRelay( address relay, address from, address to, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes memory signature, bytes memory approvalData ) public view returns (uint256 status, bytes memory recipientContext); // Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values. enum PreconditionCheck { OK, // All checks passed, the call can be relayed WrongSignature, // The transaction to relay is not signed by requested sender WrongNonce, // The provided nonce has already been used by the sender AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code } /** * @dev Relays a transaction. * * For this to succeed, multiple conditions must be met: * - {canRelay} must `return PreconditionCheck.OK` * - the sender must be a registered relay * - the transaction's gas price must be larger or equal to the one that was requested by the sender * - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the * recipient) use all gas available to them * - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is * spent) * * If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded * function and {postRelayedCall} will be called in that order. * * Parameters: * - `from`: the client originating the request * - `to`: the target {IRelayRecipient} contract * - `encodedFunction`: the function call to relay, including data * - `transactionFee`: fee (%) the relay takes over actual gas cost * - `gasPrice`: gas price the client is willing to pay * - `gasLimit`: gas to forward when calling the encoded function * - `nonce`: client's nonce * - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses * - `approvalData`: dapp-specific data forwared to {acceptRelayedCall}. This value is *not* verified by the * `RelayHub`, but it still can be used for e.g. a signature. * * Emits a {TransactionRelayed} event. */ function relayCall( address from, address to, bytes memory encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes memory signature, bytes memory approvalData ) public; /** * @dev Emitted when an attempt to relay a call failed. * * This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The * actual relayed call was not executed, and the recipient not charged. * * The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values * over 10 are custom recipient error codes returned from {acceptRelayedCall}. */ event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason); /** * @dev Emitted when a transaction is relayed. * Useful when monitoring a relay's operation and relayed calls to a contract * * Note that the actual encoded function might be reverted: this is indicated in the `status` parameter. * * `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner. */ event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge); // Reason error codes for the TransactionRelayed event enum RelayCallStatus { OK, // The transaction was successfully relayed and execution successful - never included in the event RelayedCallFailed, // The transaction was relayed, but the relayed call failed PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing } /** * @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will * spend up to `relayedCallStipend` gas. */ function requiredGas(uint256 relayedCallStipend) public view returns (uint256); /** * @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee. */ function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) public view returns (uint256); // Relay penalization. // Any account can penalize relays, removing them from the system immediately, and rewarding the // reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it // still loses half of its stake. /** * @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and * different data (gas price, gas limit, etc. may be different). * * The (unsigned) transaction data and signature for both transactions must be provided. */ function penalizeRepeatedNonce(bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2) public; /** * @dev Penalize a relay that sent a transaction that didn't target `RelayHub`'s {registerRelay} or {relayCall}. */ function penalizeIllegalTransaction(bytes memory unsignedTx, bytes memory signature) public; /** * @dev Emitted when a relay is penalized. */ event Penalized(address indexed relay, address sender, uint256 amount); /** * @dev Returns an account's nonce in `RelayHub`. */ function getNonce(address from) external view returns (uint256); }
16,071
222
// minPrice, if decimal is not 18, please reset it
uint256 public minPrice;
uint256 public minPrice;
42,842
546
// Sets the pending governance.// This function reverts if the new pending governance is the zero address or the caller is not the current/ governance. This is to prevent the contract governance being set to the zero address which would deadlock/ privileged contract functionality.//_pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGov { require(_pendingGovernance != ZERO_ADDRESS, "YumVesperVaultD8: governance address cannot be 0x0."); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); }
function setPendingGovernance(address _pendingGovernance) external onlyGov { require(_pendingGovernance != ZERO_ADDRESS, "YumVesperVaultD8: governance address cannot be 0x0."); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); }
31,917
3
// ========== DEPENDENCIES ========== // ========== STRUCTS ========== /
struct Term { uint256 percent; // 4 decimals ( 5000 = 0.5% ) uint256 claimed; // static number uint256 gClaimed; // rebase-tracking number uint256 max; // maximum nominal OHM amount can claim }
struct Term { uint256 percent; // 4 decimals ( 5000 = 0.5% ) uint256 claimed; // static number uint256 gClaimed; // rebase-tracking number uint256 max; // maximum nominal OHM amount can claim }
62,852
12
// If new entry, replace first entry with this one.
if (entry.balance == 0) { entry.next = entries[0x0].next; entries[entries[0x0].next].prev = _address; entries[0x0].next = _address; }
if (entry.balance == 0) { entry.next = entries[0x0].next; entries[entries[0x0].next].prev = _address; entries[0x0].next = _address; }
21,625
73
// Enable the "Pause of exchange". Available to the manager until the TokenSale is completed. The manager cannot turn on the pause, for example, 3 years after the end of the TokenSale. @ Do I have to use the functionno @ When it is possible to callwhile Round2 not ended @ When it is launched automaticallybefore any rounds @ Who can call the functionadmins
function tokenPause() public { require(rightAndRoles.onlyRoles(msg.sender,6)); require(!isFinalized); token.setPause(true); }
function tokenPause() public { require(rightAndRoles.onlyRoles(msg.sender,6)); require(!isFinalized); token.setPause(true); }
39,473
297
// 获得用户原有的余额
uint beforeBal = 0; if (underlyingAssetAddress == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) { beforeBal = _getEthBalance(user); } else {
uint beforeBal = 0; if (underlyingAssetAddress == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) { beforeBal = _getEthBalance(user); } else {
36,650
29
// Mints tokens according to the provided mint request. _req The payload / mint request._signature The signature produced by an account signing the mint request. /
function mintWithSignature(MintRequest calldata _req, bytes calldata _signature) external payable virtual override returns (address signer)
function mintWithSignature(MintRequest calldata _req, bytes calldata _signature) external payable virtual override returns (address signer)
8,972
59
// update hotSeats up and down.
address candidate; uint s; for( s = 0; s<seats; s+=1){ if( oracleConfigurations[ROUNDTABLE_SEATS] > hotSeats ){ candidate = chairsCandidate[hotSeats]; addShares(ORACLE, candidate, totalShares[candidate]); timeSeated[candidate] = now; hotSeats+=1; }
address candidate; uint s; for( s = 0; s<seats; s+=1){ if( oracleConfigurations[ROUNDTABLE_SEATS] > hotSeats ){ candidate = chairsCandidate[hotSeats]; addShares(ORACLE, candidate, totalShares[candidate]); timeSeated[candidate] = now; hotSeats+=1; }
53,947
9
// 用于第三步:正式分析请求时 验证该token是否有效
function isAnalysisLegal(string memory id, string memory analysis_no, string memory preAnalysisToken) public view returns(bool, string memory) { require(keccak256(bytes (id)) != keccak256(""), "分析者 id 不能为空"); require(keccak256(bytes (analysis_no)) != keccak256(""), "分析序号 不能为空"); Record[] memory rList = recordData[id]; if(rList.length == 0) return (false, " 未曾有过数据噢 "); for(uint i = 0; i<rList.length; i++) { string memory a1 = rList[i].anaNo; string memory a2 = rList[i].token; if(keccak256(bytes (a1)) == keccak256(bytes (analysis_no))) { if(keccak256(bytes (a2)) == keccak256(bytes (preAnalysisToken))) return (true, ""); else return (false, "分析函数前后不一"); } } return (false, "没有找到对应的 analysis_no"); }
function isAnalysisLegal(string memory id, string memory analysis_no, string memory preAnalysisToken) public view returns(bool, string memory) { require(keccak256(bytes (id)) != keccak256(""), "分析者 id 不能为空"); require(keccak256(bytes (analysis_no)) != keccak256(""), "分析序号 不能为空"); Record[] memory rList = recordData[id]; if(rList.length == 0) return (false, " 未曾有过数据噢 "); for(uint i = 0; i<rList.length; i++) { string memory a1 = rList[i].anaNo; string memory a2 = rList[i].token; if(keccak256(bytes (a1)) == keccak256(bytes (analysis_no))) { if(keccak256(bytes (a2)) == keccak256(bytes (preAnalysisToken))) return (true, ""); else return (false, "分析函数前后不一"); } } return (false, "没有找到对应的 analysis_no"); }
48,356
685
// Update our cumulative ledger. This is also a high precision integer.
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta));
3,844
2
// default function to accept tokens and ETH /
function() external payable {} /** verify if the given trade is authorised by account owner */ function isTradeAuthorised(string memory trade, bytes memory signature) public view returns (bool){ return address(owner) == address(getSigningAccount(trade, signature)); }
function() external payable {} /** verify if the given trade is authorised by account owner */ function isTradeAuthorised(string memory trade, bytes memory signature) public view returns (bool){ return address(owner) == address(getSigningAccount(trade, signature)); }
24,709
2
// Emitted when a slasher is added/_slasher Address of the added slasher
event SlasherAdded(address _slasher);
event SlasherAdded(address _slasher);
50,838
179
// Just transfer the tokens if they're the same.
LibERC20Token.transfer(state.fromTokenAddress, to, state.fromTokenBalance); return BRIDGE_SUCCESS;
LibERC20Token.transfer(state.fromTokenAddress, to, state.fromTokenBalance); return BRIDGE_SUCCESS;
33,114
47
// Change the upgrade master. This allows us to set a new owner for the upgrade mechanism. /
function setUpgradeMaster(address master) public { if (master == 0x0) throw; if (msg.sender != upgradeMaster) throw; upgradeMaster = master; }
function setUpgradeMaster(address master) public { if (master == 0x0) throw; if (msg.sender != upgradeMaster) throw; upgradeMaster = master; }
6,497
81
// InitializableHelper contract to support initializer functions. To use it, replacethe constructor with a function that has the `initializer` modifier.WARNING: Unlike constructors, initializer functions must be manuallyinvoked. This applies both to deploying an Initializable contract, as wellas extending an Initializable contract via inheritance.WARNING: When used with inheritance, manual care must be taken to not invokea parent initializer twice, or ensure that all initializers are idempotent,because this is not dealt with automatically as with constructors. /
contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
825
37
// buy
require(amount <= _maxTxAmount); require(tradingOpen);
require(amount <= _maxTxAmount); require(tradingOpen);
13,716
7
// Keep track of bowl minted per wallet/
mapping(address => uint256) public bowlsMintedPerWallet;
mapping(address => uint256) public bowlsMintedPerWallet;
39,889
211
// This event emits when an artwork has been burned./artworkId uint256 the id of the burned artwork.
event ArtworkBurned(uint256 indexed artworkId);
event ArtworkBurned(uint256 indexed artworkId);
70,014
6,296
// 3150
entry "open-handedly" : ENG_ADVERB
entry "open-handedly" : ENG_ADVERB
23,986
16
// ------------------------------------------------------------------------ Content moderatable contract definition This is to allow for moderator specific functions ------------------------------------------------------------------------
contract Moderatable is Ownable{ mapping(address => bool) public moderators; event ModeratorAdded(address indexed _moderator); event ModeratorRemoved(address indexed _moderator); // ------------------------------------------------------------------------ // Upon creation we set the first moderator as the owner // ------------------------------------------------------------------------ constructor() public { addModerator(owner); } // ------------------------------------------------------------------------ // Set up the modifier to only allow moderators to pass through the condition // ------------------------------------------------------------------------ modifier onlyModerators() { require(moderators[msg.sender] == true); _; } // ------------------------------------------------------------------------ // Add a moderator // ------------------------------------------------------------------------ function addModerator(address _newModerator) public onlyOwner { moderators[_newModerator] = true; emit ModeratorAdded(_newModerator); } // ------------------------------------------------------------------------ // Remove a moderator // ------------------------------------------------------------------------ function removeModerator(address _moderator) public onlyOwner { moderators[_moderator] = false; emit ModeratorRemoved(_moderator); } }
contract Moderatable is Ownable{ mapping(address => bool) public moderators; event ModeratorAdded(address indexed _moderator); event ModeratorRemoved(address indexed _moderator); // ------------------------------------------------------------------------ // Upon creation we set the first moderator as the owner // ------------------------------------------------------------------------ constructor() public { addModerator(owner); } // ------------------------------------------------------------------------ // Set up the modifier to only allow moderators to pass through the condition // ------------------------------------------------------------------------ modifier onlyModerators() { require(moderators[msg.sender] == true); _; } // ------------------------------------------------------------------------ // Add a moderator // ------------------------------------------------------------------------ function addModerator(address _newModerator) public onlyOwner { moderators[_newModerator] = true; emit ModeratorAdded(_newModerator); } // ------------------------------------------------------------------------ // Remove a moderator // ------------------------------------------------------------------------ function removeModerator(address _moderator) public onlyOwner { moderators[_moderator] = false; emit ModeratorRemoved(_moderator); } }
11,055
35
// Calculates how votes should be withdrawn from each active group. withdrawal The number of votes that need to be withdrawn.return The array of group addresses that should be withdrawn from.return The amount of votes to withdraw from the respective group in thearray of groups withdrawn from. /
function getActiveGroupWithdrawalDistribution(uint256 withdrawal) internal view returns (address[] memory, uint256[] memory)
function getActiveGroupWithdrawalDistribution(uint256 withdrawal) internal view returns (address[] memory, uint256[] memory)
23,715
21
// Set controller. Only callable by current controller _controller Controller contract address /
function setController(address _controller) external onlyController { controller = IController(_controller); emit SetController(_controller); }
function setController(address _controller) external onlyController { controller = IController(_controller); emit SetController(_controller); }
12,211
56
// Remove blocked balance
s_subscriptions[commitment.subscriptionId].blockedBalance -= commitment.estimatedCost;
s_subscriptions[commitment.subscriptionId].blockedBalance -= commitment.estimatedCost;
22,514
127
// Update reward variables of the given pool./pid The index of the pool. See `poolInfo`.
function updatePool(uint256 pid) public { PoolInfo memory pool = poolInfo[pid]; if (block.timestamp > pool.lastRewardTimestamp) { uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply > 0) { uint256 secondsElapsed = block.timestamp.sub(pool.lastRewardTimestamp); uint256 joeReward = secondsElapsed.mul(joePerSec()).mul(pool.allocPoint).div(totalAllocPoint); pool.accJoePerShare = pool.accJoePerShare.add((joeReward.mul(ACC_TOKEN_PRECISION).div(lpSupply))); } pool.lastRewardTimestamp = block.timestamp; poolInfo[pid] = pool; emit UpdatePool(pid, pool.lastRewardTimestamp, lpSupply, pool.accJoePerShare); } }
function updatePool(uint256 pid) public { PoolInfo memory pool = poolInfo[pid]; if (block.timestamp > pool.lastRewardTimestamp) { uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply > 0) { uint256 secondsElapsed = block.timestamp.sub(pool.lastRewardTimestamp); uint256 joeReward = secondsElapsed.mul(joePerSec()).mul(pool.allocPoint).div(totalAllocPoint); pool.accJoePerShare = pool.accJoePerShare.add((joeReward.mul(ACC_TOKEN_PRECISION).div(lpSupply))); } pool.lastRewardTimestamp = block.timestamp; poolInfo[pid] = pool; emit UpdatePool(pid, pool.lastRewardTimestamp, lpSupply, pool.accJoePerShare); } }
2,521
159
// Migrate lp token to another lp contract. Can be called only by owner. We trust that migrator contract is good.
function migrate(uint256 _pid) public onlyOwner { 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; }
function migrate(uint256 _pid) public onlyOwner { 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; }
14,028
36
// Figure out total token amount
uint256 tokenAmount = getFMANFromUSD(season.mysteryPack1Price); if (_quantity == 5) { tokenAmount = getFMANFromUSD(season.mysteryPack5Price); } else if (_quantity == 10) {
uint256 tokenAmount = getFMANFromUSD(season.mysteryPack1Price); if (_quantity == 5) { tokenAmount = getFMANFromUSD(season.mysteryPack5Price); } else if (_quantity == 10) {
5,888
280
// ERC721 interface compatible function for position token symbol retrieving/ return Returns symbol of token
function symbol() external view returns (string memory) { return "ONP"; }
function symbol() external view returns (string memory) { return "ONP"; }
59,278
191
// A count of how many new key purchases there have been
uint internal _totalSupply;
uint internal _totalSupply;
41,572
19
// GamePot/Neil Dwyer (neil@chefstudios.com)/A simple contract that represents a game's state machine / where users buy-in to a reward pool and a percentage gets/ paid out to the top users with some percentage going to/ the contract's owner
contract GamePot is AccessControl { enum GameState { PREGAME, PLAYING, COMPLETE } bytes32 public constant OWNER_ROLE = keccak256("OWNER"); bytes32 public constant GAME_CONTROLLER_ROLE = keccak256("GAME_CONTROLLER"); // settings uint public constant firstPlaceAwardMultiplier = 2; uint public constant percentageOfPlayersAwarded = 40; uint public constant hostingFeePercentage = 10; uint public price; // state GameState public gameState = GameState.PREGAME; address[] public playersInGame; uint public playersInGameCount; mapping (address => bool) public playersInGameLookup; mapping (address => uint) public playerBalances; uint public playerBalanceTotal; constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OWNER_ROLE, msg.sender); _setRoleAdmin(OWNER_ROLE, DEFAULT_ADMIN_ROLE); } /// @notice sets the buy-in price /// @param newPrice the new buy-in price in wei /// @dev requires OWNER role function setPrice(uint newPrice) public { require(hasRole(OWNER_ROLE, msg.sender), "Only an address with the OWNER role can do this"); require(gameState == GameState.PREGAME, "Can only change the price from the PREGAME state"); require(price != newPrice, "You are trying to set the same price"); price = newPrice; } /// @notice adds an address that has permission to control the game /// @param addr - the game controller wallet address /// @dev requires OWNER role function addGameController(address addr) public { require(hasRole(OWNER_ROLE, msg.sender), "Only an address with the OWNER role can do this"); grantRole(GAME_CONTROLLER_ROLE, addr); } /// @notice called by a game controller to start a game /// @param players - a list of wallets that are playing in this game /// @return - a tuple(bytes32[] wallets in game, bytes32[] wallets that didn't make it into game) /// @dev requires GAME_CONTROLLER role function startGame(address[] calldata players) public returns(address[] memory, address[] memory) { require(hasRole(GAME_CONTROLLER_ROLE, msg.sender), "Only an address with the GAME_CONTROLLER role can do this"); require(gameState == GameState.PREGAME, "Can only start a game from the PREGAME state"); uint inGameCount = 0; uint notEnoughBalanceCount = 0; for(uint i = 0; i < players.length; i++) { if(playerBalances[players[i]] < price) { notEnoughBalanceCount++; continue; } inGameCount++; } address[] memory inGame = new address[](inGameCount); address[] memory notEnoughBalance = new address[](notEnoughBalanceCount); uint inGameIdx = 0; uint notEnoughBalanceIdx = 0; for(uint i = 0; i < players.length; i++) { if(playerBalances[players[i]] < price) { notEnoughBalance[notEnoughBalanceIdx] = players[i]; notEnoughBalanceIdx++; continue; } inGame[inGameIdx] = players[i]; inGameIdx++; playerBalances[players[i]] -= price; playerBalanceTotal -= price; playersInGameLookup[players[i]] = true; } gameState = GameState.PLAYING; playersInGame = inGame; playersInGameCount = inGameCount; return (inGame, notEnoughBalance); } /// @notice called by a game controller to end a game /// @param leaderboard - a list of wallets in order of descending score /// @dev requires GAME_CONTROLLER role function endGame(address[] calldata leaderboard) public { require(hasRole(GAME_CONTROLLER_ROLE, msg.sender), "Only an address with the GAME_CONTROLLER role can do this"); require(gameState == GameState.PLAYING, "Can only start a game from the PLAYING state"); require(leaderboard.length > 0, "Must have some players in the leaderboard"); uint prizePool = 0; // Figure out the prize pool for(uint i = 0; i < playersInGame.length; i++) { prizePool += price; } uint paidOut = 0; for(uint i = 0; i < leaderboard.length; i++) { if(!playersInGameLookup[leaderboard[i]]) { continue; } uint award = calculateAward(leaderboard.length, i, prizePool, paidOut); if(award > 0) { paidOut += award; playerBalances[leaderboard[i]] += award; playerBalanceTotal += award; } } clearPlayingPlayers(); gameState = GameState.COMPLETE; return; } function cancelGame() public { require(hasRole(GAME_CONTROLLER_ROLE, msg.sender), "Only an address with the GAME_CONTROLLER role can do this"); // refund user for(uint i = 0; i < playersInGame.length; i++) { playerBalances[playersInGame[i]] += price; playerBalanceTotal += price; } clearPlayingPlayers(); gameState = GameState.PREGAME; return; } function resetGame() public { require(hasRole(GAME_CONTROLLER_ROLE, msg.sender), "Only an address with the GAME_CONTROLLER role can do this"); require(gameState == GameState.PLAYING, "Can only start a game from the PLAYING state"); gameState = GameState.PREGAME; } function getBalance() public view returns(uint) { return playerBalances[msg.sender]; } /// @notice called by users to buy in to games function buyIn() public payable { require(msg.value > 0, "Can't buy in with nothing"); playerBalances[msg.sender] += msg.value; playerBalanceTotal += msg.value; } function cashOut() public { uint balance = playerBalances[msg.sender]; require(balance > 0, "Your balance is empty"); playerBalances[msg.sender] = 0; playerBalanceTotal -= balance; if(!payable(msg.sender).send(balance)) { playerBalances[msg.sender] = balance; playerBalanceTotal += balance; } } function takeProfits() public { require(hasRole(OWNER_ROLE, msg.sender), "Only an address with the OWNER role can do this"); uint profits = address(this).balance - playerBalanceTotal; payable(msg.sender).transfer(profits); } function clearPlayingPlayers() private { for(uint i = 0; i < playersInGame.length; i++) { playersInGameLookup[playersInGame[i]] = false; } delete playersInGame; playersInGameCount = 0; } /// @notice Equations /// ---------------------------------------- /// Goal: Create a function f(x) = y where x is leaderboardIndex and y is price multiplier for award /// lastAwardedIndex = leaderboardLength * percentageOfPlayersAwarded / 100; /// f(x) = firstPlaceAwardMultiplier - b (x) /// f(lastAwardedIndex) = 0 = firstPlaceAwardMultipler - b (lastAwardedIndex) /// b = firstPlaceAwardMultipler / lastAwardedIndex /// therefore f(x) = firstPlaceAwardMultipler - (firstPlaceAwardMultiplier / lastAwardedIndex) * x /// @dev this function must be called in order from first place to last place function calculateAward(uint leaderboardLength, uint leaderboardIndex, uint prizePool, uint currentPaidOut) private view returns(uint) { uint lastAwardedIndexTimes100 = leaderboardLength * percentageOfPlayersAwarded; uint maxPayout = prizePool * (100 - hostingFeePercentage) / 100; uint multiplerReductionTimesPriceDividedBy100 = firstPlaceAwardMultiplier * leaderboardIndex * price / lastAwardedIndexTimes100; uint award; if(firstPlaceAwardMultiplier * price > multiplerReductionTimesPriceDividedBy100 * 100) { award = (firstPlaceAwardMultiplier * price - multiplerReductionTimesPriceDividedBy100 * 100); // make sure the contract is profitable if(award + currentPaidOut > maxPayout) { award = maxPayout - currentPaidOut; } } else { // make sure the contract is profitable, award the scraps if possible if(currentPaidOut + firstPlaceAwardMultiplier * price > maxPayout + multiplerReductionTimesPriceDividedBy100 * 100) { award = maxPayout - currentPaidOut; } } return award; } }
contract GamePot is AccessControl { enum GameState { PREGAME, PLAYING, COMPLETE } bytes32 public constant OWNER_ROLE = keccak256("OWNER"); bytes32 public constant GAME_CONTROLLER_ROLE = keccak256("GAME_CONTROLLER"); // settings uint public constant firstPlaceAwardMultiplier = 2; uint public constant percentageOfPlayersAwarded = 40; uint public constant hostingFeePercentage = 10; uint public price; // state GameState public gameState = GameState.PREGAME; address[] public playersInGame; uint public playersInGameCount; mapping (address => bool) public playersInGameLookup; mapping (address => uint) public playerBalances; uint public playerBalanceTotal; constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OWNER_ROLE, msg.sender); _setRoleAdmin(OWNER_ROLE, DEFAULT_ADMIN_ROLE); } /// @notice sets the buy-in price /// @param newPrice the new buy-in price in wei /// @dev requires OWNER role function setPrice(uint newPrice) public { require(hasRole(OWNER_ROLE, msg.sender), "Only an address with the OWNER role can do this"); require(gameState == GameState.PREGAME, "Can only change the price from the PREGAME state"); require(price != newPrice, "You are trying to set the same price"); price = newPrice; } /// @notice adds an address that has permission to control the game /// @param addr - the game controller wallet address /// @dev requires OWNER role function addGameController(address addr) public { require(hasRole(OWNER_ROLE, msg.sender), "Only an address with the OWNER role can do this"); grantRole(GAME_CONTROLLER_ROLE, addr); } /// @notice called by a game controller to start a game /// @param players - a list of wallets that are playing in this game /// @return - a tuple(bytes32[] wallets in game, bytes32[] wallets that didn't make it into game) /// @dev requires GAME_CONTROLLER role function startGame(address[] calldata players) public returns(address[] memory, address[] memory) { require(hasRole(GAME_CONTROLLER_ROLE, msg.sender), "Only an address with the GAME_CONTROLLER role can do this"); require(gameState == GameState.PREGAME, "Can only start a game from the PREGAME state"); uint inGameCount = 0; uint notEnoughBalanceCount = 0; for(uint i = 0; i < players.length; i++) { if(playerBalances[players[i]] < price) { notEnoughBalanceCount++; continue; } inGameCount++; } address[] memory inGame = new address[](inGameCount); address[] memory notEnoughBalance = new address[](notEnoughBalanceCount); uint inGameIdx = 0; uint notEnoughBalanceIdx = 0; for(uint i = 0; i < players.length; i++) { if(playerBalances[players[i]] < price) { notEnoughBalance[notEnoughBalanceIdx] = players[i]; notEnoughBalanceIdx++; continue; } inGame[inGameIdx] = players[i]; inGameIdx++; playerBalances[players[i]] -= price; playerBalanceTotal -= price; playersInGameLookup[players[i]] = true; } gameState = GameState.PLAYING; playersInGame = inGame; playersInGameCount = inGameCount; return (inGame, notEnoughBalance); } /// @notice called by a game controller to end a game /// @param leaderboard - a list of wallets in order of descending score /// @dev requires GAME_CONTROLLER role function endGame(address[] calldata leaderboard) public { require(hasRole(GAME_CONTROLLER_ROLE, msg.sender), "Only an address with the GAME_CONTROLLER role can do this"); require(gameState == GameState.PLAYING, "Can only start a game from the PLAYING state"); require(leaderboard.length > 0, "Must have some players in the leaderboard"); uint prizePool = 0; // Figure out the prize pool for(uint i = 0; i < playersInGame.length; i++) { prizePool += price; } uint paidOut = 0; for(uint i = 0; i < leaderboard.length; i++) { if(!playersInGameLookup[leaderboard[i]]) { continue; } uint award = calculateAward(leaderboard.length, i, prizePool, paidOut); if(award > 0) { paidOut += award; playerBalances[leaderboard[i]] += award; playerBalanceTotal += award; } } clearPlayingPlayers(); gameState = GameState.COMPLETE; return; } function cancelGame() public { require(hasRole(GAME_CONTROLLER_ROLE, msg.sender), "Only an address with the GAME_CONTROLLER role can do this"); // refund user for(uint i = 0; i < playersInGame.length; i++) { playerBalances[playersInGame[i]] += price; playerBalanceTotal += price; } clearPlayingPlayers(); gameState = GameState.PREGAME; return; } function resetGame() public { require(hasRole(GAME_CONTROLLER_ROLE, msg.sender), "Only an address with the GAME_CONTROLLER role can do this"); require(gameState == GameState.PLAYING, "Can only start a game from the PLAYING state"); gameState = GameState.PREGAME; } function getBalance() public view returns(uint) { return playerBalances[msg.sender]; } /// @notice called by users to buy in to games function buyIn() public payable { require(msg.value > 0, "Can't buy in with nothing"); playerBalances[msg.sender] += msg.value; playerBalanceTotal += msg.value; } function cashOut() public { uint balance = playerBalances[msg.sender]; require(balance > 0, "Your balance is empty"); playerBalances[msg.sender] = 0; playerBalanceTotal -= balance; if(!payable(msg.sender).send(balance)) { playerBalances[msg.sender] = balance; playerBalanceTotal += balance; } } function takeProfits() public { require(hasRole(OWNER_ROLE, msg.sender), "Only an address with the OWNER role can do this"); uint profits = address(this).balance - playerBalanceTotal; payable(msg.sender).transfer(profits); } function clearPlayingPlayers() private { for(uint i = 0; i < playersInGame.length; i++) { playersInGameLookup[playersInGame[i]] = false; } delete playersInGame; playersInGameCount = 0; } /// @notice Equations /// ---------------------------------------- /// Goal: Create a function f(x) = y where x is leaderboardIndex and y is price multiplier for award /// lastAwardedIndex = leaderboardLength * percentageOfPlayersAwarded / 100; /// f(x) = firstPlaceAwardMultiplier - b (x) /// f(lastAwardedIndex) = 0 = firstPlaceAwardMultipler - b (lastAwardedIndex) /// b = firstPlaceAwardMultipler / lastAwardedIndex /// therefore f(x) = firstPlaceAwardMultipler - (firstPlaceAwardMultiplier / lastAwardedIndex) * x /// @dev this function must be called in order from first place to last place function calculateAward(uint leaderboardLength, uint leaderboardIndex, uint prizePool, uint currentPaidOut) private view returns(uint) { uint lastAwardedIndexTimes100 = leaderboardLength * percentageOfPlayersAwarded; uint maxPayout = prizePool * (100 - hostingFeePercentage) / 100; uint multiplerReductionTimesPriceDividedBy100 = firstPlaceAwardMultiplier * leaderboardIndex * price / lastAwardedIndexTimes100; uint award; if(firstPlaceAwardMultiplier * price > multiplerReductionTimesPriceDividedBy100 * 100) { award = (firstPlaceAwardMultiplier * price - multiplerReductionTimesPriceDividedBy100 * 100); // make sure the contract is profitable if(award + currentPaidOut > maxPayout) { award = maxPayout - currentPaidOut; } } else { // make sure the contract is profitable, award the scraps if possible if(currentPaidOut + firstPlaceAwardMultiplier * price > maxPayout + multiplerReductionTimesPriceDividedBy100 * 100) { award = maxPayout - currentPaidOut; } } return award; } }
4,887
6
// https:github.com/makerdao/dss/blob/master/src/vat.sol
contract VatAbstract { function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; }
contract VatAbstract { function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; }
36,033
49
// approve the marketplace to sell NFTs on your behalf
approve(address(this), tokenId); payTo(owner, listingFee); payTo(seller, msg.value);
approve(address(this), tokenId); payTo(owner, listingFee); payTo(seller, msg.value);
13,404
95
// Helper function to facilitate xSNXAdmin.rebalanceTowardsHedge() Denominated in USD terms /
function calculateHedgeAssetsValueInUsd() internal view returns (uint256 hedgeAssetsValueInUsd)
function calculateHedgeAssetsValueInUsd() internal view returns (uint256 hedgeAssetsValueInUsd)
952
46
// getTotalRunesreturns the runesObtained and getPendingRunes for the inhabitant passed /
function getTotalRunes(address inhabitant) external view returns(uint256) { return runesObtained[inhabitant] + getPendingRunes(inhabitant); }
function getTotalRunes(address inhabitant) external view returns(uint256) { return runesObtained[inhabitant] + getPendingRunes(inhabitant); }
27,074
49
// Seller sign
function signSeller(uint _dealNumber) public { uint deal = dealNumbers[_dealNumber]; //If sign of seller is empty and sender it is seller for this deal require(deals[deal].signSeller == 0x0 && msg.sender == deals[deal].seller); deals[deal].signSeller = msg.sender; }
function signSeller(uint _dealNumber) public { uint deal = dealNumbers[_dealNumber]; //If sign of seller is empty and sender it is seller for this deal require(deals[deal].signSeller == 0x0 && msg.sender == deals[deal].seller); deals[deal].signSeller = msg.sender; }
51,211
300
// Get the quantity of SNX associated with a given schedule entry. /
function getVestingQuantity(address account, uint index) public view returns (uint)
function getVestingQuantity(address account, uint index) public view returns (uint)
6,055
17
// take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); }
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); }
13,150
11
// Set Methods //_key The key for the record
function setAddress(bytes32 _key, address _value) onlyLatestContract external { addressStorage[_key] = _value; }
function setAddress(bytes32 _key, address _value) onlyLatestContract external { addressStorage[_key] = _value; }
12,815
2
// Supported pools.
ICurveFi renbtcPool = ICurveFi(0x93054188d876f558f4a66B2EF1d97d16eDf0895B); ICurveFi sbtcPool = ICurveFi(0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714); ICurveFi tbtcPool = ICurveFi(0xC25099792E9349C7DD09759744ea681C7de2cb66);
ICurveFi renbtcPool = ICurveFi(0x93054188d876f558f4a66B2EF1d97d16eDf0895B); ICurveFi sbtcPool = ICurveFi(0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714); ICurveFi tbtcPool = ICurveFi(0xC25099792E9349C7DD09759744ea681C7de2cb66);
5,740
175
// register lockup in TimeLockedToken this will transfer funds from this contract and lock them for sender
token.registerLockup( _receiver, amount, claimTokenVested.team, claimTokenVested.vestingBegin, claimTokenVested.vestingEnd, claimTokenVested.lastClaim );
token.registerLockup( _receiver, amount, claimTokenVested.team, claimTokenVested.vestingBegin, claimTokenVested.vestingEnd, claimTokenVested.lastClaim );
20,146
61
// deposit tokens into the PCV allocation
function deposit() external payable override whenNotPaused { uint256 erc20AmountBalance = IERC20(token()).balanceOf(address(this)); // include any ERC20 dust from prior LP uint256 rusdAmount = _getAmountRusdToDeposit(erc20AmountBalance); _addLiquidity(erc20AmountBalance, rusdAmount); _burnRusdHeld(); // burn any RUSD dust from LP emit Deposit(msg.sender, erc20AmountBalance); }
function deposit() external payable override whenNotPaused { uint256 erc20AmountBalance = IERC20(token()).balanceOf(address(this)); // include any ERC20 dust from prior LP uint256 rusdAmount = _getAmountRusdToDeposit(erc20AmountBalance); _addLiquidity(erc20AmountBalance, rusdAmount); _burnRusdHeld(); // burn any RUSD dust from LP emit Deposit(msg.sender, erc20AmountBalance); }
39,073
121
// See {IERC2612Permit-nonces}. /
function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); }
function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); }
41,406
41
// Unblock previously blocked tokens from one address and transfer them to another from Source address to Destination address value Amount of tokens to unblock unblockTokens function can be called only by Pandora contract /
function unblockTokens( address from, address to, uint256 value
function unblockTokens( address from, address to, uint256 value
28,504
24
// A Whitelist contract that can be locked and unlocked. Provides a modifierto check for locked state plus functions and events. The contract is never locked forwhitelisted addresses. The contracts starts off unlocked and can be locked andthen unlocked a single time. Once unlocked, the contract can never be locked back. Base contract which allows children to implement an emergency stop mechanism. /
contract LockableWhitelisted is Whitelist { event Locked(); event Unlocked(); bool public locked = false; bool private unlockedOnce = false; /** * @dev Modifier to make a function callable only when the contract is not locked * or the caller is whitelisted. */ modifier whenNotLocked(address _address) { require(!locked || whitelist[_address], 'not unlocked or whitelisted'); _; } /** * @dev Returns true if the specified address is whitelisted. * @param _address The address to check for whitelisting status. */ function isWhitelisted(address _address) public view returns (bool) { return whitelist[_address]; } /** * @dev Called by the owner to lock. */ function lock() onlyOwner public { require(!unlockedOnce); if (!locked) { locked = true; emit Locked(); } } /** * @dev Called by the owner to unlock. */ function unlock() onlyOwner public { if (locked) { locked = false; unlockedOnce = true; emit Unlocked(); } } }
contract LockableWhitelisted is Whitelist { event Locked(); event Unlocked(); bool public locked = false; bool private unlockedOnce = false; /** * @dev Modifier to make a function callable only when the contract is not locked * or the caller is whitelisted. */ modifier whenNotLocked(address _address) { require(!locked || whitelist[_address], 'not unlocked or whitelisted'); _; } /** * @dev Returns true if the specified address is whitelisted. * @param _address The address to check for whitelisting status. */ function isWhitelisted(address _address) public view returns (bool) { return whitelist[_address]; } /** * @dev Called by the owner to lock. */ function lock() onlyOwner public { require(!unlockedOnce); if (!locked) { locked = true; emit Locked(); } } /** * @dev Called by the owner to unlock. */ function unlock() onlyOwner public { if (locked) { locked = false; unlockedOnce = true; emit Unlocked(); } } }
11,329
18
// ========== VIEWS ========== //Show allocations of FraxLendAMO in Frax/ return allocations : / allocations[0] = Unallocated FRAX/ allocations[1] = Allocated FRAX/ allocations[2] = Total FRAX
function showAllocations() public view returns (uint256[3] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Allocated FRAX // Frax in Frax Lend Pairs for (uint i=0; i < fraxlendpairs_array.length; i++) { IFraxLendPair_Partial newFraxLendPair = IFraxLendPair_Partial(fraxlendpairs_array[i]); uint256 share = newFraxLendPair.balanceOf(address(this)); allocations[1] = allocations[1] + (fraxlendpairShareToFrax(fraxlendpairs_array[i], share)); } // Total FRAX possessed in various forms uint256 sum_frax = allocations[0] + allocations[1]; allocations[2] = sum_frax; }
function showAllocations() public view returns (uint256[3] memory allocations) { // All numbers given are in FRAX unless otherwise stated // Unallocated FRAX allocations[0] = FRAX.balanceOf(address(this)); // Allocated FRAX // Frax in Frax Lend Pairs for (uint i=0; i < fraxlendpairs_array.length; i++) { IFraxLendPair_Partial newFraxLendPair = IFraxLendPair_Partial(fraxlendpairs_array[i]); uint256 share = newFraxLendPair.balanceOf(address(this)); allocations[1] = allocations[1] + (fraxlendpairShareToFrax(fraxlendpairs_array[i], share)); } // Total FRAX possessed in various forms uint256 sum_frax = allocations[0] + allocations[1]; allocations[2] = sum_frax; }
3,024
2
// constructor of this contractowner Owner of this contract/
constructor( address owner ) public { super.transferOwnership(owner); }
constructor( address owner ) public { super.transferOwnership(owner); }
39,229
20
// get the index price of the powerPerp, scaled down the index price is scaled down by INDEX_SCALE in the associated PowerXBase library this is the index price used when calculating funding and for collateralization _period period which you want to calculate twap withreturn index price denominated in $USD, scaled by 1e18 /
function getIndex(uint32 _period) external view returns (uint256) { return Power2Base._getIndex(_period, oracle, ethQuoteCurrencyPool, weth, quoteCurrency); }
function getIndex(uint32 _period) external view returns (uint256) { return Power2Base._getIndex(_period, oracle, ethQuoteCurrencyPool, weth, quoteCurrency); }
42,282
411
// ERC-3156 Flash loan callback
function onFlashLoan(address sender, address token, uint256 amount, uint256 fee, bytes calldata data) external override { require(sender == address(this), "FlashBorrower: External loan initiator"); (Action action) = abi.decode(data, (Action)); // Use this to unpack arbitrary data flashSender = sender; flashToken = token; flashAmount = amount; flashFee = fee; if (action == Action.NORMAL) { flashBalance = IERC20(token).balanceOf(address(this)); } else if (action == Action.STEAL) {
function onFlashLoan(address sender, address token, uint256 amount, uint256 fee, bytes calldata data) external override { require(sender == address(this), "FlashBorrower: External loan initiator"); (Action action) = abi.decode(data, (Action)); // Use this to unpack arbitrary data flashSender = sender; flashToken = token; flashAmount = amount; flashFee = fee; if (action == Action.NORMAL) { flashBalance = IERC20(token).balanceOf(address(this)); } else if (action == Action.STEAL) {
30,084
213
// Transfer the tokens to the DAO
_token.safeTransferFrom(msg.sender, _dao, _mintPrice * availableQuantity);
_token.safeTransferFrom(msg.sender, _dao, _mintPrice * availableQuantity);
43,863
86
// On swap
if ((automatedMarketMakerPairs[to] || automatedMarketMakerPairs[from]) && totalFees > 0) { fees = amount.mul(totalFees).div(100); _tokensForTeam += fees * _teamFee / totalFees; _tokensForLiquidity += fees * _liquidityFee / totalFees; }
if ((automatedMarketMakerPairs[to] || automatedMarketMakerPairs[from]) && totalFees > 0) { fees = amount.mul(totalFees).div(100); _tokensForTeam += fees * _teamFee / totalFees; _tokensForLiquidity += fees * _liquidityFee / totalFees; }
59,996
147
// Claims the oTokens belonging to the vault auctionSellOrder is the sell order of the bid gnosisEasyAuction is the address of the gnosis auction contract counterpartyThetaVault is the address of the counterparty theta /
function claimAuctionOtokens( Vault.AuctionSellOrder calldata auctionSellOrder, address gnosisEasyAuction, address counterpartyThetaVault
function claimAuctionOtokens( Vault.AuctionSellOrder calldata auctionSellOrder, address gnosisEasyAuction, address counterpartyThetaVault
59,282
178
// oods_coefficients[103]/ mload(add(context, 0x7a00)), res += c_104(f_17(x) - f_17(g^455z)) / (x - g^455z).
res := add( res, mulmod(mulmod(/*(x - g^455 * z)^(-1)*/ mload(add(denominatorsPtr, 0x740)),
res := add( res, mulmod(mulmod(/*(x - g^455 * z)^(-1)*/ mload(add(denominatorsPtr, 0x740)),
5,638
64
// Destroys `amount` tokens from the caller.
* See {ERC20-_burn}. */ // 成都链安 // 代币销毁函数,合约所有者销毁自身一定数量的代币 function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); // 成都链安 // 调用内部函数_burn进行代币销毁 }
* See {ERC20-_burn}. */ // 成都链安 // 代币销毁函数,合约所有者销毁自身一定数量的代币 function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); // 成都链安 // 调用内部函数_burn进行代币销毁 }
1,613
11
// A mapping from validator's Ethereum address to registration data.
mapping(address => ValidatorData) internal validatorsData;
mapping(address => ValidatorData) internal validatorsData;
42,424
29
// calc actual deposit amount due to BOMB burn
uint tokensToBurn = findOnePercent(amount); uint actual = amount.sub(tokensToBurn); unallocatedRewards += actual;
uint tokensToBurn = findOnePercent(amount); uint actual = amount.sub(tokensToBurn); unallocatedRewards += actual;
22,142
94
// silence warning about unused variable without the addition of bytecode.
amount; return 0;
amount; return 0;
36,677
8
// The price feed contract to use for a particular asset. asset address of the asset /
function feed(address asset) internal pure virtual override returns (address)
function feed(address asset) internal pure virtual override returns (address)
10,928
19
// <------------------------------------- royalty stuff -------------------------------------> Remove this stuff if you don't want royalties (ex 0%)
uint256 public constant royaltyBps = 1000; // Set royalty percentage (e.g., 1000 = 10%) address payable public royaltyReceiver; // Address to receive the royalties function royaltyInfo(uint256 tokenId, uint256 salePrice) public view override returns (address, uint256) { uint256 royaltyAmount = (salePrice * royaltyBps) / 10000; return (royaltyReceiver, royaltyAmount); }
uint256 public constant royaltyBps = 1000; // Set royalty percentage (e.g., 1000 = 10%) address payable public royaltyReceiver; // Address to receive the royalties function royaltyInfo(uint256 tokenId, uint256 salePrice) public view override returns (address, uint256) { uint256 royaltyAmount = (salePrice * royaltyBps) / 10000; return (royaltyReceiver, royaltyAmount); }
19,244
35
// This function is used to unlist/delist a creator from the platform/
function delistCreator(address[] memory _creators) public onlyOwner { for(uint i = 0; i < _creators.length; i++){ if (creatorWhitelist[_creators[i]] == true){ creatorWhitelist[_creators[i]] = false; emit DelistCreator(_creators[i]); } } }
function delistCreator(address[] memory _creators) public onlyOwner { for(uint i = 0; i < _creators.length; i++){ if (creatorWhitelist[_creators[i]] == true){ creatorWhitelist[_creators[i]] = false; emit DelistCreator(_creators[i]); } } }
40,491
553
// give reward for incentive
safeSend(msg.sender, incentiveReward);
safeSend(msg.sender, incentiveReward);
66,469
10
// saving feeBps in memory to minimize sloads
uint256 _feeBps = feeBps; for (uint256 i = 0; i < trancheValues.length; i++) { uint256 trancheValue = trancheValues[i];
uint256 _feeBps = feeBps; for (uint256 i = 0; i < trancheValues.length; i++) { uint256 trancheValue = trancheValues[i];
58,650
26
// If the component is equal to the output token we don't have to trade
if(components[i] == address(_outputToken)) { totalOutputTokenBought = totalOutputTokenBought.add(maxAmountSell); componentAmountSold = maxAmountSell; }
if(components[i] == address(_outputToken)) { totalOutputTokenBought = totalOutputTokenBought.add(maxAmountSell); componentAmountSold = maxAmountSell; }
38,148
99
// do the transfers
for (uint j; j < _addresses.length; j++) { transfer(_addresses[j], _amounts[j]); }
for (uint j; j < _addresses.length; j++) { transfer(_addresses[j], _amounts[j]); }
38,937
8
// Control of the functions that are executable by the teacher
modifier OnlyTeacher(address _teacher) { // Requiers that the address entered by param be equal to the contract's owner require(teacher == _teacher, "Permission denied"); _; }
modifier OnlyTeacher(address _teacher) { // Requiers that the address entered by param be equal to the contract's owner require(teacher == _teacher, "Permission denied"); _; }
50,249
10
// Min contribution is 0.1 ether
uint256 public constant MINIMUM_CONTRIBUTION = 10**17;
uint256 public constant MINIMUM_CONTRIBUTION = 10**17;
41,619
13
// _admin address
function isAdmin(address _admin) public view returns (bool) { return _admins[_admin]; }
function isAdmin(address _admin) public view returns (bool) { return _admins[_admin]; }
60,088
129
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 );
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 );
508
3
// Prevents share cost from being too high or too low - potentially needs work
require(msg.value >= 10000 && _tokenAmount >= 10000 && msg.value <= 5*10**18); ethPool = msg.value; tokenPool = _tokenAmount; invariant = ethPool.mul(tokenPool); require(token.transferFrom(msg.sender, address(this), _tokenAmount));
require(msg.value >= 10000 && _tokenAmount >= 10000 && msg.value <= 5*10**18); ethPool = msg.value; tokenPool = _tokenAmount; invariant = ethPool.mul(tokenPool); require(token.transferFrom(msg.sender, address(this), _tokenAmount));
17,597
148
// By storing the original value once again, a refund is triggered (see https:eips.ethereum.org/EIPS/eip-2200).
_depositor = address(0); _status = _NOT_ENTERED;
_depositor = address(0); _status = _NOT_ENTERED;
79,176
13
// Sends amount `amount` of ETH in proxy to SplitMainpayable reduces gas cost; no vulnerability to accidentally lock ETH introduced since fn call is restricted to SplitMainamount Amount to send /
function sendETHToMain(uint256 amount) external payable onlySplitMain() { address(splitMain).safeTransferETH(amount); }
function sendETHToMain(uint256 amount) external payable onlySplitMain() { address(splitMain).safeTransferETH(amount); }
12,262