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
0
// This variable should never be directly accessed by users of the library: interactions must be restricted to the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add this feature: see https:github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
uint256 _value; // default: 0
1,720
159
// Minting fees correction set by the `FeeManager` contract: they are going to be multiplied to the value of the fees computed using the hedge curve Scaled by `BASE_PARAMS`
uint64 bonusMalusMint;
uint64 bonusMalusMint;
70,895
0
// stores to 0 slots
function std0() external pure { RevertHelper.revertBytes(abi.encodeWithSelector(STORES, uint(0))); }
function std0() external pure { RevertHelper.revertBytes(abi.encodeWithSelector(STORES, uint(0))); }
13,146
149
// Assignes a new NFT to an address. Use and override this function with caution. Wrong usage can have serious consequences. _to Address to wich we want to add the NFT. _tokenId Which NFT we want to add. /
function _addNFToken( address _to, uint256 _tokenId ) internal override virtual
function _addNFToken( address _to, uint256 _tokenId ) internal override virtual
44,083
23
// Update number of Lemon Tokens remaining for drop, just in case it is needed
function updateLemontokensRemainingToDrop() public { lemonsRemainingToDrop = lemonContract.balanceOf(this); }
function updateLemontokensRemainingToDrop() public { lemonsRemainingToDrop = lemonContract.balanceOf(this); }
70,692
17
// Emitted when a new reward borrow speed is calculated for a market
event RewardBorrowSpeedUpdated( uint8 rewardType, CToken indexed cToken, uint256 newSpeed ); event RewardAdded(uint8 rewardType, address newRewardAddress); event RewardAddressChanged( uint8 rewardType,
event RewardBorrowSpeedUpdated( uint8 rewardType, CToken indexed cToken, uint256 newSpeed ); event RewardAdded(uint8 rewardType, address newRewardAddress); event RewardAddressChanged( uint8 rewardType,
14,125
94
//
* @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-ERC20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 9. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 9; } /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {ERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {ERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {ERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {ERC20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {ERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance') ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'ERC20: decreased allowance below zero') ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'ERC20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), 'ERC20: mint to the zero address'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'ERC20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'ERC20: burn amount exceeds allowance') ); } }
* @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-ERC20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 9. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 9; } /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {ERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {ERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {ERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {ERC20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {ERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance') ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'ERC20: decreased allowance below zero') ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'ERC20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), 'ERC20: mint to the zero address'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'ERC20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'ERC20: burn amount exceeds allowance') ); } }
15,204
76
// Return the sell price of 1 individual token.
function sellPrice() public pure returns (uint256) { uint256 _eth = 1e18; uint256 _dividends = SafeMath.div(SafeMath.mul(_eth, exitFee_), 100); uint256 _taxedeth = SafeMath.sub(_eth, _dividends); return _taxedeth; }
function sellPrice() public pure returns (uint256) { uint256 _eth = 1e18; uint256 _dividends = SafeMath.div(SafeMath.mul(_eth, exitFee_), 100); uint256 _taxedeth = SafeMath.sub(_eth, _dividends); return _taxedeth; }
7,666
35
// Purchase function allows incoming payments when not paused - requires payment code
function purchase(bytes8 paymentCode) whenNotPaused public payable { // Verify they have sent ETH in require(msg.value != 0); // Verify the payment code was included require(paymentCode != 0); // If payment from addresses are being enforced, ensure the code matches the sender address if (enforceAddressMatch) { // Get the first 8 bytes of the hash of the address bytes8 calculatedPaymentCode = bytes8(keccak256(msg.sender)); // Fail if the sender code does not match require(calculatedPaymentCode == paymentCode); } // Save off the existing purchase amount for this user uint256 existingPurchaseAmount = purchases[msg.sender]; // If they have not purchased before (0 value), then save it off if (existingPurchaseAmount == 0) { purchaserAddresses.push(msg.sender); } // Add the new purchase value to the existing value already being tracked purchases[msg.sender] = existingPurchaseAmount.add(msg.value); // Transfer out to the owner wallet owner.transfer(msg.value); // Trigger the event for a new purchase PurchaseMade(msg.sender, paymentCode, msg.value); }
function purchase(bytes8 paymentCode) whenNotPaused public payable { // Verify they have sent ETH in require(msg.value != 0); // Verify the payment code was included require(paymentCode != 0); // If payment from addresses are being enforced, ensure the code matches the sender address if (enforceAddressMatch) { // Get the first 8 bytes of the hash of the address bytes8 calculatedPaymentCode = bytes8(keccak256(msg.sender)); // Fail if the sender code does not match require(calculatedPaymentCode == paymentCode); } // Save off the existing purchase amount for this user uint256 existingPurchaseAmount = purchases[msg.sender]; // If they have not purchased before (0 value), then save it off if (existingPurchaseAmount == 0) { purchaserAddresses.push(msg.sender); } // Add the new purchase value to the existing value already being tracked purchases[msg.sender] = existingPurchaseAmount.add(msg.value); // Transfer out to the owner wallet owner.transfer(msg.value); // Trigger the event for a new purchase PurchaseMade(msg.sender, paymentCode, msg.value); }
24,782
10
// 同态乘法(可能会溢出)
function HE_Mul(uint _c1, uint _c2) public view returns(uint){ return decrypto(LibSafeMathForUint256Utils.mul(_c1, _c2)); }
function HE_Mul(uint _c1, uint _c2) public view returns(uint){ return decrypto(LibSafeMathForUint256Utils.mul(_c1, _c2)); }
38,556
20
// Address of the NFT contract
address nftContract;
address nftContract;
30,927
36
// Total tokens should be more than user want's to buy
require(balances[owner]>safeMul(tokens, multiplier));
require(balances[owner]>safeMul(tokens, multiplier));
9,964
30
// 0x51: Insufficient consensus in tally precondition clause
InsufficientConsensus,
InsufficientConsensus,
82,225
82
// Let's a pply a fee to this tx
uint256 feeamount = _amount.mul(_fee).div(10000);
uint256 feeamount = _amount.mul(_fee).div(10000);
76,422
0
// Define 2 events, one for Adding, and other for Removing
event RetailerAdded(address indexed account); event RetailerRemoved(address indexed account);
event RetailerAdded(address indexed account); event RetailerRemoved(address indexed account);
2,759
59
// Transfer tokens from one address to another from address The address which you want to send tokens from to address The address which you want to transfer to value uint256 the amount of tokens to be transferred /
function transferFrom( address from, address to, uint256 value ) public returns (bool)
function transferFrom( address from, address to, uint256 value ) public returns (bool)
40,722
108
// Utility; removes a prefix from a path. _path Path to remove the prefix from.return _unprefixedKey Unprefixed key. /
function _removeHexPrefix( bytes memory _path ) private pure returns ( bytes memory _unprefixedKey )
function _removeHexPrefix( bytes memory _path ) private pure returns ( bytes memory _unprefixedKey )
26,495
8
// Minute
dt.minute = getMinute(timestamp);
dt.minute = getMinute(timestamp);
20,997
129
// The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
assembly { approvedAddressSlot := tokenApproval.slot approvedAddress := sload(approvedAddressSlot) }
assembly { approvedAddressSlot := tokenApproval.slot approvedAddress := sload(approvedAddressSlot) }
27,621
29
// emitted when protocol fees are withdrawn tokenFees array of TokenFee structs indicating address of fee token and amount /
event FeesWithdrawn(TokenFee[3] tokenFees);
event FeesWithdrawn(TokenFee[3] tokenFees);
37,282
201
// determine if the public droptime has passed. if the feature is disabled then assume the time has passed./
function publicDropTimePassed() public view returns(bool) { if(enforcePublicDropTime == false) { return true; } return block.timestamp >= publicDropTime; }
function publicDropTimePassed() public view returns(bool) { if(enforcePublicDropTime == false) { return true; } return block.timestamp >= publicDropTime; }
14,275
67
// users withdraw ether rather than have it directly sent to them _amount value of ether to withdraw /
function withdrawEther(uint256 _amount) external nonReentrant { require(_etherBalance[msg.sender] >= _amount, 'Bal < amount'); (bool success, ) = msg.sender.call.value(_amount)(""); require(success, "Transfer failed."); }
function withdrawEther(uint256 _amount) external nonReentrant { require(_etherBalance[msg.sender] >= _amount, 'Bal < amount'); (bool success, ) = msg.sender.call.value(_amount)(""); require(success, "Transfer failed."); }
36,790
2
// The eternal platform
IEternal public eternal;
IEternal public eternal;
16,181
1
// Event fired when new message is deployed // sets a new message /
function setMessage(string _newMessage) public { message = _newMessage; NewBud(_newMessage); }
function setMessage(string _newMessage) public { message = _newMessage; NewBud(_newMessage); }
27,707
37
// Hour
timestamp += HOUR_IN_SECONDS * (hour);
timestamp += HOUR_IN_SECONDS * (hour);
16,229
131
// Check what we received
address[] memory rewardTokens = supportedRewardTokens(); uint256[] memory rewardAmounts = new uint256[](rewardTokens.length); uint256 receivedRewardTokensCount; for(uint256 i = 0; i < rewardTokens.length; i++) { address rtkn = rewardTokens[i]; uint256 newBalance = IERC20(rtkn).balanceOf(address(this)); if(newBalance > rewardBalances[rtkn]) { receivedRewardTokensCount++; rewardAmounts[i] = newBalance.sub(rewardBalances[rtkn]); rewardBalances[rtkn] = newBalance;
address[] memory rewardTokens = supportedRewardTokens(); uint256[] memory rewardAmounts = new uint256[](rewardTokens.length); uint256 receivedRewardTokensCount; for(uint256 i = 0; i < rewardTokens.length; i++) { address rtkn = rewardTokens[i]; uint256 newBalance = IERC20(rtkn).balanceOf(address(this)); if(newBalance > rewardBalances[rtkn]) { receivedRewardTokensCount++; rewardAmounts[i] = newBalance.sub(rewardBalances[rtkn]); rewardBalances[rtkn] = newBalance;
86,073
1,003
// Get the settlement proposal challenge nonce of the given wallet and currency/wallet The address of the concerned wallet/currency The concerned currency/ return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256)
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency) public view returns (uint256)
22,163
165
// Claim API helpers /
function getClaimAmountForBlock() constant returns (uint) { return CallLib.getClaimAmountForBlock(block.number); }
function getClaimAmountForBlock() constant returns (uint) { return CallLib.getClaimAmountForBlock(block.number); }
17,615
33
// Thrown when Semaphore tree depth is not supported.//depth Passed tree depth.
error UnsupportedTreeDepth(uint8 depth);
error UnsupportedTreeDepth(uint8 depth);
31,098
10
// Throws if bounty status is not ongoing._bountyID The ID of the bounty./
modifier bountyStatusOngoing(uint256 _bountyID) { require(bountyList[_bountyID].status == BountyStatus.Ongoing); _; }
modifier bountyStatusOngoing(uint256 _bountyID) { require(bountyList[_bountyID].status == BountyStatus.Ongoing); _; }
17,991
405
// There are six possible outcomes from this search:/ 1. The currency id is in the list/- it must be set to active, do nothing/- it must be set to inactive, shift suffix and concatenate/ 2. The current id is greater than the one in the search:/- it must be set to active, append to prefix and then concatenate the suffix,/ensure that we do not lose the last 2 bytes if set./- it must be set to inactive, it is not in the list, do nothing/ 3. Reached the end of the list:/- it must be set to active, check that
while (suffix != 0x00) { uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS));
while (suffix != 0x00) { uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS));
35,521
34
// MasterChef is the master of OASIS. He can make OASIS and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once OASIS is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. For any questions contact @vinceheng on Telegram
contract MasterChef is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 lastOasisPerShare; // Oasis per share on last update uint256 unclaimed; // Unclaimed reward in Oasis. // pending reward = user.unclaimed + (user.amount * (pool.accOasisPerShare - user.lastOasisPerShare) // // Whenever a user deposits or withdraws Staking tokens to a pool. Here's what happens: // 1. The pool's `accOasisPerShare` (and `lastOasisBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `lastOasisPerShare` gets updated. // 4. User's `amount` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. OASIS to distribute per block. uint256 totalDeposited; // The total deposited by users uint256 lastRewardBlock; // Last block number that OASIS distribution occurs. uint256 accOasisPerShare; // Accumulated OASIS per share, times 1e18. See below. uint256 poolLimit; uint256 unlockDate; } // The OASIS TOKEN! IERC20 public immutable oasis; address public pendingOasisOwner; address public oasisTransferOwner; address public devAddress; // Contract for locking reward IRewardLocker public immutable rewardLocker; // OASIS tokens created per block. uint256 public oasisPerBlock = 8 ether; uint256 public constant MAX_EMISSION_RATE = 1000 ether; // Safety check // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; uint256 public constant MAX_ALLOC_POINT = 100000; // Safety check // The block number when OASIS mining starts. uint256 public immutable startBlock; event Add(address indexed user, uint256 allocPoint, IERC20 indexed token, bool massUpdatePools); event Set(address indexed user, uint256 pid, uint256 allocPoint); event Deposit(address indexed user, uint256 indexed pid, uint256 amount, bool harvest); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, bool harvest); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event HarvestMultiple(address indexed user, uint256[] _pids, uint256 amount); event HarvestAll(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SetDevAddress(address indexed user, address indexed newAddress); event UpdateEmissionRate(address indexed user, uint256 oasisPerBlock); event SetOasisTransferOwner(address indexed user, address indexed oasisTransferOwner); event AcceptOasisOwnership(address indexed user, address indexed newOwner); event NewPendingOasisOwner(address indexed user, address indexed newOwner); constructor( IERC20 _oasis, uint256 _startBlock, IRewardLocker _rewardLocker, address _devAddress, address _oasisTransferOwner ) public { require(_devAddress != address(0), "!nonzero"); oasis = _oasis; startBlock = _startBlock; rewardLocker = _rewardLocker; devAddress = _devAddress; oasisTransferOwner = _oasisTransferOwner; IERC20(_oasis).safeApprove(address(_rewardLocker), uint256(0)); IERC20(_oasis).safeIncreaseAllowance( address(_rewardLocker), uint256(-1) ); } function poolLength() external view returns (uint256) { return poolInfo.length; } mapping(IERC20 => bool) public poolExistence; modifier nonDuplicated(IERC20 _lpToken) { require(poolExistence[_lpToken] == false, "nonDuplicated: duplicated"); _; } // Add a new lp to the pool. Can only be called by the owner. function add(uint256 _allocPoint, IERC20 _lpToken, bool _massUpdatePools, uint256 _poolLimit, uint256 _unlockDate) external onlyOwner nonDuplicated(_lpToken) { require(_allocPoint <= MAX_ALLOC_POINT, "!overmax"); if (_massUpdatePools) { massUpdatePools(); // This ensures that massUpdatePools will not exceed gas limit } _lpToken.balanceOf(address(this)); // Check to make sure it's a token uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolExistence[_lpToken] = true; poolInfo.push(PoolInfo({ lpToken: _lpToken, totalDeposited: 0, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accOasisPerShare: 0, poolLimit: _poolLimit, unlockDate: _unlockDate })); emit Add(msg.sender, _allocPoint, _lpToken, _massUpdatePools); } // Update the given pool's OASIS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) external onlyOwner { require(_allocPoint <= MAX_ALLOC_POINT, "!overmax"); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; emit Set(msg.sender, _pid, _allocPoint); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from); } // View function to see pending OASIS on frontend. function pendingOasis(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOasisPerShare = pool.accOasisPerShare; if (block.number > pool.lastRewardBlock && pool.totalDeposited != 0 && totalAllocPoint != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 oasisReward = multiplier.mul(oasisPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accOasisPerShare = accOasisPerShare.add(oasisReward.mul(1e18).div(pool.totalDeposited)); } return user.amount.mul(accOasisPerShare.sub(user.lastOasisPerShare)).div(1e18).add(user.unclaimed); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } if (pool.totalDeposited == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 oasisReward = multiplier.mul(oasisPerBlock).mul(pool.allocPoint).div(totalAllocPoint); // oasis.mint(devAddress, oasisReward.div(50)); // 2% // oasis.mint(address(this), oasisReward); pool.accOasisPerShare = pool.accOasisPerShare.add(oasisReward.mul(1e18).div(pool.totalDeposited)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for OASIS allocation. function deposit(uint256 _pid, uint256 _amount, bool _shouldHarvest) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; _updateUserReward(_pid, _shouldHarvest); if (_amount > 0) { uint256 beforeDeposit = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount); uint256 afterDeposit = pool.lpToken.balanceOf(address(this)); _amount = afterDeposit.sub(beforeDeposit); user.amount = user.amount.add(_amount); pool.totalDeposited = pool.totalDeposited.add(_amount); require(pool.poolLimit > 0 && pool.totalDeposited <= pool.poolLimit, "Exceeded pool limit"); } emit Deposit(msg.sender, _pid, _amount, _shouldHarvest); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount, bool _shouldHarvest) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); require(block.timestamp > pool.unlockDate, "unlock date not reached"); _updateUserReward(_pid, _shouldHarvest); if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.totalDeposited = pool.totalDeposited.sub(_amount); pool.lpToken.safeTransfer(msg.sender, _amount); } emit Withdraw(msg.sender, _pid, _amount, _shouldHarvest); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.lastOasisPerShare = 0; user.unclaimed = 0; pool.totalDeposited = pool.totalDeposited.sub(amount); pool.lpToken.safeTransfer(msg.sender, amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Update the rewards of caller, and harvests if needed function _updateUserReward(uint256 _pid, bool _shouldHarvest) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount == 0) { user.lastOasisPerShare = pool.accOasisPerShare; } uint256 pending = user.amount.mul(pool.accOasisPerShare.sub(user.lastOasisPerShare)).div(1e18).add(user.unclaimed); user.unclaimed = _shouldHarvest ? 0 : pending; if (_shouldHarvest && pending > 0) { _lockReward(msg.sender, pending); emit Harvest(msg.sender, _pid, pending); } user.lastOasisPerShare = pool.accOasisPerShare; } // Harvest one pool function harvest(uint256 _pid) external nonReentrant { _updateUserReward(_pid, true); } // Harvest specific pools into one vest function harvestMultiple(uint256[] calldata _pids) external nonReentrant { uint256 pending = 0; for (uint256 i = 0; i < _pids.length; i++) { updatePool(_pids[i]); PoolInfo storage pool = poolInfo[_pids[i]]; UserInfo storage user = userInfo[_pids[i]][msg.sender]; if (user.amount == 0) { user.lastOasisPerShare = pool.accOasisPerShare; } pending = pending.add(user.amount.mul(pool.accOasisPerShare.sub(user.lastOasisPerShare)).div(1e18).add(user.unclaimed)); user.unclaimed = 0; user.lastOasisPerShare = pool.accOasisPerShare; } if (pending > 0) { _lockReward(msg.sender, pending); } emit HarvestMultiple(msg.sender, _pids, pending); } // Harvest all into one vest. Will probably not be used // Can fail if pool length is too big due to massUpdatePools() function harvestAll() external nonReentrant { massUpdatePools(); uint256 pending = 0; for (uint256 i = 0; i < poolInfo.length; i++) { PoolInfo storage pool = poolInfo[i]; UserInfo storage user = userInfo[i][msg.sender]; if (user.amount == 0) { user.lastOasisPerShare = pool.accOasisPerShare; } pending = pending.add(user.amount.mul(pool.accOasisPerShare.sub(user.lastOasisPerShare)).div(1e18).add(user.unclaimed)); user.unclaimed = 0; user.lastOasisPerShare = pool.accOasisPerShare; } if (pending > 0) { _lockReward(msg.sender, pending); } emit HarvestAll(msg.sender, pending); } /** * @dev Call locker contract to lock rewards */ function _lockReward(address _account, uint256 _amount) internal { uint256 oasisBal = oasis.balanceOf(address(this)); rewardLocker.lock(oasis, _account, _amount > oasisBal ? oasisBal : _amount); } // Update dev address by the previous dev. function setDevAddress(address _devAddress) external onlyOwner { require(_devAddress != address(0), "!nonzero"); devAddress = _devAddress; emit SetDevAddress(msg.sender, _devAddress); } // Should never fail as long as massUpdatePools is called during add function updateEmissionRate(uint256 _oasisPerBlock) external onlyOwner { require(_oasisPerBlock <= MAX_EMISSION_RATE, "!overmax"); massUpdatePools(); oasisPerBlock = _oasisPerBlock; emit UpdateEmissionRate(msg.sender, _oasisPerBlock); } // Update oasis transfer owner. Can only be called by existing oasisTransferOwner function setOasisTransferOwner(address _oasisTransferOwner) external { require(msg.sender == oasisTransferOwner); oasisTransferOwner = _oasisTransferOwner; emit SetOasisTransferOwner(msg.sender, _oasisTransferOwner); } /** * @dev DUE TO THIS CODE THIS CONTRACT MUST BE BEHIND A TIMELOCK (Ideally 7) * THIS FUNCTION EXISTS ONLY IF THERE IS AN ISSUE WITH THIS CONTRACT * AND TOKEN MIGRATION MUST HAPPEN */ function acceptOasisOwnership() external { require(msg.sender == oasisTransferOwner); require(pendingOasisOwner != address(0)); // oasis.transferOwnership(pendingOasisOwner); pendingOasisOwner = address(0); emit AcceptOasisOwnership(msg.sender, pendingOasisOwner); } function setPendingOasisOwnership(address _pendingOwner) external { require(msg.sender == oasisTransferOwner); pendingOasisOwner = _pendingOwner; emit NewPendingOasisOwner(msg.sender, _pendingOwner); } }
contract MasterChef is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 lastOasisPerShare; // Oasis per share on last update uint256 unclaimed; // Unclaimed reward in Oasis. // pending reward = user.unclaimed + (user.amount * (pool.accOasisPerShare - user.lastOasisPerShare) // // Whenever a user deposits or withdraws Staking tokens to a pool. Here's what happens: // 1. The pool's `accOasisPerShare` (and `lastOasisBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `lastOasisPerShare` gets updated. // 4. User's `amount` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. OASIS to distribute per block. uint256 totalDeposited; // The total deposited by users uint256 lastRewardBlock; // Last block number that OASIS distribution occurs. uint256 accOasisPerShare; // Accumulated OASIS per share, times 1e18. See below. uint256 poolLimit; uint256 unlockDate; } // The OASIS TOKEN! IERC20 public immutable oasis; address public pendingOasisOwner; address public oasisTransferOwner; address public devAddress; // Contract for locking reward IRewardLocker public immutable rewardLocker; // OASIS tokens created per block. uint256 public oasisPerBlock = 8 ether; uint256 public constant MAX_EMISSION_RATE = 1000 ether; // Safety check // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; uint256 public constant MAX_ALLOC_POINT = 100000; // Safety check // The block number when OASIS mining starts. uint256 public immutable startBlock; event Add(address indexed user, uint256 allocPoint, IERC20 indexed token, bool massUpdatePools); event Set(address indexed user, uint256 pid, uint256 allocPoint); event Deposit(address indexed user, uint256 indexed pid, uint256 amount, bool harvest); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, bool harvest); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event HarvestMultiple(address indexed user, uint256[] _pids, uint256 amount); event HarvestAll(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SetDevAddress(address indexed user, address indexed newAddress); event UpdateEmissionRate(address indexed user, uint256 oasisPerBlock); event SetOasisTransferOwner(address indexed user, address indexed oasisTransferOwner); event AcceptOasisOwnership(address indexed user, address indexed newOwner); event NewPendingOasisOwner(address indexed user, address indexed newOwner); constructor( IERC20 _oasis, uint256 _startBlock, IRewardLocker _rewardLocker, address _devAddress, address _oasisTransferOwner ) public { require(_devAddress != address(0), "!nonzero"); oasis = _oasis; startBlock = _startBlock; rewardLocker = _rewardLocker; devAddress = _devAddress; oasisTransferOwner = _oasisTransferOwner; IERC20(_oasis).safeApprove(address(_rewardLocker), uint256(0)); IERC20(_oasis).safeIncreaseAllowance( address(_rewardLocker), uint256(-1) ); } function poolLength() external view returns (uint256) { return poolInfo.length; } mapping(IERC20 => bool) public poolExistence; modifier nonDuplicated(IERC20 _lpToken) { require(poolExistence[_lpToken] == false, "nonDuplicated: duplicated"); _; } // Add a new lp to the pool. Can only be called by the owner. function add(uint256 _allocPoint, IERC20 _lpToken, bool _massUpdatePools, uint256 _poolLimit, uint256 _unlockDate) external onlyOwner nonDuplicated(_lpToken) { require(_allocPoint <= MAX_ALLOC_POINT, "!overmax"); if (_massUpdatePools) { massUpdatePools(); // This ensures that massUpdatePools will not exceed gas limit } _lpToken.balanceOf(address(this)); // Check to make sure it's a token uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolExistence[_lpToken] = true; poolInfo.push(PoolInfo({ lpToken: _lpToken, totalDeposited: 0, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accOasisPerShare: 0, poolLimit: _poolLimit, unlockDate: _unlockDate })); emit Add(msg.sender, _allocPoint, _lpToken, _massUpdatePools); } // Update the given pool's OASIS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) external onlyOwner { require(_allocPoint <= MAX_ALLOC_POINT, "!overmax"); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; emit Set(msg.sender, _pid, _allocPoint); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from); } // View function to see pending OASIS on frontend. function pendingOasis(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOasisPerShare = pool.accOasisPerShare; if (block.number > pool.lastRewardBlock && pool.totalDeposited != 0 && totalAllocPoint != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 oasisReward = multiplier.mul(oasisPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accOasisPerShare = accOasisPerShare.add(oasisReward.mul(1e18).div(pool.totalDeposited)); } return user.amount.mul(accOasisPerShare.sub(user.lastOasisPerShare)).div(1e18).add(user.unclaimed); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } if (pool.totalDeposited == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 oasisReward = multiplier.mul(oasisPerBlock).mul(pool.allocPoint).div(totalAllocPoint); // oasis.mint(devAddress, oasisReward.div(50)); // 2% // oasis.mint(address(this), oasisReward); pool.accOasisPerShare = pool.accOasisPerShare.add(oasisReward.mul(1e18).div(pool.totalDeposited)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for OASIS allocation. function deposit(uint256 _pid, uint256 _amount, bool _shouldHarvest) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; _updateUserReward(_pid, _shouldHarvest); if (_amount > 0) { uint256 beforeDeposit = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount); uint256 afterDeposit = pool.lpToken.balanceOf(address(this)); _amount = afterDeposit.sub(beforeDeposit); user.amount = user.amount.add(_amount); pool.totalDeposited = pool.totalDeposited.add(_amount); require(pool.poolLimit > 0 && pool.totalDeposited <= pool.poolLimit, "Exceeded pool limit"); } emit Deposit(msg.sender, _pid, _amount, _shouldHarvest); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount, bool _shouldHarvest) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); require(block.timestamp > pool.unlockDate, "unlock date not reached"); _updateUserReward(_pid, _shouldHarvest); if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.totalDeposited = pool.totalDeposited.sub(_amount); pool.lpToken.safeTransfer(msg.sender, _amount); } emit Withdraw(msg.sender, _pid, _amount, _shouldHarvest); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.lastOasisPerShare = 0; user.unclaimed = 0; pool.totalDeposited = pool.totalDeposited.sub(amount); pool.lpToken.safeTransfer(msg.sender, amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Update the rewards of caller, and harvests if needed function _updateUserReward(uint256 _pid, bool _shouldHarvest) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount == 0) { user.lastOasisPerShare = pool.accOasisPerShare; } uint256 pending = user.amount.mul(pool.accOasisPerShare.sub(user.lastOasisPerShare)).div(1e18).add(user.unclaimed); user.unclaimed = _shouldHarvest ? 0 : pending; if (_shouldHarvest && pending > 0) { _lockReward(msg.sender, pending); emit Harvest(msg.sender, _pid, pending); } user.lastOasisPerShare = pool.accOasisPerShare; } // Harvest one pool function harvest(uint256 _pid) external nonReentrant { _updateUserReward(_pid, true); } // Harvest specific pools into one vest function harvestMultiple(uint256[] calldata _pids) external nonReentrant { uint256 pending = 0; for (uint256 i = 0; i < _pids.length; i++) { updatePool(_pids[i]); PoolInfo storage pool = poolInfo[_pids[i]]; UserInfo storage user = userInfo[_pids[i]][msg.sender]; if (user.amount == 0) { user.lastOasisPerShare = pool.accOasisPerShare; } pending = pending.add(user.amount.mul(pool.accOasisPerShare.sub(user.lastOasisPerShare)).div(1e18).add(user.unclaimed)); user.unclaimed = 0; user.lastOasisPerShare = pool.accOasisPerShare; } if (pending > 0) { _lockReward(msg.sender, pending); } emit HarvestMultiple(msg.sender, _pids, pending); } // Harvest all into one vest. Will probably not be used // Can fail if pool length is too big due to massUpdatePools() function harvestAll() external nonReentrant { massUpdatePools(); uint256 pending = 0; for (uint256 i = 0; i < poolInfo.length; i++) { PoolInfo storage pool = poolInfo[i]; UserInfo storage user = userInfo[i][msg.sender]; if (user.amount == 0) { user.lastOasisPerShare = pool.accOasisPerShare; } pending = pending.add(user.amount.mul(pool.accOasisPerShare.sub(user.lastOasisPerShare)).div(1e18).add(user.unclaimed)); user.unclaimed = 0; user.lastOasisPerShare = pool.accOasisPerShare; } if (pending > 0) { _lockReward(msg.sender, pending); } emit HarvestAll(msg.sender, pending); } /** * @dev Call locker contract to lock rewards */ function _lockReward(address _account, uint256 _amount) internal { uint256 oasisBal = oasis.balanceOf(address(this)); rewardLocker.lock(oasis, _account, _amount > oasisBal ? oasisBal : _amount); } // Update dev address by the previous dev. function setDevAddress(address _devAddress) external onlyOwner { require(_devAddress != address(0), "!nonzero"); devAddress = _devAddress; emit SetDevAddress(msg.sender, _devAddress); } // Should never fail as long as massUpdatePools is called during add function updateEmissionRate(uint256 _oasisPerBlock) external onlyOwner { require(_oasisPerBlock <= MAX_EMISSION_RATE, "!overmax"); massUpdatePools(); oasisPerBlock = _oasisPerBlock; emit UpdateEmissionRate(msg.sender, _oasisPerBlock); } // Update oasis transfer owner. Can only be called by existing oasisTransferOwner function setOasisTransferOwner(address _oasisTransferOwner) external { require(msg.sender == oasisTransferOwner); oasisTransferOwner = _oasisTransferOwner; emit SetOasisTransferOwner(msg.sender, _oasisTransferOwner); } /** * @dev DUE TO THIS CODE THIS CONTRACT MUST BE BEHIND A TIMELOCK (Ideally 7) * THIS FUNCTION EXISTS ONLY IF THERE IS AN ISSUE WITH THIS CONTRACT * AND TOKEN MIGRATION MUST HAPPEN */ function acceptOasisOwnership() external { require(msg.sender == oasisTransferOwner); require(pendingOasisOwner != address(0)); // oasis.transferOwnership(pendingOasisOwner); pendingOasisOwner = address(0); emit AcceptOasisOwnership(msg.sender, pendingOasisOwner); } function setPendingOasisOwnership(address _pendingOwner) external { require(msg.sender == oasisTransferOwner); pendingOasisOwner = _pendingOwner; emit NewPendingOasisOwner(msg.sender, _pendingOwner); } }
52,972
5
// function to get the Proof of existence for a file/
function GetFileExistenceProof(address dappBoxOrigin,string memory fileHash, string memory filePathHash) public view returns(uint256,address,address,BlockchainIdentification,bytes32) { for(uint i = 0 ; i < fileExistenceProofs[dappBoxOrigin].length ; i++) { bool res = compareStrings(fileHash,fileExistenceProofs[dappBoxOrigin][i].fileHash) && compareStrings(filePathHash,fileExistenceProofs[dappBoxOrigin][i].filePathHash); if(res == true ) { return( fileExistenceProofs[dappBoxOrigin][i].date, fileExistenceProofs[dappBoxOrigin][i].filesender, fileExistenceProofs[dappBoxOrigin][i].contractAddress, fileExistenceProofs[dappBoxOrigin][i].identifier, fileExistenceProofs[dappBoxOrigin][i].QRCodeHash); } } }
function GetFileExistenceProof(address dappBoxOrigin,string memory fileHash, string memory filePathHash) public view returns(uint256,address,address,BlockchainIdentification,bytes32) { for(uint i = 0 ; i < fileExistenceProofs[dappBoxOrigin].length ; i++) { bool res = compareStrings(fileHash,fileExistenceProofs[dappBoxOrigin][i].fileHash) && compareStrings(filePathHash,fileExistenceProofs[dappBoxOrigin][i].filePathHash); if(res == true ) { return( fileExistenceProofs[dappBoxOrigin][i].date, fileExistenceProofs[dappBoxOrigin][i].filesender, fileExistenceProofs[dappBoxOrigin][i].contractAddress, fileExistenceProofs[dappBoxOrigin][i].identifier, fileExistenceProofs[dappBoxOrigin][i].QRCodeHash); } } }
1,400
11
// A record of rates, by index
mapping (uint32 => RateCheckpoint) public rateCheckpoints;
mapping (uint32 => RateCheckpoint) public rateCheckpoints;
52,751
54
// We require that the owner should be multisig walletBecause owner can make important decisions like stopping prefundand setting TransformAgentHowever this contract can be created by any account. After creationit automatically transfers ownership to multisig wallet
transferOwnership(multisig); multisigWallet = multisig;
transferOwnership(multisig); multisigWallet = multisig;
43,029
10
// Inits the agreement /
function init( address payable _platformAddress, address _link, address _oracle, address _tokenPaymentAddress, address payable _brand, address payable _influencer, uint256 _endDate, uint256 _payPerView,
function init( address payable _platformAddress, address _link, address _oracle, address _tokenPaymentAddress, address payable _brand, address payable _influencer, uint256 _endDate, uint256 _payPerView,
50,186
149
// The BRRR TOKEN!
FodToken public fod;
FodToken public fod;
1,320
5
// Creates new token with token ID specified and assigns an ownership `_to` for this tokenChecks if `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received` on `_to` and throws if the return value is not `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.Should have a restricted access handled by the implementation_to an address to mint token to _tokenId ID of the token to mint _data additional data with no specified format, sent in call to `_to` /
function safeMint(address _to, uint256 _tokenId, bytes memory _data) external;
function safeMint(address _to, uint256 _tokenId, bytes memory _data) external;
9,371
25
// Function that is run as the first thing in the fallback function.Can be redefined in derived contracts to add functionality.Redefinitions must call super._willFallback(). /
function _willFallback() internal virtual { }
function _willFallback() internal virtual { }
25,234
141
// Safe traffick transfer function, just in case if rounding error causes pool to not have enough Trafficks.
function safeTraffickTransfer(address _to, uint256 _amount) internal { uint256 traffickBal = traffick.balanceOf(address(this)); if (_amount > traffickBal) { traffick.transfer(_to, traffickBal); } else { traffick.transfer(_to, _amount); } }
function safeTraffickTransfer(address _to, uint256 _amount) internal { uint256 traffickBal = traffick.balanceOf(address(this)); if (_amount > traffickBal) { traffick.transfer(_to, traffickBal); } else { traffick.transfer(_to, _amount); } }
21,913
13
// Sets the distribution reward rate. This will also update the poolInfo./_tokenPerSec The number of tokens to distribute per second
function setRewardRate(uint256 _tokenPerSec) external onlyOwner { updatePool(); uint256 oldRate = tokenPerSec; tokenPerSec = _tokenPerSec; emit RewardRateUpdated(oldRate, _tokenPerSec); }
function setRewardRate(uint256 _tokenPerSec) external onlyOwner { updatePool(); uint256 oldRate = tokenPerSec; tokenPerSec = _tokenPerSec; emit RewardRateUpdated(oldRate, _tokenPerSec); }
31,687
8
// _exchangeIdx The private data exchange index
function finishPrivateDataExchange(uint256 _exchangeIdx) external { require(_exchangeIdx < privateDataExchanges.length, "invalid exchange index"); PrivateDataExchange storage exchange = privateDataExchanges[_exchangeIdx]; require(PrivateDataExchangeState.Accepted == exchange.state, "exchange must be in accepted state"); require(_nowSeconds() > exchange.stateExpired || msg.sender == exchange.dataRequester, "exchange must be either expired or be finished by the data requester"); exchange.state = PrivateDataExchangeState.Closed; // transfer all exchange staked money to passport owner uint256 val = exchange.dataRequesterValue.add(exchange.passportOwnerValue); require(exchange.passportOwner.send(val)); _decOpenPrivateDataExchangesCount(); emit PrivateDataExchangeClosed(_exchangeIdx); }
function finishPrivateDataExchange(uint256 _exchangeIdx) external { require(_exchangeIdx < privateDataExchanges.length, "invalid exchange index"); PrivateDataExchange storage exchange = privateDataExchanges[_exchangeIdx]; require(PrivateDataExchangeState.Accepted == exchange.state, "exchange must be in accepted state"); require(_nowSeconds() > exchange.stateExpired || msg.sender == exchange.dataRequester, "exchange must be either expired or be finished by the data requester"); exchange.state = PrivateDataExchangeState.Closed; // transfer all exchange staked money to passport owner uint256 val = exchange.dataRequesterValue.add(exchange.passportOwnerValue); require(exchange.passportOwner.send(val)); _decOpenPrivateDataExchangesCount(); emit PrivateDataExchangeClosed(_exchangeIdx); }
10,478
5
// 募资
CrowdFunding, CrowdFundingSuccess, CrowdFundingFail, UnRepay,//待还款 RepaySuccess, Overdue,
CrowdFunding, CrowdFundingSuccess, CrowdFundingFail, UnRepay,//待还款 RepaySuccess, Overdue,
36,049
64
// Checks whether the period in which the crowdsale is started.return Whether crowdsale period has started /
function hasStarted() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp < closingTime && block.timestamp >= openingTime; }
function hasStarted() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp < closingTime && block.timestamp >= openingTime; }
23,644
18
// insert new bid
Bid memory newBid; newBid.from = msg.sender; newBid.amount = ethAmountbid; auctionBids[auctionId].push(newBid); payable(address(this)).transfer(msg.value);
Bid memory newBid; newBid.from = msg.sender; newBid.amount = ethAmountbid; auctionBids[auctionId].push(newBid); payable(address(this)).transfer(msg.value);
8,840
58
// Register a service contract whose activation is deferred by the service activation timeout/service The address of the service contract to be registered
function registerServiceDeferred(address service) public onlyDeployer notNullOrThisAddress(service)
function registerServiceDeferred(address service) public onlyDeployer notNullOrThisAddress(service)
29,011
64
// transfer total ETH of investors to owner
owner.transfer(sum);
owner.transfer(sum);
35,049
133
// Last claimed time
mapping(address => uint256) public lastClaimedTime;
mapping(address => uint256) public lastClaimedTime;
40,448
209
// Copied from OpenZeppelin https:github.com/OpenZeppelin/openzeppelin-contracts/blob/c3ae4790c71b7f53cc8fff743536dcb7031fed74/contracts/token/ERC1155/ERC1155.solL440
function asSingletonArray(uint256 element) private pure returns (uint256[] memory)
function asSingletonArray(uint256 element) private pure returns (uint256[] memory)
27,332
168
// utility, checks whether allowance for the given spender exists and approves one if it doesn't. Note that we use the non standard erc-20 interface in which `approve` has no return value so that this function will work for both standard and non standard tokens_token token to check the allowance in_spender approved address_value allowance amount/
function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private { uint256 allowance = _token.allowance(address(this), _spender); if (allowance < _value) { if (allowance > 0) safeApprove(_token, _spender, 0); safeApprove(_token, _spender, _value); } }
function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private { uint256 allowance = _token.allowance(address(this), _spender); if (allowance < _value) { if (allowance > 0) safeApprove(_token, _spender, 0); safeApprove(_token, _spender, _value); } }
5,447
134
// hasBeenLinked(): returns true if the point has ever been assigned keys
function hasBeenLinked(uint32 _point) view external returns (bool result)
function hasBeenLinked(uint32 _point) view external returns (bool result)
39,077
162
// Deposit LP tokens to Chef for TOKEN allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTokenTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if(pool.depositFeeBP > 0){ uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee.div(20).mul(19)); pool.lpToken.safeTransfer(feeAddress2, depositFee.div(20)); user.amount = user.amount.add(_amount).sub(depositFee); }else{ user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTokenTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if(pool.depositFeeBP > 0){ uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee.div(20).mul(19)); pool.lpToken.safeTransfer(feeAddress2, depositFee.div(20)); user.amount = user.amount.add(_amount).sub(depositFee); }else{ user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
13,134
89
// Check that proposal creator, owner or an admin is removing a proposal.
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
require(msg.sender == currentProposal.creator || msg.sender == _creator || _admins.contains(msg.sender));
10,811
36
// Update the mappings
recipientToGiftIds[recipient].push(nextGiftId); giftIdToGift[nextGiftId] = Gift(true, nextGiftId, giver, recipient, expiry, amtGiven, false, giverName, message, now); uint giftId = nextGiftId;
recipientToGiftIds[recipient].push(nextGiftId); giftIdToGift[nextGiftId] = Gift(true, nextGiftId, giver, recipient, expiry, amtGiven, false, giverName, message, now); uint giftId = nextGiftId;
46,014
552
// all clear - calculate the max principal amount that can be liquidated
vars.maxPrincipalAmountToLiquidate = vars .userCompoundedBorrowBalance .mul(LIQUIDATION_CLOSE_FACTOR_PERCENT) .div(100); vars.actualAmountToLiquidate = _purchaseAmount > vars.maxPrincipalAmountToLiquidate ? vars.maxPrincipalAmountToLiquidate : _purchaseAmount; (uint256 maxCollateralToLiquidate, uint256 principalAmountNeeded) = calculateAvailableCollateralToLiquidate(
vars.maxPrincipalAmountToLiquidate = vars .userCompoundedBorrowBalance .mul(LIQUIDATION_CLOSE_FACTOR_PERCENT) .div(100); vars.actualAmountToLiquidate = _purchaseAmount > vars.maxPrincipalAmountToLiquidate ? vars.maxPrincipalAmountToLiquidate : _purchaseAmount; (uint256 maxCollateralToLiquidate, uint256 principalAmountNeeded) = calculateAvailableCollateralToLiquidate(
7,151
0
// to convert either to wei and the other way around
uint BIGNUMBER = 10**18;
uint BIGNUMBER = 10**18;
38,577
126
// team -> grantable
ethealToken.generateTokens(address(this), TOKEN_FOUNDERS.add(TOKEN_TEAM));
ethealToken.generateTokens(address(this), TOKEN_FOUNDERS.add(TOKEN_TEAM));
32,314
5
// Returns the donation information
function getDonation(uint256 _id) external view returns ( uint256 _originalDonationId, uint256 _donationId, string _description, uint256 _goal, uint256 _raised, uint256 _amount, address _beneficiary, address _donor,
function getDonation(uint256 _id) external view returns ( uint256 _originalDonationId, uint256 _donationId, string _description, uint256 _goal, uint256 _raised, uint256 _amount, address _beneficiary, address _donor,
12,469
24
// Set the WBTC-A stability fee Previous: 2% New: 4%
JugAbstract(mcd_jug931).DRIP219("WBTC-A"); // drip right before JugAbstract(mcd_jug931).FILE40("WBTC-A", "duty", four_pct_rate701);
JugAbstract(mcd_jug931).DRIP219("WBTC-A"); // drip right before JugAbstract(mcd_jug931).FILE40("WBTC-A", "duty", four_pct_rate701);
30,409
45
// Info of each user that stakes LP tokens. poolId => address => staker
mapping (uint256 => mapping (address => Staker)) public stakers;
mapping (uint256 => mapping (address => Staker)) public stakers;
67,514
42
// lock the address value, set the unlock time /
function lockedValuesAndTime(address target, uint256 lockedSupply, uint lockedTimes, uint unlockTime) internal onlyOwner returns (bool success) { require(0x0 != target); releasedBalance[target] = 0; lockedBalance[target] = lockedSupply; for (uint i = 0; i < lockedTimes; i++) { if (i > 0) { unlockTime = unlockTime + 30 days; } uint256 lockedValue = lockedSupply.div(lockedTimes); if (i == lockedTimes - 1) { //the last unlock time lockedValue = lockedSupply.div(lockedTimes).add(lockedSupply.mod(lockedTimes)); } allocations[target].push(TimeLock(unlockTime, lockedValue)); } return true; }
function lockedValuesAndTime(address target, uint256 lockedSupply, uint lockedTimes, uint unlockTime) internal onlyOwner returns (bool success) { require(0x0 != target); releasedBalance[target] = 0; lockedBalance[target] = lockedSupply; for (uint i = 0; i < lockedTimes; i++) { if (i > 0) { unlockTime = unlockTime + 30 days; } uint256 lockedValue = lockedSupply.div(lockedTimes); if (i == lockedTimes - 1) { //the last unlock time lockedValue = lockedSupply.div(lockedTimes).add(lockedSupply.mod(lockedTimes)); } allocations[target].push(TimeLock(unlockTime, lockedValue)); } return true; }
68,458
256
// Upper tick of the position
int24 upper;
int24 upper;
38,618
75
// https:docs.synthetix.io/contracts/source/interfaces/isynthetix
interface ISynthetix { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey) external view returns (uint); function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferableSynthetix(address account) external view returns (uint transferable); // Mutative Functions function burnSynths(uint amount) external; function burnSynthsOnBehalf(address burnForAddress, uint amount) external; function burnSynthsToTarget() external; function burnSynthsToTargetOnBehalf(address burnForAddress) external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function issueMaxSynths() external; function issueMaxSynthsOnBehalf(address issueForAddress) external; function issueSynths(uint amount) external; function issueSynthsOnBehalf(address issueForAddress, uint amount) external; function mint() external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; }
interface ISynthetix { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey) external view returns (uint); function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferableSynthetix(address account) external view returns (uint transferable); // Mutative Functions function burnSynths(uint amount) external; function burnSynthsOnBehalf(address burnForAddress, uint amount) external; function burnSynthsToTarget() external; function burnSynthsToTargetOnBehalf(address burnForAddress) external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function issueMaxSynths() external; function issueMaxSynthsOnBehalf(address issueForAddress) external; function issueSynths(uint amount) external; function issueSynthsOnBehalf(address issueForAddress, uint amount) external; function mint() external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; }
13,057
0
// Event emits after token minting /
event MintNTT(address indexed account, uint256 indexed tokenId, Metadata metadata);
event MintNTT(address indexed account, uint256 indexed tokenId, Metadata metadata);
24,495
10
// 0x08 id of precompiled bn256Pairing contract (checking the elliptic curve pairings) add(input, 0x20) since we have an unbounded array, the first 256 bits refer to its length mul(inputSize, 0x20) size of call parameters, each word is 0x20 bytes 0x20 size of result (one 32 byte boolean!)
success := staticcall(not(0), 0x08, add(input, 0x20), mul(inputSize, 0x20), result, 0x20)
success := staticcall(not(0), 0x08, add(input, 0x20), mul(inputSize, 0x20), result, 0x20)
20,491
1
// Fixed point scale /
uint256 internal constant FIXED_POINT_SCALE = 1e18;
uint256 internal constant FIXED_POINT_SCALE = 1e18;
16,402
0
// Set at contract creation and is not able to updated or changed
address public transactionsContract; constructor( QuicToken _Quic, address _devaddr, address _liquidityaddr, address _comfundaddr, address _founderaddr, uint256 _rewardPerBlock, uint256 _startBlock,
address public transactionsContract; constructor( QuicToken _Quic, address _devaddr, address _liquidityaddr, address _comfundaddr, address _founderaddr, uint256 _rewardPerBlock, uint256 _startBlock,
13,706
1,147
// Indicates that the contract is in the process of being initialized. /
bool private _initializing;
bool private _initializing;
3,664
347
// Called by owner to increase the LMSR parameter `b` by depositing base tokens. `b` uses same decimals as baseToken /
function increaseB(uint256 _b) external payable onlyOwner nonReentrant returns (uint256 amountIn) { require(_b > b, "New b must be higher"); // increase b and calculate amount to be paid by owner uint256 costBefore = lastCost; b = _b; lastCost = currentCumulativeCost(); amountIn = lastCost.sub(costBefore); require(amountIn > 0, "Amount in must be > 0"); // transfer amount from owner uint256 balanceBefore = baseToken.uniBalanceOf(address(this)); baseToken.uniTransferFromSenderToThis(amountIn); uint256 balanceAfter = baseToken.uniBalanceOf(address(this)); require(baseToken.isETH() || balanceAfter.sub(balanceBefore) == amountIn, "Deflationary tokens not supported"); require(balanceCap == 0 || baseToken.uniBalanceOf(address(this)) <= balanceCap, "Balance cap exceeded"); emit UpdatedB(b, lastCost.sub(costBefore)); }
function increaseB(uint256 _b) external payable onlyOwner nonReentrant returns (uint256 amountIn) { require(_b > b, "New b must be higher"); // increase b and calculate amount to be paid by owner uint256 costBefore = lastCost; b = _b; lastCost = currentCumulativeCost(); amountIn = lastCost.sub(costBefore); require(amountIn > 0, "Amount in must be > 0"); // transfer amount from owner uint256 balanceBefore = baseToken.uniBalanceOf(address(this)); baseToken.uniTransferFromSenderToThis(amountIn); uint256 balanceAfter = baseToken.uniBalanceOf(address(this)); require(baseToken.isETH() || balanceAfter.sub(balanceBefore) == amountIn, "Deflationary tokens not supported"); require(balanceCap == 0 || baseToken.uniBalanceOf(address(this)) <= balanceCap, "Balance cap exceeded"); emit UpdatedB(b, lastCost.sub(costBefore)); }
7,529
18
// 查询id
function getTransactionId(uint fromChainId, bytes memory txHash, address toToken, address recipient, uint256 amount) pure public returns (bytes32){ // 根据来源跨链交易生成唯一hash id,作为这笔跨链的id bytes32 transactionId = keccak256(abi.encodePacked(fromChainId, txHash, toToken, recipient, amount)); return transactionId; }
function getTransactionId(uint fromChainId, bytes memory txHash, address toToken, address recipient, uint256 amount) pure public returns (bytes32){ // 根据来源跨链交易生成唯一hash id,作为这笔跨链的id bytes32 transactionId = keccak256(abi.encodePacked(fromChainId, txHash, toToken, recipient, amount)); return transactionId; }
9,969
25
// use totalBurn for Record the number of burns
mapping (address => uint256) public balanceBurn;
mapping (address => uint256) public balanceBurn;
19,625
13
// Burn DAIPoints
_burn(msg.sender, _amount);
_burn(msg.sender, _amount);
32,946
295
// The list is not full yet.Just add the player to the list.
leaderBoardPlayers.push(_addressToUpdate); addressToIsInLeaderboard[_addressToUpdate] = true; isChanged = true;
leaderBoardPlayers.push(_addressToUpdate); addressToIsInLeaderboard[_addressToUpdate] = true; isChanged = true;
17,406
3
// This generates a public event on the blockchain
event Transfer(address indexed from, address indexed to, uint256 value); event FundTransfer(address backer, uint amount, bool isContribution);
event Transfer(address indexed from, address indexed to, uint256 value); event FundTransfer(address backer, uint amount, bool isContribution);
50,377
7
// Returns the message sender as address. _message ABI encoded Hyperlane message.return Sender of `_message` as address /
function senderAddress(bytes calldata _message) internal pure returns (address)
function senderAddress(bytes calldata _message) internal pure returns (address)
25,181
200
// MasterChef is the master of SDefo. He can make SDefo and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once SDEFO is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SDEFOs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSDefoPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSDefoPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SDEFOs to distribute per block. uint256 lastRewardBlock; // Last block number that SDEFOs distribution occurs. uint256 accSDefoPerShare; // Accumulated SDEFOs per share, times 1e12. See below. } // The SDEFO TOKEN! sDefhold public sdefo; // Dev address. address public devaddr; // Block number when bonus SDEFO period ends. uint256 public bonusEndBlock; // SDEFO tokens created per block. uint256 public sdefoPerBlock; // Bonus muliplier for early sdefo makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SDEFO mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( sDefhold _sdefo, address _devaddr, uint256 _sdefoPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { sdefo = _sdefo; devaddr = _devaddr; sdefoPerBlock = _sdefoPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSDefoPerShare: 0 })); } // Update the given pool's SDEFO allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending SDEFOs on frontend. function pendingSDefo(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSDefoPerShare = pool.accSDefoPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sdefoReward = multiplier.mul(sdefoPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSDefoPerShare = accSDefoPerShare.add(sdefoReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSDefoPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sdefoReward = multiplier.mul(sdefoPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sdefo.mint(devaddr, sdefoReward.div(10)); sdefo.mint(address(this), sdefoReward); pool.accSDefoPerShare = pool.accSDefoPerShare.add(sdefoReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SDEFO allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSDefoPerShare).div(1e12).sub(user.rewardDebt); safeSDefoTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSDefoPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSDefoPerShare).div(1e12).sub(user.rewardDebt); safeSDefoTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSDefoPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sdefo transfer function, just in case if rounding error causes pool to not have enough SDEFOs. function safeSDefoTransfer(address _to, uint256 _amount) internal { uint256 sdefoBal = sdefo.balanceOf(address(this)); if (_amount > sdefoBal) { sdefo.transfer(_to, sdefoBal); } else { sdefo.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SDEFOs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSDefoPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSDefoPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SDEFOs to distribute per block. uint256 lastRewardBlock; // Last block number that SDEFOs distribution occurs. uint256 accSDefoPerShare; // Accumulated SDEFOs per share, times 1e12. See below. } // The SDEFO TOKEN! sDefhold public sdefo; // Dev address. address public devaddr; // Block number when bonus SDEFO period ends. uint256 public bonusEndBlock; // SDEFO tokens created per block. uint256 public sdefoPerBlock; // Bonus muliplier for early sdefo makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SDEFO mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( sDefhold _sdefo, address _devaddr, uint256 _sdefoPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { sdefo = _sdefo; devaddr = _devaddr; sdefoPerBlock = _sdefoPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSDefoPerShare: 0 })); } // Update the given pool's SDEFO allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending SDEFOs on frontend. function pendingSDefo(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSDefoPerShare = pool.accSDefoPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sdefoReward = multiplier.mul(sdefoPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSDefoPerShare = accSDefoPerShare.add(sdefoReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSDefoPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sdefoReward = multiplier.mul(sdefoPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sdefo.mint(devaddr, sdefoReward.div(10)); sdefo.mint(address(this), sdefoReward); pool.accSDefoPerShare = pool.accSDefoPerShare.add(sdefoReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SDEFO allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSDefoPerShare).div(1e12).sub(user.rewardDebt); safeSDefoTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSDefoPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSDefoPerShare).div(1e12).sub(user.rewardDebt); safeSDefoTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSDefoPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sdefo transfer function, just in case if rounding error causes pool to not have enough SDEFOs. function safeSDefoTransfer(address _to, uint256 _amount) internal { uint256 sdefoBal = sdefo.balanceOf(address(this)); if (_amount > sdefoBal) { sdefo.transfer(_to, sdefoBal); } else { sdefo.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
5,682
10
// NOTE: this interface lacks return values for transfer/transferFrom/approve on purpose, as we use the SafeERC20 library to check the return value
interface GeneralERC20 { function transfer(address to, uint256 amount) external; function transferFrom(address from, address to, uint256 amount) external; function approve(address spender, uint256 amount) external; function balanceOf(address spender) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); }
interface GeneralERC20 { function transfer(address to, uint256 amount) external; function transferFrom(address from, address to, uint256 amount) external; function approve(address spender, uint256 amount) external; function balanceOf(address spender) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); }
51,429
137
// Validates that an interest collection does not exceed a maximum APY. If last collectionwas under 30 mins ago, simply check it does not exceed 10bps _newSupply New total supply of the mAsset _interestIncrease in total supply since last collection _timeSinceLastCollection Seconds since last collection /
function validateCollection( uint256 _newSupply, uint256 _interest, uint256 _timeSinceLastCollection
function validateCollection( uint256 _newSupply, uint256 _interest, uint256 _timeSinceLastCollection
38,494
0
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress; event Mint(address _to, uint256 attack, uint256 defend, uint256 rank, uint256 _tokenId); event UpdateSkill(uint256 _id, uint256 _attack, uint256 _defend, uint256 _rank);
address public newContractAddress; event Mint(address _to, uint256 attack, uint256 defend, uint256 rank, uint256 _tokenId); event UpdateSkill(uint256 _id, uint256 _attack, uint256 _defend, uint256 _rank);
26,686
146
// View function to see pending SUMMAs on frontend.
function pendingSumma(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSummaPerShare = pool.accSummaPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardTime && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardTime, block.number); uint256 summaReward = multiplier.mul(pool.allocPoint).div(totalAllocPoint); accSummaPerShare = accSummaPerShare.add(summaReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSummaPerShare).div(1e12).sub(user.rewardDebt); }
function pendingSumma(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSummaPerShare = pool.accSummaPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardTime && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardTime, block.number); uint256 summaReward = multiplier.mul(pool.allocPoint).div(totalAllocPoint); accSummaPerShare = accSummaPerShare.add(summaReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSummaPerShare).div(1e12).sub(user.rewardDebt); }
68,179
1
// enum GoodsStatus
uint16 constant internal None = 0; uint16 constant internal Available = 1; uint16 constant internal Canceled = 2;
uint16 constant internal None = 0; uint16 constant internal Available = 1; uint16 constant internal Canceled = 2;
40,206
54
// Delight와 DPlay 교역소는 모든 토큰을 전송할 수 있습니다.
msg.sender == delightItemManager || msg.sender == dplayTradingPost;
msg.sender == delightItemManager || msg.sender == dplayTradingPost;
21,596
16
// no need to check lid, wrapTokenX, wrapTokenY because core will revert unenough deposit and this contract will not save any token(including eth) theorily so we donot care that some one will steal token from this contract
uint256 actualLimX = _recvTokenFromUser(tokenX, tokenXIsWrap, addParam.xLim); uint256 actualLimY = _recvTokenFromUser(tokenY, tokenYIsWrap, addParam.yLim); delete isMintOrAddLiquidity; ILiquidityManager.AddLiquidityParam memory actualParam = addParam; actualParam.xLim = uint128(actualLimX); actualParam.yLim = uint128(actualLimY); if (tokenX != peripheryAddr.weth) { IERC20(tokenX).approve(peripheryAddr.liquidityManager, type(uint256).max); }
uint256 actualLimX = _recvTokenFromUser(tokenX, tokenXIsWrap, addParam.xLim); uint256 actualLimY = _recvTokenFromUser(tokenY, tokenYIsWrap, addParam.yLim); delete isMintOrAddLiquidity; ILiquidityManager.AddLiquidityParam memory actualParam = addParam; actualParam.xLim = uint128(actualLimX); actualParam.yLim = uint128(actualLimY); if (tokenX != peripheryAddr.weth) { IERC20(tokenX).approve(peripheryAddr.liquidityManager, type(uint256).max); }
26,712
6
// the TRIBE token contract
ITribe public override tribe;
ITribe public override tribe;
73,720
175
// Private function to add a token to this extension's token tracking data structures. tokenId uint256 ID of the token to be added to the tokens list /
function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); }
function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); }
142
159
// fetch the rate and treat is as current, so inverse limits if frozen will always be applied regardless of current rate
(rates[i], times[i]) = _getRateAndTimestampAtRound(currencyKey, roundId); if (roundId == 0) {
(rates[i], times[i]) = _getRateAndTimestampAtRound(currencyKey, roundId); if (roundId == 0) {
26,073
18
// Emitted when the ownership is transferred.
event OwnershipTransferred(address indexed from, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
3,693
2
// All type hashes have this format: (bytes calldata, address sender, uint256 nonce, uint256 deadline).
bytes32 structHash = keccak256( abi.encode(typeHash, keccak256(_calldata()), msg.sender, getNextNonce(user), deadline) ); _ensureValidSignature(user, structHash, _signature(), deadline, errorCode);
bytes32 structHash = keccak256( abi.encode(typeHash, keccak256(_calldata()), msg.sender, getNextNonce(user), deadline) ); _ensureValidSignature(user, structHash, _signature(), deadline, errorCode);
12,218
26
// Emit an event to notify listeners of the withdrawal
emit WithdrawFunds(projectId, msg.sender, amount);
emit WithdrawFunds(projectId, msg.sender, amount);
206
13
// if the new size is smaller, removed array elements will be cleared
m_pairsOfFlags.length = newSize;
m_pairsOfFlags.length = newSize;
27,062
54
// Interface for Bank NFT
interface I_TokenBank { function Mint(uint8, address) external; //amount, to function totalSupply() external view returns (uint256); function setApprovalForAll(address, bool) external; //address, operator function transferFrom(address, address, uint256) external; function ownerOf(uint256) external view returns (address); //who owns this token function _ownerOf16(uint16) external view returns (address); function addController(address) external; }
interface I_TokenBank { function Mint(uint8, address) external; //amount, to function totalSupply() external view returns (uint256); function setApprovalForAll(address, bool) external; //address, operator function transferFrom(address, address, uint256) external; function ownerOf(uint256) external view returns (address); //who owns this token function _ownerOf16(uint16) external view returns (address); function addController(address) external; }
75,033
312
// Increase the boost total proportionately.
totalFeiBoosted += feiAmount;
totalFeiBoosted += feiAmount;
71,868
0
// key is the cToken address, value is the priceFeed address
mapping(address => address) priceFeeds; event NewPriceFeed(address cToken, address oldPriceFeed, address newPriceFeed);
mapping(address => address) priceFeeds; event NewPriceFeed(address cToken, address oldPriceFeed, address newPriceFeed);
40,789
193
// update loan end time
loanLocal.endTimestamp = loanLocal.endTimestamp .add(maxDuration); uint256 interestAmountRequired = loanLocal.endTimestamp .sub(block.timestamp); interestAmountRequired = interestAmountRequired .mul(loanInterestLocal.owedPerDay); interestAmountRequired = interestAmountRequired .div(24 hours);
loanLocal.endTimestamp = loanLocal.endTimestamp .add(maxDuration); uint256 interestAmountRequired = loanLocal.endTimestamp .sub(block.timestamp); interestAmountRequired = interestAmountRequired .mul(loanInterestLocal.owedPerDay); interestAmountRequired = interestAmountRequired .div(24 hours);
15,634
97
// See {ERC20-_burn} and {ERC20-allowance}. /
function burnFrom(address _account, uint256 _amount) public virtual { uint256 decreasedAllowance = allowance(_account, msg.sender).sub(_amount, "ERC20: burn amount exceeds allowance"); _approve(_account, msg.sender, decreasedAllowance); _burn(_account, _amount); _moveDelegates(_delegates[_account], address(0), _amount); }
function burnFrom(address _account, uint256 _amount) public virtual { uint256 decreasedAllowance = allowance(_account, msg.sender).sub(_amount, "ERC20: burn amount exceeds allowance"); _approve(_account, msg.sender, decreasedAllowance); _burn(_account, _amount); _moveDelegates(_delegates[_account], address(0), _amount); }
36,635
13
// 1. player mints a base character NFT/ TODO add whitelist
function mintGenesis(uint256 _donation) external { require(dlc.balanceOf(msg.sender) >= 10e18, "mintGenesisCharacter: Love balance is not enough"); BaseCharacterStorage.Layout storage bcs = BaseCharacterStorage.layout(); /// @dev player can only mint 1 // require(erc.holderTokens[msg.sender].length() == 0, "mintGenesis: msg.sender balance > 0"); // require(bcs.baseCharId[msg.sender] == 0, "mintGenesis: msg.sender balance > 0"); require(balanceOf(msg.sender) == 0, "mintGenesis: msg.sender NFT balance > 0"); require(totalSupply() < 2_000, "2_000 already exist"); dlc.transferFrom(msg.sender, 0x000000000000000000000000000000000000dEaD, 10e18); // dlc.transfer(0x000000000000000000000000000000000000dEaD, 10e18); uint256 prevTokenId = totalSupply(); uint256 newTokenId = prevTokenId + 1; if (_donation > 0) { if (weth.balanceOf(msg.sender) >= _donation) { // weth.transfer(address(this), _donation); weth.transferFrom(msg.sender, address(this), _donation); bcs.empathy[newTokenId] + _donation; } } // ERC721BaseStorage.Layout storage l = ERC721BaseStorage.layout(); // TODO implement on721Received in test contract // _safeMint(msg.sender, prevTokenId + 1); _mint(msg.sender, newTokenId); requestRandomness(newTokenId); }
function mintGenesis(uint256 _donation) external { require(dlc.balanceOf(msg.sender) >= 10e18, "mintGenesisCharacter: Love balance is not enough"); BaseCharacterStorage.Layout storage bcs = BaseCharacterStorage.layout(); /// @dev player can only mint 1 // require(erc.holderTokens[msg.sender].length() == 0, "mintGenesis: msg.sender balance > 0"); // require(bcs.baseCharId[msg.sender] == 0, "mintGenesis: msg.sender balance > 0"); require(balanceOf(msg.sender) == 0, "mintGenesis: msg.sender NFT balance > 0"); require(totalSupply() < 2_000, "2_000 already exist"); dlc.transferFrom(msg.sender, 0x000000000000000000000000000000000000dEaD, 10e18); // dlc.transfer(0x000000000000000000000000000000000000dEaD, 10e18); uint256 prevTokenId = totalSupply(); uint256 newTokenId = prevTokenId + 1; if (_donation > 0) { if (weth.balanceOf(msg.sender) >= _donation) { // weth.transfer(address(this), _donation); weth.transferFrom(msg.sender, address(this), _donation); bcs.empathy[newTokenId] + _donation; } } // ERC721BaseStorage.Layout storage l = ERC721BaseStorage.layout(); // TODO implement on721Received in test contract // _safeMint(msg.sender, prevTokenId + 1); _mint(msg.sender, newTokenId); requestRandomness(newTokenId); }
19,889
147
// The NOVA TOKEN!
NovaToken public nova;
NovaToken public nova;
49,815
24
// helper function to transfer the ownership of a video's tokenId./ Only accessible to trusted contracts./_from address which you want to send the token from./_to address which you want to transfer the token to./_tokenId uint256 ID of the token of the video to be transferred.
function transferVideoTrusted( address _from, address _to, uint256 _tokenId) public whenNotPaused
function transferVideoTrusted( address _from, address _to, uint256 _tokenId) public whenNotPaused
44,286
4
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
mapping(address => bool) private _defaultOperators;
6,293
192
// GalacticApes Extends ERC721 Non-Fungible Token Standard basic implementation /
contract vagagagga is ERC721Enumerable, Ownable { using Strings for uint256; using Address for address; struct Conf { bool mintEnabled; uint8 perMint; uint16 perAccount; uint16 supply; uint16 maxApes; uint64 price; } address private controller; uint256 public imagesHash; string private defaultURI; string private baseURI; string private metaURI; mapping(uint256 => uint256) private metaHashes; Conf private conf; event updateMetaHash(address, uint256, uint256); modifier isController(address sender) { require( sender != address(0) && (sender == owner() || sender == controller) ); _; } /** * @notice Setup ERC721 and initial config */ constructor( string memory name, string memory symbol, string memory _defaultURI ) ERC721(name, symbol) { conf = Conf(false, 10, 250, 151, 9999, 80000000000000000); defaultURI = _defaultURI; } /** * @notice Mint reserved GalacticApes. * @param accounts Array of accounts to receive reserves. * @param start Index to start minting at. * @dev Utilize unchecked {} and calldata for gas savings. */ function mintReserved(address[] calldata accounts, uint16 start) public onlyOwner { address[] memory _accounts = accounts; unchecked { for (uint8 i = 0; i < _accounts.length; i++) { _safeMint(_accounts[i], start + i); } } } /** * @notice Take eth out of the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @notice Bring new Apes into the world. * @param amount Number of Apes to mint. * @dev Utilize unchecked {} and calldata for gas savings. */ function mint(uint256 amount) public payable { require(conf.mintEnabled, "Minting is disabled."); require( conf.supply + amount < conf.maxApes, "Amount exceeds maximum supply of Test." ); require( balanceOf(msg.sender) + amount <= conf.perAccount, "Amount exceeds current maximum mints per account." ); require( amount <= conf.perMint, "Amount exceeds current maximum Apes per mint." ); require( conf.price * amount <= msg.value, "Ether value sent is not correct." ); uint16 supply = conf.supply; unchecked { for (uint16 i = 0; i < amount; i++) { _safeMint(msg.sender, supply++); } } conf.supply = supply; } /** * @notice Set meta hash for token. * @param id Token id. * @param _hash Hash value. * @dev Only authorized accounts. */ function setMetaHash(uint256 id, uint256 _hash) public isController(msg.sender) { require(_exists(id), "Token does not exist."); metaHashes[id] = _hash; emit updateMetaHash(msg.sender, id, _hash); } /** * @notice Return meta hash for token. */ function getMetaHash(uint256 id) public view returns (uint256) { return metaHashes[id]; } /** * @notice Sets URI for image hashes. */ function setImagesHash(uint256 _imagesHash) public onlyOwner { imagesHash = _imagesHash; } /** * @dev Returns minting state. */ function getMintEnabled() public view returns (bool) { return conf.mintEnabled; } /** * @notice Toggles minting state. */ function toggleMintEnabled() public onlyOwner { conf.mintEnabled = !conf.mintEnabled; } /** * @notice Returns max Apes per mint. */ function getPerMint() public view returns (uint8) { return conf.perMint; } /** * @notice Sets max Apes per mint. */ function setPerMint(uint8 _perMint) public onlyOwner { conf.perMint = _perMint; } /** * @notice Returns max mints per account. */ function getPerAccount() public view returns (uint16) { return conf.perAccount; } /** * @notice Sets max mints per account. */ function setPerAccount(uint16 _perAccount) public onlyOwner { conf.perAccount = _perAccount; } /** * @notice Set base URI. */ function setBaseURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist."); if (bytes(baseURI).length == 0) { return defaultURI; } else { return string(abi.encodePacked(baseURI, (tokenId + 1).toString())); } } }
contract vagagagga is ERC721Enumerable, Ownable { using Strings for uint256; using Address for address; struct Conf { bool mintEnabled; uint8 perMint; uint16 perAccount; uint16 supply; uint16 maxApes; uint64 price; } address private controller; uint256 public imagesHash; string private defaultURI; string private baseURI; string private metaURI; mapping(uint256 => uint256) private metaHashes; Conf private conf; event updateMetaHash(address, uint256, uint256); modifier isController(address sender) { require( sender != address(0) && (sender == owner() || sender == controller) ); _; } /** * @notice Setup ERC721 and initial config */ constructor( string memory name, string memory symbol, string memory _defaultURI ) ERC721(name, symbol) { conf = Conf(false, 10, 250, 151, 9999, 80000000000000000); defaultURI = _defaultURI; } /** * @notice Mint reserved GalacticApes. * @param accounts Array of accounts to receive reserves. * @param start Index to start minting at. * @dev Utilize unchecked {} and calldata for gas savings. */ function mintReserved(address[] calldata accounts, uint16 start) public onlyOwner { address[] memory _accounts = accounts; unchecked { for (uint8 i = 0; i < _accounts.length; i++) { _safeMint(_accounts[i], start + i); } } } /** * @notice Take eth out of the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @notice Bring new Apes into the world. * @param amount Number of Apes to mint. * @dev Utilize unchecked {} and calldata for gas savings. */ function mint(uint256 amount) public payable { require(conf.mintEnabled, "Minting is disabled."); require( conf.supply + amount < conf.maxApes, "Amount exceeds maximum supply of Test." ); require( balanceOf(msg.sender) + amount <= conf.perAccount, "Amount exceeds current maximum mints per account." ); require( amount <= conf.perMint, "Amount exceeds current maximum Apes per mint." ); require( conf.price * amount <= msg.value, "Ether value sent is not correct." ); uint16 supply = conf.supply; unchecked { for (uint16 i = 0; i < amount; i++) { _safeMint(msg.sender, supply++); } } conf.supply = supply; } /** * @notice Set meta hash for token. * @param id Token id. * @param _hash Hash value. * @dev Only authorized accounts. */ function setMetaHash(uint256 id, uint256 _hash) public isController(msg.sender) { require(_exists(id), "Token does not exist."); metaHashes[id] = _hash; emit updateMetaHash(msg.sender, id, _hash); } /** * @notice Return meta hash for token. */ function getMetaHash(uint256 id) public view returns (uint256) { return metaHashes[id]; } /** * @notice Sets URI for image hashes. */ function setImagesHash(uint256 _imagesHash) public onlyOwner { imagesHash = _imagesHash; } /** * @dev Returns minting state. */ function getMintEnabled() public view returns (bool) { return conf.mintEnabled; } /** * @notice Toggles minting state. */ function toggleMintEnabled() public onlyOwner { conf.mintEnabled = !conf.mintEnabled; } /** * @notice Returns max Apes per mint. */ function getPerMint() public view returns (uint8) { return conf.perMint; } /** * @notice Sets max Apes per mint. */ function setPerMint(uint8 _perMint) public onlyOwner { conf.perMint = _perMint; } /** * @notice Returns max mints per account. */ function getPerAccount() public view returns (uint16) { return conf.perAccount; } /** * @notice Sets max mints per account. */ function setPerAccount(uint16 _perAccount) public onlyOwner { conf.perAccount = _perAccount; } /** * @notice Set base URI. */ function setBaseURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist."); if (bytes(baseURI).length == 0) { return defaultURI; } else { return string(abi.encodePacked(baseURI, (tokenId + 1).toString())); } } }
12,128