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
134
// Extra safety measure that allows us to manually unwind one level. In case we somehow get into as state where the cost of unwinding freezes the system. We can manually unwind a few levels
* with this function and then 'rebalance()' with new {borrowRate} and {borrowConfig} values. * @param _borrowRate configurable borrow rate in case it's required to unwind successfully */ function deleverageOnce(uint _borrowRate) external onlyOwner { require(_borrowRate <= BORROW_RATE_MAX, "!safe"); uint256 wantBal = IERC20(want).balanceOf(address(this)); IVToken(vtoken).repayBorrow(wantBal); uint256 borrowBal = IVToken(vtoken).borrowBalanceCurrent(address(this)); uint256 targetUnderlying = borrowBal.mul(100).div(_borrowRate); uint256 balanceOfUnderlying = IVToken(vtoken).balanceOfUnderlying(address(this)); IVToken(vtoken).redeemUnderlying(balanceOfUnderlying.sub(targetUnderlying)); updateBalance(); wantBal = IERC20(want).balanceOf(address(this)); reserves = wantBal; }
* with this function and then 'rebalance()' with new {borrowRate} and {borrowConfig} values. * @param _borrowRate configurable borrow rate in case it's required to unwind successfully */ function deleverageOnce(uint _borrowRate) external onlyOwner { require(_borrowRate <= BORROW_RATE_MAX, "!safe"); uint256 wantBal = IERC20(want).balanceOf(address(this)); IVToken(vtoken).repayBorrow(wantBal); uint256 borrowBal = IVToken(vtoken).borrowBalanceCurrent(address(this)); uint256 targetUnderlying = borrowBal.mul(100).div(_borrowRate); uint256 balanceOfUnderlying = IVToken(vtoken).balanceOfUnderlying(address(this)); IVToken(vtoken).redeemUnderlying(balanceOfUnderlying.sub(targetUnderlying)); updateBalance(); wantBal = IERC20(want).balanceOf(address(this)); reserves = wantBal; }
17,286
1
// The function the owner must call periodically to prove they are alive. /
function checkIn() external { require(msg.sender == owner, "Only the owner can check in."); lastCheckIn = block.timestamp; emit CheckIn(); }
function checkIn() external { require(msg.sender == owner, "Only the owner can check in."); lastCheckIn = block.timestamp; emit CheckIn(); }
22,960
3
// Player start a trade for selling equipment with a certain number of silver coins invitee_address: the address of the player and the equipment wanted to sell as well as the silver number with that. in this function, player can make a trade. /
function invite_trade(address invitee_address, uint256 equipment_id, uint256 silver_number) external;
function invite_trade(address invitee_address, uint256 equipment_id, uint256 silver_number) external;
2,929
1
// Get the expiry time of the option Returns the expiry time of the option in seconds since the Unix epochreturn The expiry time of the option /
function getExpiryTime() external view returns (uint256);
function getExpiryTime() external view returns (uint256);
25,879
0
// ---------------- error code ---------------------- --- UA scope code ---
uint16 public constant CODE_SUCCESS = 0; // success uint16 public constant CODE_PRECRIME_FAILURE = 1; // !!! crimes found
uint16 public constant CODE_SUCCESS = 0; // success uint16 public constant CODE_PRECRIME_FAILURE = 1; // !!! crimes found
18,503
72
// Leave token balance as is.The tokens are unusable if a refund call could be successful due to transferAllowed = false upon failing to reach SOFT_CAP. /
function refund() public { require(refundAllowed); require(!softCapReached); require(weiBalances[msg.sender] > 0); uint256 currentBalance = weiBalances[msg.sender]; weiBalances[msg.sender] = 0; msg.sender.transfer(currentBalance); }
function refund() public { require(refundAllowed); require(!softCapReached); require(weiBalances[msg.sender] > 0); uint256 currentBalance = weiBalances[msg.sender]; weiBalances[msg.sender] = 0; msg.sender.transfer(currentBalance); }
54,335
125
// updates the exchange rate for the contract /
function updateRate(uint256 newExchangeRate) external onlyOwner { require(newExchangeRate <= _maxRate, "ARTMSwapV01: new exchange rate exceeds maximum"); require(newExchangeRate >= _minRate, "ARTMSwapV01: new exchange rate lower than minimum"); _exchangeRate = newExchangeRate; }
function updateRate(uint256 newExchangeRate) external onlyOwner { require(newExchangeRate <= _maxRate, "ARTMSwapV01: new exchange rate exceeds maximum"); require(newExchangeRate >= _minRate, "ARTMSwapV01: new exchange rate lower than minimum"); _exchangeRate = newExchangeRate; }
29,405
197
// A cheaper version of keccak256(toBytes(item)) that avoids copying memory.return keccak256 hash of the item payload. /
function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) { (uint memPtr, uint len) = payloadLocation(item); bytes32 result; assembly { result := keccak256(memPtr, len) } return result; }
function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) { (uint memPtr, uint len) = payloadLocation(item); bytes32 result; assembly { result := keccak256(memPtr, len) } return result; }
7,434
3
// Derived contracts need only register support for their own interfaces, we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
_registerInterface(_INTERFACE_ID_ERC165);
15,986
14
// Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded.
* Emits a {Transfer} event. */ function transfer(address recipient, uint amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint value); }
* Emits a {Transfer} event. */ function transfer(address recipient, uint amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint value); }
1,445
12
// Admin who transfers its role
address private previousAdmin; event FixedCryptoFee(uint256 RubicPart, uint256 integratorPart, address indexed integrator); event FixedCryptoFeeCollected(uint256 amount, address collector); event TokenFee(uint256 RubicPart, uint256 integratorPart, address indexed integrator, address token); event IntegratorTokenFeeCollected(uint256 amount, address indexed integrator, address token); event RubicTokenFeeCollected(uint256 amount, address token); event InitAdminTransfer(address admintShifter, address newAdmin); event AcceptAdmin(address adminShifter, address newAdmin);
address private previousAdmin; event FixedCryptoFee(uint256 RubicPart, uint256 integratorPart, address indexed integrator); event FixedCryptoFeeCollected(uint256 amount, address collector); event TokenFee(uint256 RubicPart, uint256 integratorPart, address indexed integrator, address token); event IntegratorTokenFeeCollected(uint256 amount, address indexed integrator, address token); event RubicTokenFeeCollected(uint256 amount, address token); event InitAdminTransfer(address admintShifter, address newAdmin); event AcceptAdmin(address adminShifter, address newAdmin);
31,183
128
// // Gets the last available user point _addr User addressreturn bias i.e. yreturn slope i.e. linear gradientreturn ts i.e. time point was logged /
function getLastUserPoint(address _addr) external override view returns( int128 bias, int128 slope, uint256 ts )
function getLastUserPoint(address _addr) external override view returns( int128 bias, int128 slope, uint256 ts )
15,785
7
// Store loan inside borrower loans mapping
borrowerLoans[loan.borrower].push(loanId);
borrowerLoans[loan.borrower].push(loanId);
11,302
48
// emit Transfer(fromAddr, toAddr, amount);
Transfer(fromAddr, toAddr, amount); return true;
Transfer(fromAddr, toAddr, amount); return true;
41,045
44
// update mada variable /
uint poolReward = IDefiERC20(address(pool.lpToken)).rewardOf(address(this)); uint pool_total = IDefiERC20(address(pool.lpToken)).balanceOf(address(this)).add(poolReward); uint pool_point_ratio; if(pool_total == 0){ pool_point_ratio = uint(1).mul(1e12); pool.mintedPoint = _amount.mul(1e12).div(pool_point_ratio); }
uint poolReward = IDefiERC20(address(pool.lpToken)).rewardOf(address(this)); uint pool_total = IDefiERC20(address(pool.lpToken)).balanceOf(address(this)).add(poolReward); uint pool_point_ratio; if(pool_total == 0){ pool_point_ratio = uint(1).mul(1e12); pool.mintedPoint = _amount.mul(1e12).div(pool_point_ratio); }
35,283
277
// Transfer the meta lp token to the caller
metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount); return metaLPTokenAmount;
metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount); return metaLPTokenAmount;
81,370
1
// List of all the projects
Project[] private projects;
Project[] private projects;
18,745
56
// Let the network know the user has voted on the dispute and their casted vote
emit Voted(_disputeId, _supportsDispute, msg.sender, voteWeight);
emit Voted(_disputeId, _supportsDispute, msg.sender, voteWeight);
41,665
35
// Copy all consideration array data into memory at tail pointer.
calldatacopy( mPtrTail, add(cdPtrLength, OneWord), mul(arrLength, ConsiderationItem_size) )
calldatacopy( mPtrTail, add(cdPtrLength, OneWord), mul(arrLength, ConsiderationItem_size) )
20,498
164
// total user in each pool
mapping(uint256 => uint256) public Pools;
mapping(uint256 => uint256) public Pools;
17,320
43
// `msg.sender` approves `_spender` to spend `_amount` tokens on/its behalf. This is a modified version of the ERC20 approve function/to be a little bit safer/_spender The address of the account able to transfer the tokens/_amount The amount of tokens to be approved for transfer/ return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; }
function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; }
26,234
117
// Safely mints `quantity` tokens and transfers them to `to`. Requirements: - If `to` refers to a smart contract, it must implement
* {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 quantity, bytes memory _data) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { // Updates: // - `balance += quantity`. // - `numberMinted += quantity`. // // We can directly add to the balance and number minted. _packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1); // Updates: // - `address` to the owner. // - `startTimestamp` to the timestamp of minting. // - `burned` to `false`. // - `nextInitialized` to `quantity == 1`. _packedOwnerships[startTokenId] = _addressToUint256(to) | (block.timestamp << BITPOS_START_TIMESTAMP) | (_boolToUint256(quantity == 1) << BITPOS_NEXT_INITIALIZED); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.code.length != 0) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex < end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex < end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); }
* {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 quantity, bytes memory _data) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { // Updates: // - `balance += quantity`. // - `numberMinted += quantity`. // // We can directly add to the balance and number minted. _packedAddressData[to] += quantity * ((1 << BITPOS_NUMBER_MINTED) | 1); // Updates: // - `address` to the owner. // - `startTimestamp` to the timestamp of minting. // - `burned` to `false`. // - `nextInitialized` to `quantity == 1`. _packedOwnerships[startTokenId] = _addressToUint256(to) | (block.timestamp << BITPOS_START_TIMESTAMP) | (_boolToUint256(quantity == 1) << BITPOS_NEXT_INITIALIZED); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.code.length != 0) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex < end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex < end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); }
27,122
671
// Following the pool share calculation from Alpha Homora: https:github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.solL104
uint256 share = total == 0 ? amount : amount.mul(totalSupply()).div(total); emit Deposit(msg.sender, amount, share); _mint(msg.sender, share);
uint256 share = total == 0 ? amount : amount.mul(totalSupply()).div(total); emit Deposit(msg.sender, amount, share); _mint(msg.sender, share);
39,435
275
// cfx hash
uint256 private constant _DEFI_ROOT_HASH = 0xe23c1845b96c0c4b37fbb545b38cff2fe0449edb1df7e34390454e19d697616b;
uint256 private constant _DEFI_ROOT_HASH = 0xe23c1845b96c0c4b37fbb545b38cff2fe0449edb1df7e34390454e19d697616b;
76,854
56
// ============================================================================== _ __ _ | __ . _.(_(_)| (/_|(_)(_||(_.=====================_|=======================================================
function registerNameCore( uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all
function registerNameCore( uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all
6,634
6
// EIP-712 domain separator
DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPE_HASH, DOMAIN_NAME_HASH, DOMAIN_VERSION_HASH, _getChainID(), address(this), DOMAIN_SALT ) );
DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPE_HASH, DOMAIN_NAME_HASH, DOMAIN_VERSION_HASH, _getChainID(), address(this), DOMAIN_SALT ) );
2,044
25
// Gets current timeZone.
int256 _oldTimeZone = timeZone; require( _timeZone >= -11 hours && _timeZone <= 11 hours && _timeZone != _oldTimeZone, "_setTimeZone: New timeZone Exceeding the setting range or timeZone has been set!" );
int256 _oldTimeZone = timeZone; require( _timeZone >= -11 hours && _timeZone <= 11 hours && _timeZone != _oldTimeZone, "_setTimeZone: New timeZone Exceeding the setting range or timeZone has been set!" );
52,130
229
// It's probably overly-cautious to check rewards on every call, but even when the pool has 1 extra reward token (most have 0) it only adds ~10-15k gas units, so more convenient to always check than to monitor for rewards changes.
addExtraRewards(); IConvexBaseRewardPool(getConvexPool()).getReward();
addExtraRewards(); IConvexBaseRewardPool(getConvexPool()).getReward();
9,508
1
// Calc reserve updates
uint total_frax_mint = getAmountOut(fxs_amount, current_fxs_virtual_reserves, current_collat_virtual_reserves);
uint total_frax_mint = getAmountOut(fxs_amount, current_fxs_virtual_reserves, current_collat_virtual_reserves);
14,546
17
// Map the original token to the wrapped token
originalToWrappedTokens[originalToken] = wrappedToken;
originalToWrappedTokens[originalToken] = wrappedToken;
27,771
25
// Because of https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20.mdtransfer-1
emit Transfer(address(0), owner, amount);
emit Transfer(address(0), owner, amount);
69,065
15
// withdrawAnyTokens Withdraw any tokens from the contract_tokenAddress is a token contract address amount is an amount of tokens /
function withdrawAnyTokens( address _tokenAddress, uint256 amount ) onlyOwner public
function withdrawAnyTokens( address _tokenAddress, uint256 amount ) onlyOwner public
11,540
116
// Update remaning claimable stake for token pools
earningsPool.claimableStake = earningsPool.claimableStake.sub(_stake); return (fees, rewards);
earningsPool.claimableStake = earningsPool.claimableStake.sub(_stake); return (fees, rewards);
24,633
129
// redeem bond for user_recipient address_stake bool return uint /
function redeem( address _recipient, bool _stake ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ), lastBlock: block.number, pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, payout ); } }
function redeem( address _recipient, bool _stake ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ), lastBlock: block.number, pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, payout ); } }
2,202
0
// Emitted when a rule engine is set. /
event RuleEngine(IEIP1404Wrapper indexed newRuleEngine); IEIP1404Wrapper public ruleEngine;
event RuleEngine(IEIP1404Wrapper indexed newRuleEngine); IEIP1404Wrapper public ruleEngine;
29,817
24
// Get the deduction from the rate and the time elapsed
uint256 deduction = currentAuction.priceDeductionRate * timeElapsed;
uint256 deduction = currentAuction.priceDeductionRate * timeElapsed;
7,637
35
// function tokenPlus(address _token, address _user, uint _value) external returns (bool);function tokenMinus(address _token, address _user, uint _value) external returns (bool);
function trustedTokens(address _token) external view returns (bool);
function trustedTokens(address _token) external view returns (bool);
6,699
41
// The address allowed to call calculateRate
address public seedProposer; uint256 internal constant NEGATIVE_RATE_LIMIT = TWENTY_SEVEN_DECIMAL_NUMBER - 1; uint256 internal constant TWENTY_SEVEN_DECIMAL_NUMBER = 10 ** 27; uint256 internal constant EIGHTEEN_DECIMAL_NUMBER = 10 ** 18; constructor( int256 Kp_, int256 Ki_, uint256 perSecondCumulativeLeak_,
address public seedProposer; uint256 internal constant NEGATIVE_RATE_LIMIT = TWENTY_SEVEN_DECIMAL_NUMBER - 1; uint256 internal constant TWENTY_SEVEN_DECIMAL_NUMBER = 10 ** 27; uint256 internal constant EIGHTEEN_DECIMAL_NUMBER = 10 ** 18; constructor( int256 Kp_, int256 Ki_, uint256 perSecondCumulativeLeak_,
5,695
5
// Get minter allowance for an account minter The address of the minter /
function minterAllowance(address minter) external view returns (uint256) { return minterAllowed[minter]; }
function minterAllowance(address minter) external view returns (uint256) { return minterAllowed[minter]; }
26,706
57
// See {_burnPercentage}. /
function burnPercentage() external view returns (uint256) { return _burnPercentage; }
function burnPercentage() external view returns (uint256) { return _burnPercentage; }
74,634
919
// Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken- Only callable by the LendingPool from The address getting liquidated, current owner of the aTokens to The recipient value The amount of tokens getting transferred /
) external override onlyLendingPool { // Being a normal transfer, the Transfer() and BalanceTransfer() are emitted // so no need to emit a specific event here _transfer(from, to, value, false); emit Transfer(from, to, value); }
) external override onlyLendingPool { // Being a normal transfer, the Transfer() and BalanceTransfer() are emitted // so no need to emit a specific event here _transfer(from, to, value, false); emit Transfer(from, to, value); }
15,410
195
// Makes Deposit Possible
function () external payable {} }
function () external payable {} }
29,744
16
// Allow new provider applications _providerAddress The provider's public key address _name The provider's name _details A SHA256 hash of the new providers details _fee The fee charged for customer verification /
function newProvider(address _providerAddress, string _name, bytes32 _details, uint256 _fee) public returns (bool success);
function newProvider(address _providerAddress, string _name, bytes32 _details, uint256 _fee) public returns (bool success);
3,501
9
// Private view function to get the current implementation from theupgrade beacon. This is accomplished via a staticcall to the beacon with nodata, and the beacon will return an abi-encoded implementation address.return implementation Address of the implementation. /
function _implementation() private view returns (address implementation) { // Get the current implementation address from the upgrade beacon. (bool ok, bytes memory returnData) = _UPGRADE_BEACON.staticcall(""); // Revert and pass along revert message if call to upgrade beacon reverts. require(ok, string(returnData)); // Set the implementation to the address returned from the upgrade beacon. implementation = abi.decode(returnData, (address)); }
function _implementation() private view returns (address implementation) { // Get the current implementation address from the upgrade beacon. (bool ok, bytes memory returnData) = _UPGRADE_BEACON.staticcall(""); // Revert and pass along revert message if call to upgrade beacon reverts. require(ok, string(returnData)); // Set the implementation to the address returned from the upgrade beacon. implementation = abi.decode(returnData, (address)); }
50,000
66
// Return true if price has more than doubled, or more than halved.
return percentDeviation > MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND;
return percentDeviation > MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND;
21,113
49
// Set new rewards per block Can only be called by the owner newRewardTokensPerBlock new amount of reward token to reward each block /
function setRewardsPerBlock(uint256 newRewardTokensPerBlock) external onlyOwner { emit ChangedRewardTokensPerBlock(rewardTokensPerBlock, newRewardTokensPerBlock); rewardTokensPerBlock = newRewardTokensPerBlock; _setRewardsEndBlock(); }
function setRewardsPerBlock(uint256 newRewardTokensPerBlock) external onlyOwner { emit ChangedRewardTokensPerBlock(rewardTokensPerBlock, newRewardTokensPerBlock); rewardTokensPerBlock = newRewardTokensPerBlock; _setRewardsEndBlock(); }
10,186
17
// calls to the staking smart contract to retrieve user balance for an epoch
function getEpochStake(address userAddress, uint128 epochId) external view returns (uint) { return _getUserBalancePerEpoch(userAddress, epochId); }
function getEpochStake(address userAddress, uint128 epochId) external view returns (uint) { return _getUserBalancePerEpoch(userAddress, epochId); }
6,540
0
// ckb tx
RawTx, Outputs, OutputsData, RecipientCellOutput, RecipientCellData, Script, RecipientCellTypescriptArgs
RawTx, Outputs, OutputsData, RecipientCellOutput, RecipientCellData, Script, RecipientCellTypescriptArgs
34,147
98
// get total time locked amount of addressaccount The address want to know the time lock amount. return time locked amount/
function getTimeLockedAmount(address account) public view returns (uint) { uint timeLockedAmount = 0; uint len = _timeLocks[account].length; for (uint i = 0; i < len; i++) { if (block.timestamp < _timeLocks[account][i].expiresAt) { timeLockedAmount = timeLockedAmount.add(_timeLocks[account][i].amount); } } return timeLockedAmount; }
function getTimeLockedAmount(address account) public view returns (uint) { uint timeLockedAmount = 0; uint len = _timeLocks[account].length; for (uint i = 0; i < len; i++) { if (block.timestamp < _timeLocks[account][i].expiresAt) { timeLockedAmount = timeLockedAmount.add(_timeLocks[account][i].amount); } } return timeLockedAmount; }
8,138
32
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MerkleDistributor: Invalid proof.');
bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MerkleDistributor: Invalid proof.');
5,357
135
// Skip dial if no votes, disabled or was over cap
if (dialVotes[l] == 0) { continue; }
if (dialVotes[l] == 0) { continue; }
35,965
13
// Address of the Koans founder's wallet.
address public koansFoundersAddress;
address public koansFoundersAddress;
2,799
33
// This function add an address in the `ADMIN_ROLE`. Only owner can call it. Can not be called if the Bridge is paused. Parameters: address of admin to be added Returns: bool - true if it is sucessful/
function addAdmin(address account) external onlyOwner whenNotPaused returns (bool)
function addAdmin(address account) external onlyOwner whenNotPaused returns (bool)
50,093
47
// executes the ERC20 token's `transfer` function and reverts upon failure the main purpose of this function is to prevent a non standard ERC20 token from failing silently_token ERC20 token address_totarget address_value transfer amount/
function safeTransfer(IERC20Token _token, address _to, uint256 _value) public { execute(_token, abi.encodeWithSelector(TRANSFER_FUNC_SELECTOR, _to, _value)); }
function safeTransfer(IERC20Token _token, address _to, uint256 _value) public { execute(_token, abi.encodeWithSelector(TRANSFER_FUNC_SELECTOR, _to, _value)); }
40,949
233
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
1,703
45
// Function to buy token
function buyTokens() public payable isOpen { uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(10**18).div(tokenPrice); require(Rick.balanceOf(address(this)) >= tokens, "Insufficient token balance"); tokensSold = tokensSold.add(tokens); purchasedTokens[msg.sender] = purchasedTokens[msg.sender].add(tokens); emit TokenPurchase(msg.sender, weiAmount, tokens); }
function buyTokens() public payable isOpen { uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(10**18).div(tokenPrice); require(Rick.balanceOf(address(this)) >= tokens, "Insufficient token balance"); tokensSold = tokensSold.add(tokens); purchasedTokens[msg.sender] = purchasedTokens[msg.sender].add(tokens); emit TokenPurchase(msg.sender, weiAmount, tokens); }
766
21
// Oracle address
AggregatorInterface public usdOracle; event OracleChanged(address oracle); event RentPriceChanged(uint prices);
AggregatorInterface public usdOracle; event OracleChanged(address oracle); event RentPriceChanged(uint prices);
39,343
67
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _burn(account, amount);
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _burn(account, amount);
2,221
181
// By calling this function, you agreed that you have read and accepted the terms & conditions available at this link: https:hungerbrainz.com/terms
require(tokenType < 2,"Invalid type"); require(tokenId_.current() <= SUP_THRESHOLD,"Buy using SUP"); if(isPresale){ require(msg.sender == address(whitelist),"Not whitelisted"); require(userPurchase[receiver] + tokenAmount <= 3,"Purchase limit"); }
require(tokenType < 2,"Invalid type"); require(tokenId_.current() <= SUP_THRESHOLD,"Buy using SUP"); if(isPresale){ require(msg.sender == address(whitelist),"Not whitelisted"); require(userPurchase[receiver] + tokenAmount <= 3,"Purchase limit"); }
53,643
292
// gets address of all admins /
function getAdmins() external view returns (address[] memory);
function getAdmins() external view returns (address[] memory);
37,045
21
// This modifier limits access to only related wallets, owner of the contract to execute functions /
modifier onlyAuthorizedUsers() { bool found = false; // Check in relatedWallets if (relatedWallets[msg.sender] == true) { found = true; } // If not found in relatedWallets, check in member if (!found) { if (msg.sender == member) { found = true; } } // If not found in either, revert the transaction if (!found) { revert UserNotAuthorized(); } _; }
modifier onlyAuthorizedUsers() { bool found = false; // Check in relatedWallets if (relatedWallets[msg.sender] == true) { found = true; } // If not found in relatedWallets, check in member if (!found) { if (msg.sender == member) { found = true; } } // If not found in either, revert the transaction if (!found) { revert UserNotAuthorized(); } _; }
16,319
32
// Called when an address wants to submit a bid to the sale/self Stored crowdsale from crowdsale contract/ return currentBonus percentage of the bonus that is applied for the purchase
function getCurrentBonus(InteractiveCrowdsaleStorage storage self) internal view returns (uint256){ // can't underflow becuase endWithdrawalTime > startTime uint256 bonusTime = self.endWithdrawalTime - self.base.startTime; // can't underflow because now > startTime uint256 elapsed = now - self.base.startTime; uint256 percentElapsed = (elapsed * 100)/bonusTime; bool err; uint256 currentBonus; (err,currentBonus) = self.priceBonusPercent.minus(((percentElapsed * self.priceBonusPercent)/100)); require(!err); return currentBonus; }
function getCurrentBonus(InteractiveCrowdsaleStorage storage self) internal view returns (uint256){ // can't underflow becuase endWithdrawalTime > startTime uint256 bonusTime = self.endWithdrawalTime - self.base.startTime; // can't underflow because now > startTime uint256 elapsed = now - self.base.startTime; uint256 percentElapsed = (elapsed * 100)/bonusTime; bool err; uint256 currentBonus; (err,currentBonus) = self.priceBonusPercent.minus(((percentElapsed * self.priceBonusPercent)/100)); require(!err); return currentBonus; }
13,316
68
// Contract constructor _token address token that will be stored in the pool _cap uint256 predefined cap of the pool /
constructor(address _token, uint256 _cap) public { token = ERC20Basic(_token); cap = _cap; totalAllocated = 0; }
constructor(address _token, uint256 _cap) public { token = ERC20Basic(_token); cap = _cap; totalAllocated = 0; }
37,273
59
// Tell the current term identification number. Note that there may be pending term transitions. return Identification number of the current term/
function getCurrentTermId() external view returns (uint64);
function getCurrentTermId() external view returns (uint64);
10,386
3
// Level libraryFunctions to swap tokens on Level protocol
library Level { using SafeERC20 for IERC20; function swap( address from, uint256 amountIn, IWowmaxRouter.Swap memory swapData ) internal returns (uint256 amountOut) { IERC20(from).safeTransfer(swapData.addr, amountIn); uint256 balanceBefore = IERC20(swapData.to).balanceOf(address(this)); ILevelPool(swapData.addr).swap(from, swapData.to, 0, address(this), new bytes(0)); amountOut = IERC20(swapData.to).balanceOf(address(this)) - balanceBefore; } }
library Level { using SafeERC20 for IERC20; function swap( address from, uint256 amountIn, IWowmaxRouter.Swap memory swapData ) internal returns (uint256 amountOut) { IERC20(from).safeTransfer(swapData.addr, amountIn); uint256 balanceBefore = IERC20(swapData.to).balanceOf(address(this)); ILevelPool(swapData.addr).swap(from, swapData.to, 0, address(this), new bytes(0)); amountOut = IERC20(swapData.to).balanceOf(address(this)) - balanceBefore; } }
45,633
62
// Transfers the deed to the current registrar, if different from this one. Used during the upgrade process to a permanent registrar._hash The name hash to transfer. /
function transferRegistrars(bytes32 _hash) external onlyOwner(_hash) { address registrar = ens.owner(rootNode); require(registrar != address(this)); // Migrate the deed Entry storage h = _entries[_hash]; h.deed.setRegistrar(registrar); // Call the new registrar to accept the transfer Registrar(registrar).acceptRegistrarTransfer(_hash, h.deed, h.registrationDate); // Zero out the Entry h.deed = Deed(0); h.registrationDate = 0; h.value = 0; h.highestBid = 0; }
function transferRegistrars(bytes32 _hash) external onlyOwner(_hash) { address registrar = ens.owner(rootNode); require(registrar != address(this)); // Migrate the deed Entry storage h = _entries[_hash]; h.deed.setRegistrar(registrar); // Call the new registrar to accept the transfer Registrar(registrar).acceptRegistrarTransfer(_hash, h.deed, h.registrationDate); // Zero out the Entry h.deed = Deed(0); h.registrationDate = 0; h.value = 0; h.highestBid = 0; }
39,065
55
// Executes a percentage division value The value of which the percentage needs to be calculated percentage The percentage of the value to be calculatedreturn The value divided the percentage /
function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; }
function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; }
17,179
189
// Counters Matt Condon (@shrugs) Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the numberof elements in a mapping, issuing ERC721 ids, or counting request ids Include with `using Counters for Counters.Counter;`Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMathoverflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is neverdirectly accessed. /
library Counters { using SafeMath for uint256; struct Counter { // 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 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } }
library Counters { using SafeMath for uint256; struct Counter { // 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 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } }
6,464
100
// The address of the user that is wrapping / unwrapping tokens. This will not be persisted, to reduce gas usage.
address _depositor;
address _depositor;
65,724
78
// Update token info _newName The new name _newSymbol The new symbol _newDecimals The new decimals /
function updateTokenInfo( string calldata _newName, string calldata _newSymbol, uint8 _newDecimals
function updateTokenInfo( string calldata _newName, string calldata _newSymbol, uint8 _newDecimals
7,925
111
// Closes the vault, terminates the contract and the token contract as well.Only allowed while the vault is open (not when refunds are enabled or the vaultis already closed). Balance would be transferred to _recipient, but it isalways zero anyway. /
function destroyAndSend(address _recipient) public onlyOwner { vault.close(); super.destroyAndSend(_recipient); DemeterToken(token).destroyAndSend(_recipient); }
function destroyAndSend(address _recipient) public onlyOwner { vault.close(); super.destroyAndSend(_recipient); DemeterToken(token).destroyAndSend(_recipient); }
25,774
8
// The timestamps when each handle is claimable. A value of 0 means a handle isn't being challenged.
mapping(bytes32 => uint256) public override challengeExpiryOf;
mapping(bytes32 => uint256) public override challengeExpiryOf;
24,746
12
// add a and b and then subtract c /
function addThenSub( uint256 a, uint256 b, uint256 c
function addThenSub( uint256 a, uint256 b, uint256 c
17,754
44
// Declare an investment for an address /
function invest(address _investor, uint256 _amount) public onlyOwner { // make sure the investor is not an empty address require(_investor != address(0), "Investor is empty"); // make sure the amount is not zero require(_amount != 0, "Amount is zero"); // do not sell if sale is finished require(!bFinished, "Sale is finished"); // do not sell if not initialized require(bInitialized, "Sale is not initialized"); // process input data // call with same arguments brlToken.invest(_investor, _amount); // add the amount to the total nTotalCollected = nTotalCollected.add(_amount); // convert input currency to output // - get rate from module uint256 nRate = getRate(); // - total amount from the rate obtained uint256 nOutputAmount = _amount.div(nRate); // pass to module to handling outputs // get the current contract's balance uint256 nBalance = baseToken.balanceOf(address(this)); // calculate how many tokens we can sell uint256 nRemainingBalance = nBalance.sub(nTotalSold); // make sure we're not selling more than we have require( nOutputAmount <= nRemainingBalance, "Offer does not have enough tokens to sell" ); // read the payment data from our map Payment storage payment = mapPayments[_investor]; // increase the amount of tokens this investor has purchased payment.totalAmount = payment.totalAmount.add(nOutputAmount); // after everything, add the bought tokens to the total nTotalSold = nTotalSold.add(nOutputAmount); // and check if the sale is sucessful after this sale if (!bSuccess) { if (nTotalSold >= MIN_TOTAL_TOKEN_SOLD) { // we have sold more than minimum, success bSuccess = true; } } }
function invest(address _investor, uint256 _amount) public onlyOwner { // make sure the investor is not an empty address require(_investor != address(0), "Investor is empty"); // make sure the amount is not zero require(_amount != 0, "Amount is zero"); // do not sell if sale is finished require(!bFinished, "Sale is finished"); // do not sell if not initialized require(bInitialized, "Sale is not initialized"); // process input data // call with same arguments brlToken.invest(_investor, _amount); // add the amount to the total nTotalCollected = nTotalCollected.add(_amount); // convert input currency to output // - get rate from module uint256 nRate = getRate(); // - total amount from the rate obtained uint256 nOutputAmount = _amount.div(nRate); // pass to module to handling outputs // get the current contract's balance uint256 nBalance = baseToken.balanceOf(address(this)); // calculate how many tokens we can sell uint256 nRemainingBalance = nBalance.sub(nTotalSold); // make sure we're not selling more than we have require( nOutputAmount <= nRemainingBalance, "Offer does not have enough tokens to sell" ); // read the payment data from our map Payment storage payment = mapPayments[_investor]; // increase the amount of tokens this investor has purchased payment.totalAmount = payment.totalAmount.add(nOutputAmount); // after everything, add the bought tokens to the total nTotalSold = nTotalSold.add(nOutputAmount); // and check if the sale is sucessful after this sale if (!bSuccess) { if (nTotalSold >= MIN_TOTAL_TOKEN_SOLD) { // we have sold more than minimum, success bSuccess = true; } } }
21,209
1
// Limit withdrawal amount
require(withdraw_amount <= 100000000000000000);
require(withdraw_amount <= 100000000000000000);
4,244
28
// return total number of store fronts /
function getStoreFrontCount() public view returns (uint) { return storeCount; }
function getStoreFrontCount() public view returns (uint) { return storeCount; }
13,007
234
// Get index of the most significant non-zero bit in binary representation ofx.Reverts if x is zero. return index of the most significant non-zero bit in binary representationof x /
function msb (uint256 x) private pure returns (uint256) { require (x > 0); uint256 result = 0; if (x >= 0x100000000000000000000000000000000) { x >>= 128; result += 128; } if (x >= 0x10000000000000000) { x >>= 64; result += 64; } if (x >= 0x100000000) { x >>= 32; result += 32; } if (x >= 0x10000) { x >>= 16; result += 16; } if (x >= 0x100) { x >>= 8; result += 8; } if (x >= 0x10) { x >>= 4; result += 4; } if (x >= 0x4) { x >>= 2; result += 2; } if (x >= 0x2) result += 1; // No need to shift x anymore return result; }
function msb (uint256 x) private pure returns (uint256) { require (x > 0); uint256 result = 0; if (x >= 0x100000000000000000000000000000000) { x >>= 128; result += 128; } if (x >= 0x10000000000000000) { x >>= 64; result += 64; } if (x >= 0x100000000) { x >>= 32; result += 32; } if (x >= 0x10000) { x >>= 16; result += 16; } if (x >= 0x100) { x >>= 8; result += 8; } if (x >= 0x10) { x >>= 4; result += 4; } if (x >= 0x4) { x >>= 2; result += 2; } if (x >= 0x2) result += 1; // No need to shift x anymore return result; }
42,220
7
// SeizableBridgeERC20 SeizableBridgeERC20 contract Error messagesSE02: Caller is not seizer/
contract SeizableBridgeERC20 is Initializable, ISeizable, BridgeERC20 { using Roles for Roles.Role; Roles.Role internal _seizers; function initialize( address owner, IProcessor processor ) public override initializer { BridgeERC20.initialize(owner, processor); } modifier onlySeizer() { require(isSeizer(_msgSender()), "SE02"); _; } function isSeizer(address _seizer) public override view returns (bool) { return _seizers.has(_seizer); } function addSeizer(address _seizer) public override onlyAdministrator { _seizers.add(_seizer); emit SeizerAdded(_seizer); } function removeSeizer(address _seizer) public override onlyAdministrator { _seizers.remove(_seizer); emit SeizerRemoved(_seizer); } /** * @dev called by the owner to seize value from the account */ function seize(address _account, uint256 _value) public override onlySeizer hasProcessor { _processor.seize(_msgSender(), _account, _value); emit Seize(_account, _value); emit Transfer(_account, _msgSender(), _value); } /* Reserved slots for future use: https://docs.openzeppelin.com/sdk/2.5/writing-contracts.html#modifying-your-contracts */ uint256[49] private ______gap; }
contract SeizableBridgeERC20 is Initializable, ISeizable, BridgeERC20 { using Roles for Roles.Role; Roles.Role internal _seizers; function initialize( address owner, IProcessor processor ) public override initializer { BridgeERC20.initialize(owner, processor); } modifier onlySeizer() { require(isSeizer(_msgSender()), "SE02"); _; } function isSeizer(address _seizer) public override view returns (bool) { return _seizers.has(_seizer); } function addSeizer(address _seizer) public override onlyAdministrator { _seizers.add(_seizer); emit SeizerAdded(_seizer); } function removeSeizer(address _seizer) public override onlyAdministrator { _seizers.remove(_seizer); emit SeizerRemoved(_seizer); } /** * @dev called by the owner to seize value from the account */ function seize(address _account, uint256 _value) public override onlySeizer hasProcessor { _processor.seize(_msgSender(), _account, _value); emit Seize(_account, _value); emit Transfer(_account, _msgSender(), _value); } /* Reserved slots for future use: https://docs.openzeppelin.com/sdk/2.5/writing-contracts.html#modifying-your-contracts */ uint256[49] private ______gap; }
29,549
130
// gives square root of given x.
function sqrt(uint256 x) internal pure returns (uint256 y)
function sqrt(uint256 x) internal pure returns (uint256 y)
19,019
122
// if we did find a nearby active offer Walk the order book down from there...
if(_isPricedLtOrEq(id, pos)) { uint old_pos;
if(_isPricedLtOrEq(id, pos)) { uint old_pos;
39,552
54
// Gets the next available sequence ID for signing when using executeAndConfirmreturns the sequenceId one higher than the highest currently stored /
function getNextSequenceId() public view returns (uint) { uint highestSequenceId = 0; for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) { if (recentSequenceIds[i] > highestSequenceId) { highestSequenceId = recentSequenceIds[i]; } } return highestSequenceId + 1; }
function getNextSequenceId() public view returns (uint) { uint highestSequenceId = 0; for (uint i = 0; i < SEQUENCE_ID_WINDOW_SIZE; i++) { if (recentSequenceIds[i] > highestSequenceId) { highestSequenceId = recentSequenceIds[i]; } } return highestSequenceId + 1; }
19,557
18
// get current powerlevel for tokenid
function powerLevelByIndex(uint256 tokenId) public view returns (uint256) { return _tokenPowerLevel[tokenId]; }
function powerLevelByIndex(uint256 tokenId) public view returns (uint256) { return _tokenPowerLevel[tokenId]; }
2,423
10
// Price of parent should be bigger than item, other - swap
max = parent;
max = parent;
21,176
16
// Verify msgChallengesigningPubKey + signaturegenerator ==noncegenerator https:ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 The point corresponding to the address returned by ecrecover(-sr,v,r,er) is (r⁻¹ mod Q)(erR-(-s)rg)=eR+sg, where R is the (v,r) point. See https:crypto.stackexchange.com/a/18106 solium-disable-next-line indentation
address recoveredAddress = ecrecover(
address recoveredAddress = ecrecover(
44,894
8
// Emitted when the governor's voting delay is updated
event VotingDelayUpdated(uint256 prevVotingDelay, uint256 newVotingDelay);
event VotingDelayUpdated(uint256 prevVotingDelay, uint256 newVotingDelay);
32,274
72
// Test whether an identifier is valid./identifier The identifier to test.
function validIdentifier(uint256 identifier) public pure returns(bool) { return identifier < 4294967296; // 2^16 * 2^16 }
function validIdentifier(uint256 identifier) public pure returns(bool) { return identifier < 4294967296; // 2^16 * 2^16 }
29,408
158
// Subtract the earliest update
if (updates >= granularity) { ( , ConverterFeedObservation storage firstConverterFeedObservation ) = getFirstObservationsInWindow(); converterPriceCumulative = subtract(converterPriceCumulative, firstConverterFeedObservation.timeAdjustedPrice); }
if (updates >= granularity) { ( , ConverterFeedObservation storage firstConverterFeedObservation ) = getFirstObservationsInWindow(); converterPriceCumulative = subtract(converterPriceCumulative, firstConverterFeedObservation.timeAdjustedPrice); }
49,683
30
// Creates a new MISOMarket using _templateId. Initializes auction with the parameters passed. _templateId Id of the auction template to create. _token The token address to be sold. _tokenSupply Amount of tokens to be sold at market. _integratorFeeAccount Address to send refferal bonus, if set. _data Data to be sent to template on Init.return newMarket Market address. /
function createMarket( uint256 _templateId, address _token, uint256 _tokenSupply, address payable _integratorFeeAccount, bytes calldata _data ) external payable returns (address newMarket)
function createMarket( uint256 _templateId, address _token, uint256 _tokenSupply, address payable _integratorFeeAccount, bytes calldata _data ) external payable returns (address newMarket)
21,575
96
// ERC20 Token Standard, optional extension: Safe TransfersNote: the ERC-165 identifier for this interface is 0x53f41a97. /
interface IERC20SafeTransfers { /** * Transfers tokens from the caller to `to`. If this address is a contract, then calls `onERC20Received(address,address,uint256,bytes)` on it. * @dev Reverts if `to` is the zero address. * @dev Reverts if `value` is greater than the sender's balance. * @dev Reverts if `to` is a contract which does not implement `onERC20Received(address,address,uint256,bytes)`. * @dev Reverts if `to` is a contract and the call to `onERC20Received(address,address,uint256,bytes)` returns a wrong value. * @dev Emits an {IERC20-Transfer} event. * @param to The address for the tokens to be transferred to. * @param amount The amount of tokens to be transferred. * @param data Optional additional data with no specified format, to be passed to the receiver contract. * @return true. */ function safeTransfer( address to, uint256 amount, bytes calldata data ) external returns (bool); /** * Transfers tokens from `from` to another address, using the allowance mechanism. * If this address is a contract, then calls `onERC20Received(address,address,uint256,bytes)` on it. * @dev Reverts if `to` is the zero address. * @dev Reverts if `value` is greater than `from`'s balance. * @dev Reverts if the sender does not have at least `value` allowance by `from`. * @dev Reverts if `to` is a contract which does not implement `onERC20Received(address,address,uint256,bytes)`. * @dev Reverts if `to` is a contract and the call to `onERC20Received(address,address,uint256,bytes)` returns a wrong value. * @dev Emits an {IERC20-Transfer} event. * @param from The address which owns the tokens to be transferred. * @param to The address for the tokens to be transferred to. * @param amount The amount of tokens to be transferred. * @param data Optional additional data with no specified format, to be passed to the receiver contract. * @return true. */ function safeTransferFrom( address from, address to, uint256 amount, bytes calldata data ) external returns (bool); }
interface IERC20SafeTransfers { /** * Transfers tokens from the caller to `to`. If this address is a contract, then calls `onERC20Received(address,address,uint256,bytes)` on it. * @dev Reverts if `to` is the zero address. * @dev Reverts if `value` is greater than the sender's balance. * @dev Reverts if `to` is a contract which does not implement `onERC20Received(address,address,uint256,bytes)`. * @dev Reverts if `to` is a contract and the call to `onERC20Received(address,address,uint256,bytes)` returns a wrong value. * @dev Emits an {IERC20-Transfer} event. * @param to The address for the tokens to be transferred to. * @param amount The amount of tokens to be transferred. * @param data Optional additional data with no specified format, to be passed to the receiver contract. * @return true. */ function safeTransfer( address to, uint256 amount, bytes calldata data ) external returns (bool); /** * Transfers tokens from `from` to another address, using the allowance mechanism. * If this address is a contract, then calls `onERC20Received(address,address,uint256,bytes)` on it. * @dev Reverts if `to` is the zero address. * @dev Reverts if `value` is greater than `from`'s balance. * @dev Reverts if the sender does not have at least `value` allowance by `from`. * @dev Reverts if `to` is a contract which does not implement `onERC20Received(address,address,uint256,bytes)`. * @dev Reverts if `to` is a contract and the call to `onERC20Received(address,address,uint256,bytes)` returns a wrong value. * @dev Emits an {IERC20-Transfer} event. * @param from The address which owns the tokens to be transferred. * @param to The address for the tokens to be transferred to. * @param amount The amount of tokens to be transferred. * @param data Optional additional data with no specified format, to be passed to the receiver contract. * @return true. */ function safeTransferFrom( address from, address to, uint256 amount, bytes calldata data ) external returns (bool); }
54,554
15
// Gives permission to `to` to transfer `tokenId` token to another account.The approval is cleared when the token is transferred. Only a single account can be approved at a time, so approving the zero address clears previous approvals. Requirements: - The caller must own the token or be an approved operator.- `tokenId` must exist. Emits an {Approval} event. /
function approve(address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
777
257
// the address of the FEI contract/ return fei contract
function fei() external view returns (IFei);
function fei() external view returns (IFei);
39,590
3
// minimum insurance cost in usdt
uint256 public minimumInsuranceCost;
uint256 public minimumInsuranceCost;
13,756
4
// When minting tokens
require( totalSupply().add(amount) <= cap(), "ERC20Capped: cap exceeded" );
require( totalSupply().add(amount) <= cap(), "ERC20Capped: cap exceeded" );
48,684
61
// uint256 tradeValue = address(this).balance - contractEthBalance;new balance less the old balance
/*uint256 gasAfter = gasleft();//gas uint256 gasUsed = gasBefore - gasAfter; uint256 gasRefund = gasUsed * tx.gasprice; //10% extra to cover eth transfer to seller uint256 extraFee = gasRefund * 1/10; uint256 userProceeds = tradeValue - gasRefund - extraFee;
/*uint256 gasAfter = gasleft();//gas uint256 gasUsed = gasBefore - gasAfter; uint256 gasRefund = gasUsed * tx.gasprice; //10% extra to cover eth transfer to seller uint256 extraFee = gasRefund * 1/10; uint256 userProceeds = tradeValue - gasRefund - extraFee;
8,497
215
// decreaseApproval overrride
function decreaseApproval( address _spender, uint _subtractedValue ) public
function decreaseApproval( address _spender, uint _subtractedValue ) public
45,195
49
// Returns if the token is mintable or not /
function mintable() public override view returns (bool) { return isMintable; }
function mintable() public override view returns (bool) { return isMintable; }
49,122
264
// Math: FAIR blocks initReserve from being burned unless we reach the RUN state which prevents an underflow
currencyValue /= totalSupply() - stakeholdersPoolIssued - shareholdersPool; return currencyValue;
currencyValue /= totalSupply() - stakeholdersPoolIssued - shareholdersPool; return currencyValue;
4,117
34
// this is the fourth and the final of the settlement functions
function settleFinal() external onlyAdmin
function settleFinal() external onlyAdmin
47,087
50
// UNSRegistry v0.2additional functions so other trusted contracts to interact with the tokens. /
contract UNSRegistry is ERC721Upgradeable, ERC2771RegistryContext, RecordStorage, UNSRegistryForwarder, IUNSRegistry { /** * @dev ERC-1967: Emitted when the implementation is upgraded. Required for ABI decoding only. */ event Upgraded(address indexed implementation); /** * @dev ERC-1967: Emitted when the admin account has changed. Required for ABI decoding only. */ event AdminChanged(address previousAdmin, address newAdmin); string public constant NAME = 'UNS: Registry'; string public constant VERSION = '0.2.0'; string internal _prefix; address internal _mintingManager; modifier onlyApprovedOrOwner(uint256 tokenId) { require(_isApprovedOrOwner(_msgSender(), tokenId), 'Registry: SENDER_IS_NOT_APPROVED_OR_OWNER'); _; } modifier onlyMintingManager() { require(_msgSender() == _mintingManager, 'Registry: SENDER_IS_NOT_MINTING_MANAGER'); _; } modifier protectTokenOperation(uint256 tokenId) { if (isTrustedForwarder(msg.sender)) { require(tokenId == _msgToken(), 'Registry: TOKEN_INVALID'); } else { _invalidateNonce(tokenId); } _; } function initialize(address mintingManager) public initializer { _mintingManager = mintingManager; __ERC721_init_unchained('Unstoppable Domains', 'UD'); __ERC2771RegistryContext_init_unchained(); __UNSRegistryForwarder_init_unchained(); } /// ERC721 Metadata extension function setTokenURIPrefix(string calldata prefix) external override onlyMintingManager { _prefix = prefix; emit NewURIPrefix(prefix); } /// Ownership function isApprovedOrOwner(address spender, uint256 tokenId) external view override returns (bool) { return _isApprovedOrOwner(spender, tokenId); } function approve(address to, uint256 tokenId) public override(IERC721Upgradeable, ERC721Upgradeable) protectTokenOperation(tokenId) { super.approve(to, tokenId); } /// Registry Constants function root() public pure returns (uint256) { return 0; } function childIdOf(uint256 tokenId, string calldata label) external pure override returns (uint256) { return _childId(tokenId, label); } function exists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } /// Minting function mint( address to, uint256 tokenId, string calldata uri ) external override onlyMintingManager { _mint(to, tokenId, uri); } function safeMint( address to, uint256 tokenId, string calldata uri ) external override onlyMintingManager { _safeMint(to, tokenId, uri, ''); } function safeMint( address to, uint256 tokenId, string calldata uri, bytes calldata data ) external override onlyMintingManager { _safeMint(to, tokenId, uri, data); } function mintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values ) external override onlyMintingManager { _mint(to, tokenId, uri); _setMany(keys, values, tokenId); } function safeMintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values ) external override onlyMintingManager { _safeMintWithRecords(to, tokenId, uri, keys, values, ''); } function safeMintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values, bytes calldata data ) external override onlyMintingManager { _safeMintWithRecords(to, tokenId, uri, keys, values, data); } /// Transfering function setOwner(address to, uint256 tokenId) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _transfer(ownerOf(tokenId), to, tokenId); } function transferFrom( address from, address to, uint256 tokenId ) public override(IERC721Upgradeable, ERC721Upgradeable) onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reset(tokenId); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public override(IERC721Upgradeable, ERC721Upgradeable) onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reset(tokenId); _safeTransfer(from, to, tokenId, data); } /// Burning function burn(uint256 tokenId) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reset(tokenId); _burn(tokenId); } /// Resolution function resolverOf(uint256 tokenId) external view override returns (address) { return _exists(tokenId) ? address(this) : address(0x0); } function set( string calldata key, string calldata value, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _set(key, value, tokenId); } function setMany( string[] calldata keys, string[] calldata values, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _setMany(keys, values, tokenId); } function setByHash( uint256 keyHash, string calldata value, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _setByHash(keyHash, value, tokenId); } function setManyByHash( uint256[] calldata keyHashes, string[] calldata values, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _setManyByHash(keyHashes, values, tokenId); } function reconfigure( string[] calldata keys, string[] calldata values, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reconfigure(keys, values, tokenId); } function reset(uint256 tokenId) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reset(tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) { return super.supportsInterface(interfaceId); } // TODO: guard the function by owner check // This is the keccak-256 hash of "uns.polygon.root_chain_manager" subtracted by 1 bytes32 internal constant _ROOT_CHAIN_MANAGER_SLOT = 0xbe2bb46ac0377341a1ec5c3116d70fd5029d704bd46292e58f6265dd177ebafe; function setRootChainManager(address rootChainManager) public { require( StorageSlotUpgradeable.getAddressSlot(_ROOT_CHAIN_MANAGER_SLOT).value == address(0), 'Registry: ROOT_CHAIN_MANEGER_NOT_EMPTY' ); StorageSlotUpgradeable.getAddressSlot(_ROOT_CHAIN_MANAGER_SLOT).value = rootChainManager; } function depositToPolygon(uint256 tokenId) public onlyApprovedOrOwner(tokenId) { address manager = StorageSlotUpgradeable.getAddressSlot(_ROOT_CHAIN_MANAGER_SLOT).value; bytes32 tokenType = RootChainManagerStorage(manager).tokenToType(address(this)); address predicate = RootChainManagerStorage(manager).typeToPredicate(tokenType); // A workaround for MintableERC721Predicate // that requires a depositor to be equal to token owner: // https://github.com/maticnetwork/pos-portal/blob/88dbf0a88fd68fa11f7a3b9d36629930f6b93a05/contracts/root/TokenPredicates/MintableERC721Predicate.sol#L94 _transfer(_msgSender(), address(this), tokenId); _approve(predicate, tokenId); IRootChainManager(manager).depositFor(_msgSender(), address(this), abi.encode(tokenId)); } /// Internal function _childId(uint256 tokenId, string memory label) internal pure returns (uint256) { require(bytes(label).length != 0, 'Registry: LABEL_EMPTY'); return uint256(keccak256(abi.encodePacked(tokenId, keccak256(abi.encodePacked(label))))); } function _mint( address to, uint256 tokenId, string memory uri ) internal { _mint(to, tokenId); emit NewURI(tokenId, uri); } function _safeMint( address to, uint256 tokenId, string memory uri, bytes memory data ) internal { _safeMint(to, tokenId, data); emit NewURI(tokenId, uri); } function _safeMintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values, bytes memory data ) internal { _safeMint(to, tokenId, uri, data); _setMany(keys, values, tokenId); } function _baseURI() internal view override(ERC721Upgradeable) returns (string memory) { return _prefix; } function _msgSender() internal view override(ContextUpgradeable, ERC2771RegistryContext) returns (address) { return super._msgSender(); } function _msgData() internal view override(ContextUpgradeable, ERC2771RegistryContext) returns (bytes calldata) { return super._msgData(); } // Reserved storage space to allow for layout changes in the future. uint256[50] private __gap; }
contract UNSRegistry is ERC721Upgradeable, ERC2771RegistryContext, RecordStorage, UNSRegistryForwarder, IUNSRegistry { /** * @dev ERC-1967: Emitted when the implementation is upgraded. Required for ABI decoding only. */ event Upgraded(address indexed implementation); /** * @dev ERC-1967: Emitted when the admin account has changed. Required for ABI decoding only. */ event AdminChanged(address previousAdmin, address newAdmin); string public constant NAME = 'UNS: Registry'; string public constant VERSION = '0.2.0'; string internal _prefix; address internal _mintingManager; modifier onlyApprovedOrOwner(uint256 tokenId) { require(_isApprovedOrOwner(_msgSender(), tokenId), 'Registry: SENDER_IS_NOT_APPROVED_OR_OWNER'); _; } modifier onlyMintingManager() { require(_msgSender() == _mintingManager, 'Registry: SENDER_IS_NOT_MINTING_MANAGER'); _; } modifier protectTokenOperation(uint256 tokenId) { if (isTrustedForwarder(msg.sender)) { require(tokenId == _msgToken(), 'Registry: TOKEN_INVALID'); } else { _invalidateNonce(tokenId); } _; } function initialize(address mintingManager) public initializer { _mintingManager = mintingManager; __ERC721_init_unchained('Unstoppable Domains', 'UD'); __ERC2771RegistryContext_init_unchained(); __UNSRegistryForwarder_init_unchained(); } /// ERC721 Metadata extension function setTokenURIPrefix(string calldata prefix) external override onlyMintingManager { _prefix = prefix; emit NewURIPrefix(prefix); } /// Ownership function isApprovedOrOwner(address spender, uint256 tokenId) external view override returns (bool) { return _isApprovedOrOwner(spender, tokenId); } function approve(address to, uint256 tokenId) public override(IERC721Upgradeable, ERC721Upgradeable) protectTokenOperation(tokenId) { super.approve(to, tokenId); } /// Registry Constants function root() public pure returns (uint256) { return 0; } function childIdOf(uint256 tokenId, string calldata label) external pure override returns (uint256) { return _childId(tokenId, label); } function exists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } /// Minting function mint( address to, uint256 tokenId, string calldata uri ) external override onlyMintingManager { _mint(to, tokenId, uri); } function safeMint( address to, uint256 tokenId, string calldata uri ) external override onlyMintingManager { _safeMint(to, tokenId, uri, ''); } function safeMint( address to, uint256 tokenId, string calldata uri, bytes calldata data ) external override onlyMintingManager { _safeMint(to, tokenId, uri, data); } function mintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values ) external override onlyMintingManager { _mint(to, tokenId, uri); _setMany(keys, values, tokenId); } function safeMintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values ) external override onlyMintingManager { _safeMintWithRecords(to, tokenId, uri, keys, values, ''); } function safeMintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values, bytes calldata data ) external override onlyMintingManager { _safeMintWithRecords(to, tokenId, uri, keys, values, data); } /// Transfering function setOwner(address to, uint256 tokenId) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _transfer(ownerOf(tokenId), to, tokenId); } function transferFrom( address from, address to, uint256 tokenId ) public override(IERC721Upgradeable, ERC721Upgradeable) onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reset(tokenId); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory data ) public override(IERC721Upgradeable, ERC721Upgradeable) onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reset(tokenId); _safeTransfer(from, to, tokenId, data); } /// Burning function burn(uint256 tokenId) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reset(tokenId); _burn(tokenId); } /// Resolution function resolverOf(uint256 tokenId) external view override returns (address) { return _exists(tokenId) ? address(this) : address(0x0); } function set( string calldata key, string calldata value, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _set(key, value, tokenId); } function setMany( string[] calldata keys, string[] calldata values, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _setMany(keys, values, tokenId); } function setByHash( uint256 keyHash, string calldata value, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _setByHash(keyHash, value, tokenId); } function setManyByHash( uint256[] calldata keyHashes, string[] calldata values, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _setManyByHash(keyHashes, values, tokenId); } function reconfigure( string[] calldata keys, string[] calldata values, uint256 tokenId ) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reconfigure(keys, values, tokenId); } function reset(uint256 tokenId) external override onlyApprovedOrOwner(tokenId) protectTokenOperation(tokenId) { _reset(tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) { return super.supportsInterface(interfaceId); } // TODO: guard the function by owner check // This is the keccak-256 hash of "uns.polygon.root_chain_manager" subtracted by 1 bytes32 internal constant _ROOT_CHAIN_MANAGER_SLOT = 0xbe2bb46ac0377341a1ec5c3116d70fd5029d704bd46292e58f6265dd177ebafe; function setRootChainManager(address rootChainManager) public { require( StorageSlotUpgradeable.getAddressSlot(_ROOT_CHAIN_MANAGER_SLOT).value == address(0), 'Registry: ROOT_CHAIN_MANEGER_NOT_EMPTY' ); StorageSlotUpgradeable.getAddressSlot(_ROOT_CHAIN_MANAGER_SLOT).value = rootChainManager; } function depositToPolygon(uint256 tokenId) public onlyApprovedOrOwner(tokenId) { address manager = StorageSlotUpgradeable.getAddressSlot(_ROOT_CHAIN_MANAGER_SLOT).value; bytes32 tokenType = RootChainManagerStorage(manager).tokenToType(address(this)); address predicate = RootChainManagerStorage(manager).typeToPredicate(tokenType); // A workaround for MintableERC721Predicate // that requires a depositor to be equal to token owner: // https://github.com/maticnetwork/pos-portal/blob/88dbf0a88fd68fa11f7a3b9d36629930f6b93a05/contracts/root/TokenPredicates/MintableERC721Predicate.sol#L94 _transfer(_msgSender(), address(this), tokenId); _approve(predicate, tokenId); IRootChainManager(manager).depositFor(_msgSender(), address(this), abi.encode(tokenId)); } /// Internal function _childId(uint256 tokenId, string memory label) internal pure returns (uint256) { require(bytes(label).length != 0, 'Registry: LABEL_EMPTY'); return uint256(keccak256(abi.encodePacked(tokenId, keccak256(abi.encodePacked(label))))); } function _mint( address to, uint256 tokenId, string memory uri ) internal { _mint(to, tokenId); emit NewURI(tokenId, uri); } function _safeMint( address to, uint256 tokenId, string memory uri, bytes memory data ) internal { _safeMint(to, tokenId, data); emit NewURI(tokenId, uri); } function _safeMintWithRecords( address to, uint256 tokenId, string calldata uri, string[] calldata keys, string[] calldata values, bytes memory data ) internal { _safeMint(to, tokenId, uri, data); _setMany(keys, values, tokenId); } function _baseURI() internal view override(ERC721Upgradeable) returns (string memory) { return _prefix; } function _msgSender() internal view override(ContextUpgradeable, ERC2771RegistryContext) returns (address) { return super._msgSender(); } function _msgData() internal view override(ContextUpgradeable, ERC2771RegistryContext) returns (bytes calldata) { return super._msgData(); } // Reserved storage space to allow for layout changes in the future. uint256[50] private __gap; }
6,493
7
// The following success variables replace require statements with corresponding functions called. Removing require statements to ensure a wrong proof verification challenge's require statement correctly works
bool success_pp4_out_not_0; bool success_pp4_pairing; (success_pp4_out_not_0, success_pp4_pairing) = Pairing.pairingProd4( proof.A, proof.B, Pairing.negate(vk_dot_inputs), vk.gamma, Pairing.negate(proof.C), vk.delta, Pairing.negate(vk.alpha), vk.beta); if (!success_pp4_out_not_0 || !success_pp4_pairing) { return 5; }
bool success_pp4_out_not_0; bool success_pp4_pairing; (success_pp4_out_not_0, success_pp4_pairing) = Pairing.pairingProd4( proof.A, proof.B, Pairing.negate(vk_dot_inputs), vk.gamma, Pairing.negate(proof.C), vk.delta, Pairing.negate(vk.alpha), vk.beta); if (!success_pp4_out_not_0 || !success_pp4_pairing) { return 5; }
8,250