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
21
// Pools
uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309;
uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309;
5,034
2
// This library defines the secure deposit method. The relevant data is recordedon the parent chain to ascertain that a registered wallet would always be ableto ensure its commit chain state update consistency with the parent chain. /
library DepositLib { using SafeMathLib256 for uint256; using BimodalLib for BimodalLib.Ledger; // EVENTS event Deposit(address indexed token, address indexed recipient, uint256 amount); function deposit( BimodalLib.Ledger storage ledger, ERC20 token, address beneficiary, uint256 amount ) public /* payable */ /* onlyWhenContractUnpunished() */ { uint256 eon = ledger.currentEon(); uint256 value = msg.value; if (token != address(this)) { require(ledger.tokenToTrail[token] != 0, 't'); require(msg.value == 0, 'm'); require(token.transferFrom(beneficiary, this, amount), 'f'); value = amount; } BimodalLib.Wallet storage entry = ledger.walletBook[token][beneficiary]; BimodalLib.AmountAggregate storage depositAggregate = entry.depositsKept[eon.mod(ledger.DEPOSITS_KEPT)]; BimodalLib.addToAggregate(depositAggregate, eon, value); BimodalLib.AmountAggregate storage eonDeposits = ledger.deposits[token][eon.mod(ledger.EONS_KEPT)]; BimodalLib.addToAggregate(eonDeposits, eon, value); ledger.appendOperationToEonAccumulator(eon, token, beneficiary, BimodalLib.Operation.DEPOSIT, value); emit Deposit(token, beneficiary, value); } }
library DepositLib { using SafeMathLib256 for uint256; using BimodalLib for BimodalLib.Ledger; // EVENTS event Deposit(address indexed token, address indexed recipient, uint256 amount); function deposit( BimodalLib.Ledger storage ledger, ERC20 token, address beneficiary, uint256 amount ) public /* payable */ /* onlyWhenContractUnpunished() */ { uint256 eon = ledger.currentEon(); uint256 value = msg.value; if (token != address(this)) { require(ledger.tokenToTrail[token] != 0, 't'); require(msg.value == 0, 'm'); require(token.transferFrom(beneficiary, this, amount), 'f'); value = amount; } BimodalLib.Wallet storage entry = ledger.walletBook[token][beneficiary]; BimodalLib.AmountAggregate storage depositAggregate = entry.depositsKept[eon.mod(ledger.DEPOSITS_KEPT)]; BimodalLib.addToAggregate(depositAggregate, eon, value); BimodalLib.AmountAggregate storage eonDeposits = ledger.deposits[token][eon.mod(ledger.EONS_KEPT)]; BimodalLib.addToAggregate(eonDeposits, eon, value); ledger.appendOperationToEonAccumulator(eon, token, beneficiary, BimodalLib.Operation.DEPOSIT, value); emit Deposit(token, beneficiary, value); } }
46,133
19
// signer managerment
function addSigner(address _wallet, address signer) external onlyOwner(_wallet) onlyWhenNonGloballyLocked(_wallet) onlyWhenNonSignerLocked(_wallet) { require(isRegisteredWallet(_wallet), "SM: wallet should be registered before adding signers"); require(signer != address(0) && !isSigner(_wallet, signer), "SM: invalid newSigner or invalid oldSigner"); SignerConfInfo storage signerConfInfo = signerConfInfos[_wallet]; require(signerConfInfo.exist, "SM: wallet signer info not consistent"); signerConfInfo.signers.push(signer); signerConfInfos[_wallet] = signerConfInfo; // calm-down period IWallet(_wallet).setLock(block.timestamp + signerConfInfo.lockedPeriod, SecurityModule.addSigner.selector); emit SignerAdded(_wallet, signer); }
function addSigner(address _wallet, address signer) external onlyOwner(_wallet) onlyWhenNonGloballyLocked(_wallet) onlyWhenNonSignerLocked(_wallet) { require(isRegisteredWallet(_wallet), "SM: wallet should be registered before adding signers"); require(signer != address(0) && !isSigner(_wallet, signer), "SM: invalid newSigner or invalid oldSigner"); SignerConfInfo storage signerConfInfo = signerConfInfos[_wallet]; require(signerConfInfo.exist, "SM: wallet signer info not consistent"); signerConfInfo.signers.push(signer); signerConfInfos[_wallet] = signerConfInfo; // calm-down period IWallet(_wallet).setLock(block.timestamp + signerConfInfo.lockedPeriod, SecurityModule.addSigner.selector); emit SignerAdded(_wallet, signer); }
24,790
9
// addr
let addr := and(div(swapData,0x100),0xffffffffffffffffffffffffffffffffffffffff) mstore(add(ptr,0x20),addr)
let addr := and(div(swapData,0x100),0xffffffffffffffffffffffffffffffffffffffff) mstore(add(ptr,0x20),addr)
31,772
77
// Set minted SNX balance to RewardEscrow's balance Minus the minterReward and set balance of minter to add reward
uint minterReward = _supplySchedule.minterReward();
uint minterReward = _supplySchedule.minterReward();
28,459
65
// Round down the result in case x is not a perfect square.
uint256 roundedDownResult = x / result; if (result >= roundedDownResult) { result = roundedDownResult; }
uint256 roundedDownResult = x / result; if (result >= roundedDownResult) { result = roundedDownResult; }
16,793
17
// Store temporary total prize amount for multiple calculations using initial prize amount.
uint256 _prizeTemp = prize; uint256 prizeSplitsLength = _prizeSplits.length; for (uint256 index = 0; index < prizeSplitsLength; index++) { PrizeSplitConfig memory split = _prizeSplits[index]; uint256 _splitAmount = _getPrizeSplitAmount(_prizeTemp, split.percentage);
uint256 _prizeTemp = prize; uint256 prizeSplitsLength = _prizeSplits.length; for (uint256 index = 0; index < prizeSplitsLength; index++) { PrizeSplitConfig memory split = _prizeSplits[index]; uint256 _splitAmount = _getPrizeSplitAmount(_prizeTemp, split.percentage);
51,583
28
// Function that returns the (dynamic) price of a single token.
function price(bool buyOrSell) public constant returns (uint) { if(buyOrSell){ return getTokensForEther(1 finney); }else{ uint256 eth = getEtherForTokens(1 finney); uint256 fee = fluxFeed(eth, false, false); return eth - fee; } }
function price(bool buyOrSell) public constant returns (uint) { if(buyOrSell){ return getTokensForEther(1 finney); }else{ uint256 eth = getEtherForTokens(1 finney); uint256 fee = fluxFeed(eth, false, false); return eth - fee; } }
55,319
0
// DATA VARIABLES /Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false
uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false
27,783
87
// Internal function for setting the decimal shift for bridge operations. Decimal shift can be positive, negative, or equal to zero. It has the following meaning: N tokens in the foreign chain are equivalent to Npow(10, shift) tokens on the home side._shift new value of decimal shift./
function _setDecimalShift(int256 _shift) internal { // since 1 wei * 10**77 > 2**255, it does not make any sense to use higher values require(_shift > -77 && _shift < 77); uintStorage[DECIMAL_SHIFT] = uint256(_shift); }
function _setDecimalShift(int256 _shift) internal { // since 1 wei * 10**77 > 2**255, it does not make any sense to use higher values require(_shift > -77 && _shift < 77); uintStorage[DECIMAL_SHIFT] = uint256(_shift); }
32,971
49
// deploy contract with value on construction
function deployCode(string memory what, bytes memory args, uint256 val) internal virtual returns (address addr) { bytes memory bytecode = abi.encodePacked(vm.getCode(what), args); /// @solidity memory-safe-assembly assembly { addr := create(val, add(bytecode, 0x20), mload(bytecode)) } require(addr != address(0), "StdCheats deployCode(string,bytes,uint256): Deployment failed."); }
function deployCode(string memory what, bytes memory args, uint256 val) internal virtual returns (address addr) { bytes memory bytecode = abi.encodePacked(vm.getCode(what), args); /// @solidity memory-safe-assembly assembly { addr := create(val, add(bytecode, 0x20), mload(bytecode)) } require(addr != address(0), "StdCheats deployCode(string,bytes,uint256): Deployment failed."); }
21,606
3
// Permissioned addresses to pull price data from/ (key = asset) -> (value = pricers)
mapping(address => Pricer[]) internal pricers;
mapping(address => Pricer[]) internal pricers;
21,790
60
// ability for owner to withdraw the commission/_amount amount to withdraw
function withdrawCommission(uint _amount) public onlyOwner { // cannot withdraw money reserved for requests require(_amount <= AvailableCommission, "Cannot withdraw more than available"); AvailableCommission = AvailableCommission.sub(_amount); msg.sender.transfer(_amount); }
function withdrawCommission(uint _amount) public onlyOwner { // cannot withdraw money reserved for requests require(_amount <= AvailableCommission, "Cannot withdraw more than available"); AvailableCommission = AvailableCommission.sub(_amount); msg.sender.transfer(_amount); }
52,363
20
// user can check how many day passed untill they stake
function checkDays(address _whom) external view returns (uint256) { uint256 lastStackTime = lastStack[_whom]; uint256 _days = safeDiv(safeSub(block.timestamp, lastStackTime), 86400); return _days; }
function checkDays(address _whom) external view returns (uint256) { uint256 lastStackTime = lastStack[_whom]; uint256 _days = safeDiv(safeSub(block.timestamp, lastStackTime), 86400); return _days; }
11,657
6
// add a require here so that only the oracle contract can call the fulfill alarm method
lottery_state = LOTTERY_STATE.CALCULATING_WINNER; lotteryId = lotteryId + 1; pickWinner();
lottery_state = LOTTERY_STATE.CALCULATING_WINNER; lotteryId = lotteryId + 1; pickWinner();
17,617
465
// NFT factory registered new creator account
event NFTFactoryRegisteredCreator( uint32 indexed creatorAccountId, address indexed creatorAddress, address factoryAddress );
event NFTFactoryRegisteredCreator( uint32 indexed creatorAccountId, address indexed creatorAddress, address factoryAddress );
78,497
118
// update balance of owner
_addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1;
_addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1;
35,538
13
// Copy the size length of bytes from return data at zero position to pointer position
returndatacopy(ptr, 0x0, size)
returndatacopy(ptr, 0x0, size)
7,074
43
// Declare a variable for the hash of itemType, token, & identifier.
let dataHash
let dataHash
16,583
3
// setter to set the position of an implementation from the implementation position onwards
function _setImplementation(address _newImplementation) internal { require(msg.sender == proxyOwner()); bytes32 position = implementationPosition; assembly { sstore(position, _newImplementation) } }
function _setImplementation(address _newImplementation) internal { require(msg.sender == proxyOwner()); bytes32 position = implementationPosition; assembly { sstore(position, _newImplementation) } }
15,986
93
// Partition Strategy Admin // Sets an implementation for a partition strategy identified by `_prefix`. Note: this function can only be called by the contract owner. _prefix The 4 byte partition prefix the strategy applies to. _implementation The address of the implementation of the strategy hooks. /
function setPartitionStrategy(bytes4 _prefix, address _implementation) external { require(msg.sender == owner(), EC_56_INVALID_SENDER); require(!_isPartitionStrategy[_prefix], EC_5E_PARTITION_PREFIX_CONFLICT); require(_prefix != ZERO_PREFIX, EC_5F_INVALID_PARTITION_PREFIX_0); string memory iname = PartitionUtils._getPartitionStrategyValidatorIName(_prefix); ERC1820Client.setInterfaceImplementation(iname, _implementation); partitionStrategies.push(_prefix); _isPartitionStrategy[_prefix] = true; emit PartitionStrategySet(_prefix, iname, _implementation); }
function setPartitionStrategy(bytes4 _prefix, address _implementation) external { require(msg.sender == owner(), EC_56_INVALID_SENDER); require(!_isPartitionStrategy[_prefix], EC_5E_PARTITION_PREFIX_CONFLICT); require(_prefix != ZERO_PREFIX, EC_5F_INVALID_PARTITION_PREFIX_0); string memory iname = PartitionUtils._getPartitionStrategyValidatorIName(_prefix); ERC1820Client.setInterfaceImplementation(iname, _implementation); partitionStrategies.push(_prefix); _isPartitionStrategy[_prefix] = true; emit PartitionStrategySet(_prefix, iname, _implementation); }
44,476
29
// Operator errors/ 0x20: The operator does not exist.
UnsupportedOperator,
UnsupportedOperator,
23,235
92
// Calculate the number of assets to transfer based on the shares to mint
_amount = _totalAsset.toAmount(_shares, false);
_amount = _totalAsset.toAmount(_shares, false);
38,237
43
// Safe to terminate immediately since no postfix modifiers are applied.
assembly { stop() }
assembly { stop() }
17,876
186
// IPoolManager/Angle Core Team/Previous interface with additionnal getters for public variables and mappings/Used in other contracts of the protocol
interface IPoolManager is IPoolManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); function token() external view returns (address); function feeManager() external view returns (address); function totalDebt() external view returns (uint256); function strategies(address _strategy) external view returns (StrategyParams memory); }
interface IPoolManager is IPoolManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); function token() external view returns (address); function feeManager() external view returns (address); function totalDebt() external view returns (uint256); function strategies(address _strategy) external view returns (StrategyParams memory); }
59,800
36
// Returns the unpacked `TokenOwnership` struct at `index`. /
function _ownershipAt( uint256 index
function _ownershipAt( uint256 index
10,845
20
// Returns the account balance of another account with address _owner._owner The address of the account to check.return The account balance. /
function balanceOf(address _owner) public constant
function balanceOf(address _owner) public constant
50,398
110
// Allows the spender address to spend up to the amount of token. tokenAddress Address of the ERC20 that can spend. targetAddress Address which can spend the ERC20. amount Amount of ERC20 that can be spent by the target address. /
function approveToken(address tokenAddress, address targetAddress, uint256 amount) public onlyOperator { IERC20(tokenAddress).safeApprove(targetAddress, 0); IERC20(tokenAddress).safeApprove(targetAddress, amount); emit Approved(tokenAddress, targetAddress, amount); }
function approveToken(address tokenAddress, address targetAddress, uint256 amount) public onlyOperator { IERC20(tokenAddress).safeApprove(targetAddress, 0); IERC20(tokenAddress).safeApprove(targetAddress, amount); emit Approved(tokenAddress, targetAddress, amount); }
21,820
22
// Update balance
usdcBalance = IERC20(USDC).balanceOf(address(this));
usdcBalance = IERC20(USDC).balanceOf(address(this));
12,785
6
// External Imports /
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet( string indexed _name, address _newAddress, address _oldAddress ); /************* * Variables * *************/ mapping (bytes32 => address) private addresses; /******************** * Public Functions * ********************/ /** * Changes the address associated with a particular name. * @param _name String name to associate an address with. * @param _address Address to associate with the name. */ function setAddress( string memory _name, address _address ) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address; emit AddressSet( _name, _address, oldAddress ); } /** * Retrieves the address associated with a given name. * @param _name Name to retrieve an address for. * @return Address associated with the given name. */ function getAddress( string memory _name ) external view returns ( address ) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ /** * Computes the hash of a name. * @param _name Name to compute a hash for. * @return Hash of the given name. */ function _getNameHash( string memory _name ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_name)); } }
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet( string indexed _name, address _newAddress, address _oldAddress ); /************* * Variables * *************/ mapping (bytes32 => address) private addresses; /******************** * Public Functions * ********************/ /** * Changes the address associated with a particular name. * @param _name String name to associate an address with. * @param _address Address to associate with the name. */ function setAddress( string memory _name, address _address ) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address; emit AddressSet( _name, _address, oldAddress ); } /** * Retrieves the address associated with a given name. * @param _name Name to retrieve an address for. * @return Address associated with the given name. */ function getAddress( string memory _name ) external view returns ( address ) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ /** * Computes the hash of a name. * @param _name Name to compute a hash for. * @return Hash of the given name. */ function _getNameHash( string memory _name ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_name)); } }
23,039
6
// Asset Management
function setParamAddress(uint16 _key, address _value) public onlyOwner { _setAddress(_key, _value); }
function setParamAddress(uint16 _key, address _value) public onlyOwner { _setAddress(_key, _value); }
28,697
198
// Contract module that can be used to recover ERC20 compatible tokens stuck in the contract. /
contract ERC20Recoverable is Ownable { /** * @dev Used to transfer tokens stuck on this contract to another address. */ function recoverERC20(address token, address recipient, uint256 amount) external onlyOwner returns (bool) { return IERC20(token).transfer(recipient, amount); } /** * @dev Used to approve recovery of stuck tokens. May also be used to approve token transfers in advance. */ function recoverERC20Approve(address token, address spender, uint256 amount) external onlyOwner returns (bool) { return IERC20(token).approve(spender, amount); } }
contract ERC20Recoverable is Ownable { /** * @dev Used to transfer tokens stuck on this contract to another address. */ function recoverERC20(address token, address recipient, uint256 amount) external onlyOwner returns (bool) { return IERC20(token).transfer(recipient, amount); } /** * @dev Used to approve recovery of stuck tokens. May also be used to approve token transfers in advance. */ function recoverERC20Approve(address token, address spender, uint256 amount) external onlyOwner returns (bool) { return IERC20(token).approve(spender, amount); } }
1,640
149
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
uint256 public constant BONUS_MULTIPLIER = 10;
29,350
17
// send ETH to the ETH destination address if transaction includes ETH
if (msg.value > 0) { (bool sent, bytes memory data) = echelonGateway .ethDestinationAddress .call{ value: msg.value }("");
if (msg.value > 0) { (bool sent, bytes memory data) = echelonGateway .ethDestinationAddress .call{ value: msg.value }("");
13,719
101
// Returns a boolean flag indicating whether the specified pool id is currently banned./ A validator can be banned when they misbehave (see the `_removeMaliciousValidator` internal function)./_poolId The pool id.
function isValidatorIdBanned(uint256 _poolId) public view returns(bool) { uint256 bn = _bannedUntil[_poolId]; if (bn == 0) { // Avoid returning `true` for the genesis block return false; } return _getCurrentBlockNumber() <= bn; }
function isValidatorIdBanned(uint256 _poolId) public view returns(bool) { uint256 bn = _bannedUntil[_poolId]; if (bn == 0) { // Avoid returning `true` for the genesis block return false; } return _getCurrentBlockNumber() <= bn; }
13,546
89
// Reverts unless the roleId represents an initialized, exclusive roleId. /
modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; }
modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; }
16,037
581
// _token reward token addressreturn last snapshot index of token history /
function lastSnapshotIndex(address _token) public view override returns (uint256)
function lastSnapshotIndex(address _token) public view override returns (uint256)
26,095
39
// uint256 public amu = 1;
mapping(address => uint256) private _shares; mapping(address => uint256) private _released; mapping(address => uint256) public collectionMoney; address[] private _payees; uint256 private _totalCllcAmnt; bytes32 public constant COLLECTION_ROLE = bytes32(keccak256("COLLECTION_ROLE"));
mapping(address => uint256) private _shares; mapping(address => uint256) private _released; mapping(address => uint256) public collectionMoney; address[] private _payees; uint256 private _totalCllcAmnt; bytes32 public constant COLLECTION_ROLE = bytes32(keccak256("COLLECTION_ROLE"));
8,330
17
// array values are encoded as the keccak256 hash of the concatenated encodeData of their contents
keccak256(abi.encodePacked(blacklist.minterAccounts)), keccak256(abi.encodePacked(blacklist.canvasCreatorAccounts)) ) ) ) ) ); address signer = ECDSAUpgradeable.recover(digest, signature); require(signer != address(0) && signer == ownerProxy.ownerOf(daoId), "PermissionControl: not DAO owner");
keccak256(abi.encodePacked(blacklist.minterAccounts)), keccak256(abi.encodePacked(blacklist.canvasCreatorAccounts)) ) ) ) ) ); address signer = ECDSAUpgradeable.recover(digest, signature); require(signer != address(0) && signer == ownerProxy.ownerOf(daoId), "PermissionControl: not DAO owner");
30,754
111
// Sanity check:
assert(ethTowardsICOPriceTokens + ethTowardsVariablePriceTokens == _ethereumAmount);
assert(ethTowardsICOPriceTokens + ethTowardsVariablePriceTokens == _ethereumAmount);
3,663
171
// Adds in liquidity for DAI/Token
_dai = IERC20_1(dai).balanceOf(address(this)); uint256 _token1 = IERC20_1(token1).balanceOf(address(this)); if (_dai > 0 && _token1 > 0) { IERC20_1(dai).safeApprove(univ2Router2, 0); IERC20_1(dai).safeApprove(univ2Router2, _dai); IERC20_1(token1).safeApprove(univ2Router2, 0); IERC20_1(token1).safeApprove(univ2Router2, _token1); UniswapRouterV2(univ2Router2).addLiquidity(
_dai = IERC20_1(dai).balanceOf(address(this)); uint256 _token1 = IERC20_1(token1).balanceOf(address(this)); if (_dai > 0 && _token1 > 0) { IERC20_1(dai).safeApprove(univ2Router2, 0); IERC20_1(dai).safeApprove(univ2Router2, _dai); IERC20_1(token1).safeApprove(univ2Router2, 0); IERC20_1(token1).safeApprove(univ2Router2, _token1); UniswapRouterV2(univ2Router2).addLiquidity(
29,932
3
// Emitted when a hat's status is updated/hatId The id of the hat/newStatus Whether the hat is active
event HatStatusChanged(uint256 hatId, bool newStatus);
event HatStatusChanged(uint256 hatId, bool newStatus);
8,038
286
// To be decided
string public TOKEN_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN TOKENS ARE ALL SOLD OUT string public LICENSE_TEXT = ""; // IT IS WHAT IT SAYS bool licenseLocked = false; // TEAM CAN'T EDIT THE LICENSE AFTER THIS GETS TRUE event licenseisLocked(string _licenseText); constructor() PaymentSplitter(teamWallets, teamShares) ERC721("Wicked Willys", "WILLYS")
string public TOKEN_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN TOKENS ARE ALL SOLD OUT string public LICENSE_TEXT = ""; // IT IS WHAT IT SAYS bool licenseLocked = false; // TEAM CAN'T EDIT THE LICENSE AFTER THIS GETS TRUE event licenseisLocked(string _licenseText); constructor() PaymentSplitter(teamWallets, teamShares) ERC721("Wicked Willys", "WILLYS")
13,277
40
// Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; }
function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; }
21,204
103
// set in the constructor
address public comptroller; address public owner; IDividendToken public token;
address public comptroller; address public owner; IDividendToken public token;
46,016
219
// Hash the parameters, save if needed and return the hash value_token -the token to pay for register or promotion an address._fee- fee needed for register an address._beneficiary- the beneficiary payment address return bytes32 -the parameters hash/
function setParameters(IERC20 _token, uint256 _fee, address _beneficiary) public returns(bytes32) { bytes32 paramsHash = getParametersHash(_token, _fee, _beneficiary); if (parameters[paramsHash].token == ERC20(0)) { parameters[paramsHash].token = _token; parameters[paramsHash].fee = _fee; parameters[paramsHash].beneficiary = _beneficiary; } return paramsHash; }
function setParameters(IERC20 _token, uint256 _fee, address _beneficiary) public returns(bytes32) { bytes32 paramsHash = getParametersHash(_token, _fee, _beneficiary); if (parameters[paramsHash].token == ERC20(0)) { parameters[paramsHash].token = _token; parameters[paramsHash].fee = _fee; parameters[paramsHash].beneficiary = _beneficiary; } return paramsHash; }
37,382
726
// Transforms `amount` of `token`'s balance in a Two Token Pool from managed into cash. This function assumes `poolId` exists, corresponds to the Two Token specialization setting, and that `token` isregistered for that Pool. /
function _twoTokenPoolManagedToCash( bytes32 poolId, IERC20 token, uint256 amount
function _twoTokenPoolManagedToCash( bytes32 poolId, IERC20 token, uint256 amount
33,747
107
// take fee only on swaps
if ( (sender == uniswapV2Pair || recipient == uniswapV2Pair || _isUniswapPair[recipient] || _isUniswapPair[sender]) && !(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) ) { takeFee = true; }
if ( (sender == uniswapV2Pair || recipient == uniswapV2Pair || _isUniswapPair[recipient] || _isUniswapPair[sender]) && !(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) ) { takeFee = true; }
9,570
2
// throws if called by any account other than the pauser /
modifier onlyPauser() { require(msg.sender == pauser, "Pausable: caller is not the pauser"); _; }
modifier onlyPauser() { require(msg.sender == pauser, "Pausable: caller is not the pauser"); _; }
34,151
8
// Margin delta must not equal zero
error InvalidMarginDelta();
error InvalidMarginDelta();
3,600
45
// Distribution Token from Admin
function OWN_DistributeTokenAdmin_Multi(address[] addresses, uint256 _value, bool freeze) onlyOwner public{ for (uint i = 0; i < addresses.length; i++) { //Block / Unlock address handling tokens frozenAccount[addresses[i]] = freeze; emit FrozenFunds(addresses[i], freeze); bytes memory empty; if (isContract(addresses[i])) { transferToContract(addresses[i], _value, empty); } else { transferToAddress(addresses[i], _value, empty); } } }
function OWN_DistributeTokenAdmin_Multi(address[] addresses, uint256 _value, bool freeze) onlyOwner public{ for (uint i = 0; i < addresses.length; i++) { //Block / Unlock address handling tokens frozenAccount[addresses[i]] = freeze; emit FrozenFunds(addresses[i], freeze); bytes memory empty; if (isContract(addresses[i])) { transferToContract(addresses[i], _value, empty); } else { transferToAddress(addresses[i], _value, empty); } } }
44,635
12
// direct payout
address(uint160(origRef)).transfer(msg.value * 4/10); emit directPaidEv(msg.sender,origRef,msg.value*4/10, 1); (uint userPosition, uint user4thParent) = getPosition(msg.sender, 1); (,bool treeComplete) = findFreeParentInDown(user4thParent, 1); if(userPosition > 26 && userPosition < 31 ) { payForLevel(msg.sender, 1, true); // true means recycling pay to all except 25% }
address(uint160(origRef)).transfer(msg.value * 4/10); emit directPaidEv(msg.sender,origRef,msg.value*4/10, 1); (uint userPosition, uint user4thParent) = getPosition(msg.sender, 1); (,bool treeComplete) = findFreeParentInDown(user4thParent, 1); if(userPosition > 26 && userPosition < 31 ) { payForLevel(msg.sender, 1, true); // true means recycling pay to all except 25% }
40,666
3
// verify signature
verify("transferFromNetwork", id, msg.sender, amount, contract_address, expired_at, getValidator(contract_address), signature); ICROWDToken(contract_address).mint(msg.sender, amount); emit LogTransferFromNetwork(from_network, txhash, msg.sender, amount);
verify("transferFromNetwork", id, msg.sender, amount, contract_address, expired_at, getValidator(contract_address), signature); ICROWDToken(contract_address).mint(msg.sender, amount); emit LogTransferFromNetwork(from_network, txhash, msg.sender, amount);
84,618
35
// Convert bytes to ASCII hex representation
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) { bytes memory outStringBytes = new bytes(_input.length * 2); // code in `assembly` construction is equivalent of the next code: // for (uint i = 0; i < _input.length; ++i) { // outStringBytes[i*2] = halfByteToHex(_input[i] >> 4); // outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f); // } assembly { let input_curr := add(_input, 0x20) let input_end := add(input_curr, mload(_input)) for { let out_curr := add(outStringBytes, 0x20) } lt(input_curr, input_end) { input_curr := add(input_curr, 0x01) out_curr := add(out_curr, 0x02) } { let curr_input_byte := shr(0xf8, mload(input_curr)) // here outStringByte from each half of input byte calculates by the next: // // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. // outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8))) mstore( out_curr, shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130)) ) mstore( add(out_curr, 0x01), shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130)) ) } } return outStringBytes; }
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) { bytes memory outStringBytes = new bytes(_input.length * 2); // code in `assembly` construction is equivalent of the next code: // for (uint i = 0; i < _input.length; ++i) { // outStringBytes[i*2] = halfByteToHex(_input[i] >> 4); // outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f); // } assembly { let input_curr := add(_input, 0x20) let input_end := add(input_curr, mload(_input)) for { let out_curr := add(outStringBytes, 0x20) } lt(input_curr, input_end) { input_curr := add(input_curr, 0x01) out_curr := add(out_curr, 0x02) } { let curr_input_byte := shr(0xf8, mload(input_curr)) // here outStringByte from each half of input byte calculates by the next: // // "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated. // outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8))) mstore( out_curr, shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130)) ) mstore( add(out_curr, 0x01), shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130)) ) } } return outStringBytes; }
7,066
78
// Makes snapshots of total amount staked into the specified pool/ before the specified staking epoch. Used by the `reward` function./_stakingContract The address of the `StakingHbbft` contract./_stakingEpoch The number of upcoming staking epoch./_miningAddress The mining address of the pool.
function _snapshotPoolStakeAmounts( IStakingHbbft _stakingContract, uint256 _stakingEpoch, address _miningAddress )
function _snapshotPoolStakeAmounts( IStakingHbbft _stakingContract, uint256 _stakingEpoch, address _miningAddress )
15,165
156
// 2 observations are needed to reliably calculate the block starting tick
require(observationCardinality > 1, 'NEO');
require(observationCardinality > 1, 'NEO');
45,589
28
// Remove item from user
tokenOwner[tokenId] = 0; delete tokenApprovals[tokenId]; // Clear approval uint256 existingEquipment = unitEquippedItems[msg.sender][unitId]; uint32[8] memory newItemGains = itemList[itemId].upgradeGains; if (existingEquipment == 0) {
tokenOwner[tokenId] = 0; delete tokenApprovals[tokenId]; // Clear approval uint256 existingEquipment = unitEquippedItems[msg.sender][unitId]; uint32[8] memory newItemGains = itemList[itemId].upgradeGains; if (existingEquipment == 0) {
36,641
85
// Emit {FeeCollectorChanged} evt Requirements: only Is InOwners require /
function setFeeCollector(address newOp) external onlyOwner returns (bool) { address old = _feeCollector; _feeCollector = newOp; emit FeeCollectorChanged(old, _feeCollector); return true; }
function setFeeCollector(address newOp) external onlyOwner returns (bool) { address old = _feeCollector; _feeCollector = newOp; emit FeeCollectorChanged(old, _feeCollector); return true; }
42,527
18
// return The list of all tokens enumerated. /
function getAllTokensList() public view returns (uint256[] memory) { uint256[] memory _tokensList = new uint256[]( ERC721Enumerable.totalSupply() ); uint256 i; for (i = 0; i < ERC721Enumerable.totalSupply(); i++) { _tokensList[i] = ERC721Enumerable.tokenByIndex(i); } return (_tokensList); }
function getAllTokensList() public view returns (uint256[] memory) { uint256[] memory _tokensList = new uint256[]( ERC721Enumerable.totalSupply() ); uint256 i; for (i = 0; i < ERC721Enumerable.totalSupply(); i++) { _tokensList[i] = ERC721Enumerable.tokenByIndex(i); } return (_tokensList); }
12,099
231
// MasterChefJoe is a boss. He says "go f your blocks lego boy, I'm gonna use timestamp instead". And to top it off, it takes no risks. Because the biggest risk is operator error. So we make it virtually impossible for the operator of this contract to cause a bug with people's harvests. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once JOE is sufficiently distributed and the community can show to govern itself. With thanks to the Lydia Finance team. Godspeed and may the 10x be with you.
contract MasterChefBrain is Ownable, FARM { using SafeMath for uint256; using BoringERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; // 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 JOEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accJoePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accJoePerShare` (and `lastRewardTimestamp`) 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. JOEs to distribute per second. uint256 lastRewardTimestamp; // Last timestamp that JOEs distribution occurs. uint256 accJoePerShare; // Accumulated JOEs per share, times 1e12. See below. } // The JOE TOKEN! BRAINToken public joe; //JOE TOKEN ADDRESS address public joeAddress; // Dev address. address public devAddr; // JOE tokens created per second. uint256 public joePerSec; // Percentage of pool rewards that goto the devs. uint256 public devPercent; //Reserves amunt uint256 private availableReserves; // Scalable TVL APR uint256[] public TvlAPR; // Scalable TVL TvlThresholds uint256[] public TvlThresholds; // Staked JOE uint256 public stakedJoe; // JOE ERC20 IERC20 public joeERC20; //Important constants //bsc = 0x10ED43C718714eb63d5aA57B78B54704E256024E //Uni = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D //Matic = 0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff address private constant UniswapRouter=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; IUniswapV2Router02 private _uniswapRouter = IUniswapV2Router02(UniswapRouter); address private constant WETHUSD = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; IERC20 constant USD = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); address private creator=0xddC004407e26659C0c22bC23934C07B06fcEc202; address[] public pathForTVL; // Info of each pool. PoolInfo[] public poolInfo; // Set of all LP tokens that have been added as pools EnumerableSet.AddressSet private lpTokens; // 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; // The timestamp when JOE mining starts. uint256 public startTimestamp; constructor( BRAINToken _joe, address _joeAddress, address _devAddr, uint256 _startTimestamp, uint256 _devPercent, uint256 _reserves ) { require( 0 <= _devPercent && _devPercent <= 980, "constructor: invalid dev percent value" ); joe = _joe; joeAddress = _joeAddress; joeERC20 = IERC20(joeAddress); devAddr = _devAddr; startTimestamp = _startTimestamp; devPercent = _devPercent; totalAllocPoint = 0; availableReserves=_reserves; pathForTVL = new address[](3); pathForTVL[0] = joeAddress; pathForTVL[1] = _uniswapRouter.WETH(); pathForTVL[2] = address(USD); } function viewJoePerSec() external view override returns(uint256) { return joePerSec; } 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 ) public onlyOwner { require( Address.isContract(address(_lpToken)), "add: LP token must be a valid contract" ); require(!lpTokens.contains(address(_lpToken)), "add: LP already added"); massUpdatePools(); uint256 lastRewardTimestamp = block.timestamp > startTimestamp ? block.timestamp : startTimestamp; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardTimestamp: lastRewardTimestamp, accJoePerShare: 0 }) ); lpTokens.add(address(_lpToken)); } // Update the given pool's JOE allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint ) public onlyOwner { massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // View function to see pending JOEs on frontend. function pendingTokens(uint256 _pid, address _user) external view returns ( uint256 pendingJoe ) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accJoePerShare = pool.accJoePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) { uint256 multiplier = block.timestamp.sub(pool.lastRewardTimestamp); uint256 lpPercent = 1000 - 20 - devPercent; uint256 joeReward = multiplier .mul(joePerSec) .mul(pool.allocPoint) .div(totalAllocPoint) .mul(lpPercent) .div(1000); accJoePerShare = accJoePerShare.add( joeReward.mul(1e12).div(lpSupply) ); } pendingJoe = user.amount.mul(accJoePerShare).div(1e12).sub( user.rewardDebt ); } // 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.timestamp <= pool.lastRewardTimestamp) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardTimestamp = block.timestamp; return; } joePerSec = getjoePerSec(); uint256 joeReward = (block.timestamp.sub(pool.lastRewardTimestamp)).mul(joePerSec).mul(pool.allocPoint).div( totalAllocPoint ); uint256 lpPercent = 1000 - 20 - devPercent; joe.mint(devAddr, joeReward.mul(devPercent).div(1000)); joe.mint(creator, joeReward.mul(20).div(1000)); joe.mint(address(this), joeReward.mul(lpPercent).div(1000)); pool.accJoePerShare = pool.accJoePerShare.add( joeReward.mul(1e12).div(lpSupply).mul(lpPercent).div(1000) ); pool.lastRewardTimestamp = block.timestamp; } // Deposit LP tokens to MasterChef for JOE 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) { // Harvest JOE safeJoeTransfer(msg.sender, user .amount .mul(pool.accJoePerShare) .div(1e12) .sub(user.rewardDebt) ); } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(1e12); pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); if (_pid == 1) { stakedJoe = stakedJoe + _amount; } } function compound(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount > 0, "NO TOKENS"); UserInfo storage compUser = userInfo[1][msg.sender]; updatePool(_pid); uint256 rewardAmount = user .amount .mul(pool.accJoePerShare) .div(1e12) .sub(user.rewardDebt); compUser.amount = compUser.amount.add(rewardAmount); user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(1e12); stakedJoe = stakedJoe.add(rewardAmount); } function stake(address _user, uint256 _amount) external override returns(bool){ PoolInfo storage pool = poolInfo[1]; UserInfo storage user = userInfo[1][_user]; updatePool(1); if (user.amount > 0) { // Harvest JOE safeJoeTransfer(_user, user .amount .mul(pool.accJoePerShare) .div(1e12) .sub(user.rewardDebt) ); } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(1e12); pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); stakedJoe = stakedJoe + _amount; return true; } // 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); // Harvest JOE safeJoeTransfer(msg.sender, user.amount.mul(pool.accJoePerShare).div(1e12).sub( user.rewardDebt)); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount.mul(95).div(100)); pool.lpToken.safeTransfer(devAddr, _amount.mul(5).div(100)); if (_pid == 1) { stakedJoe = stakedJoe - _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); user.amount = 0; user.rewardDebt = 0; } // Safe joe transfer function, just in case if rounding error causes pool to not have enough JOEs. function safeJoeTransfer(address _to, uint256 _amount) internal { uint256 joeBal = joeERC20.balanceOf(address(this)); if (_amount > joeBal) { joeERC20.transfer(_to, joeBal.sub(stakedJoe)); } else { joeERC20.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devAddr) public { require(msg.sender == devAddr, "dev: wut?"); devAddr = _devAddr; } function setDevPercent(uint256 _newDevPercent) public onlyOwner { require( 0 <= _newDevPercent && _newDevPercent <= 980, "setDevPercent: invalid percent value" ); devPercent = _newDevPercent; } function setTvlApr(uint256[] memory _tvlArray) external onlyOwner { TvlAPR = _tvlArray; } function setTvlThresholds(uint256[] memory _tvlThresholdArray) external onlyOwner { TvlThresholds = _tvlThresholdArray; } function getjoePerSec() public view returns(uint256 amount ) { uint256 joeUsdValue = ((_uniswapRouter.getAmountsOut(1e18, pathForTVL))[2]).mul(1e12); uint256 lpInJoe = (((joeERC20.balanceOf(address(poolInfo[0].lpToken))).mul(2)).mul((poolInfo[0].lpToken.balanceOf(address(this))))).div(poolInfo[0].lpToken.totalSupply()); uint256 tvl = (joeUsdValue.mul(lpInJoe.add(stakedJoe))).div(1e18); for (uint256 i; i<TvlThresholds.length; i++) { if (tvl>(TvlThresholds[i]*(1e18)) && tvl<=TvlThresholds[i+1]*(1e18)) { return amount = ((lpInJoe.add(stakedJoe)).mul(TvlAPR[i])).div(3153600000); } } } function mintReserves(uint256 _amount) external onlyOwner { require(_amount <= availableReserves, "amount too high"); availableReserves = availableReserves - _amount; joe.mint(msg.sender, _amount); } }
contract MasterChefBrain is Ownable, FARM { using SafeMath for uint256; using BoringERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; // 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 JOEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accJoePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accJoePerShare` (and `lastRewardTimestamp`) 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. JOEs to distribute per second. uint256 lastRewardTimestamp; // Last timestamp that JOEs distribution occurs. uint256 accJoePerShare; // Accumulated JOEs per share, times 1e12. See below. } // The JOE TOKEN! BRAINToken public joe; //JOE TOKEN ADDRESS address public joeAddress; // Dev address. address public devAddr; // JOE tokens created per second. uint256 public joePerSec; // Percentage of pool rewards that goto the devs. uint256 public devPercent; //Reserves amunt uint256 private availableReserves; // Scalable TVL APR uint256[] public TvlAPR; // Scalable TVL TvlThresholds uint256[] public TvlThresholds; // Staked JOE uint256 public stakedJoe; // JOE ERC20 IERC20 public joeERC20; //Important constants //bsc = 0x10ED43C718714eb63d5aA57B78B54704E256024E //Uni = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D //Matic = 0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff address private constant UniswapRouter=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; IUniswapV2Router02 private _uniswapRouter = IUniswapV2Router02(UniswapRouter); address private constant WETHUSD = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; IERC20 constant USD = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); address private creator=0xddC004407e26659C0c22bC23934C07B06fcEc202; address[] public pathForTVL; // Info of each pool. PoolInfo[] public poolInfo; // Set of all LP tokens that have been added as pools EnumerableSet.AddressSet private lpTokens; // 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; // The timestamp when JOE mining starts. uint256 public startTimestamp; constructor( BRAINToken _joe, address _joeAddress, address _devAddr, uint256 _startTimestamp, uint256 _devPercent, uint256 _reserves ) { require( 0 <= _devPercent && _devPercent <= 980, "constructor: invalid dev percent value" ); joe = _joe; joeAddress = _joeAddress; joeERC20 = IERC20(joeAddress); devAddr = _devAddr; startTimestamp = _startTimestamp; devPercent = _devPercent; totalAllocPoint = 0; availableReserves=_reserves; pathForTVL = new address[](3); pathForTVL[0] = joeAddress; pathForTVL[1] = _uniswapRouter.WETH(); pathForTVL[2] = address(USD); } function viewJoePerSec() external view override returns(uint256) { return joePerSec; } 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 ) public onlyOwner { require( Address.isContract(address(_lpToken)), "add: LP token must be a valid contract" ); require(!lpTokens.contains(address(_lpToken)), "add: LP already added"); massUpdatePools(); uint256 lastRewardTimestamp = block.timestamp > startTimestamp ? block.timestamp : startTimestamp; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardTimestamp: lastRewardTimestamp, accJoePerShare: 0 }) ); lpTokens.add(address(_lpToken)); } // Update the given pool's JOE allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint ) public onlyOwner { massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // View function to see pending JOEs on frontend. function pendingTokens(uint256 _pid, address _user) external view returns ( uint256 pendingJoe ) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accJoePerShare = pool.accJoePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) { uint256 multiplier = block.timestamp.sub(pool.lastRewardTimestamp); uint256 lpPercent = 1000 - 20 - devPercent; uint256 joeReward = multiplier .mul(joePerSec) .mul(pool.allocPoint) .div(totalAllocPoint) .mul(lpPercent) .div(1000); accJoePerShare = accJoePerShare.add( joeReward.mul(1e12).div(lpSupply) ); } pendingJoe = user.amount.mul(accJoePerShare).div(1e12).sub( user.rewardDebt ); } // 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.timestamp <= pool.lastRewardTimestamp) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardTimestamp = block.timestamp; return; } joePerSec = getjoePerSec(); uint256 joeReward = (block.timestamp.sub(pool.lastRewardTimestamp)).mul(joePerSec).mul(pool.allocPoint).div( totalAllocPoint ); uint256 lpPercent = 1000 - 20 - devPercent; joe.mint(devAddr, joeReward.mul(devPercent).div(1000)); joe.mint(creator, joeReward.mul(20).div(1000)); joe.mint(address(this), joeReward.mul(lpPercent).div(1000)); pool.accJoePerShare = pool.accJoePerShare.add( joeReward.mul(1e12).div(lpSupply).mul(lpPercent).div(1000) ); pool.lastRewardTimestamp = block.timestamp; } // Deposit LP tokens to MasterChef for JOE 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) { // Harvest JOE safeJoeTransfer(msg.sender, user .amount .mul(pool.accJoePerShare) .div(1e12) .sub(user.rewardDebt) ); } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(1e12); pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); if (_pid == 1) { stakedJoe = stakedJoe + _amount; } } function compound(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount > 0, "NO TOKENS"); UserInfo storage compUser = userInfo[1][msg.sender]; updatePool(_pid); uint256 rewardAmount = user .amount .mul(pool.accJoePerShare) .div(1e12) .sub(user.rewardDebt); compUser.amount = compUser.amount.add(rewardAmount); user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(1e12); stakedJoe = stakedJoe.add(rewardAmount); } function stake(address _user, uint256 _amount) external override returns(bool){ PoolInfo storage pool = poolInfo[1]; UserInfo storage user = userInfo[1][_user]; updatePool(1); if (user.amount > 0) { // Harvest JOE safeJoeTransfer(_user, user .amount .mul(pool.accJoePerShare) .div(1e12) .sub(user.rewardDebt) ); } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(1e12); pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); stakedJoe = stakedJoe + _amount; return true; } // 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); // Harvest JOE safeJoeTransfer(msg.sender, user.amount.mul(pool.accJoePerShare).div(1e12).sub( user.rewardDebt)); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accJoePerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount.mul(95).div(100)); pool.lpToken.safeTransfer(devAddr, _amount.mul(5).div(100)); if (_pid == 1) { stakedJoe = stakedJoe - _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); user.amount = 0; user.rewardDebt = 0; } // Safe joe transfer function, just in case if rounding error causes pool to not have enough JOEs. function safeJoeTransfer(address _to, uint256 _amount) internal { uint256 joeBal = joeERC20.balanceOf(address(this)); if (_amount > joeBal) { joeERC20.transfer(_to, joeBal.sub(stakedJoe)); } else { joeERC20.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devAddr) public { require(msg.sender == devAddr, "dev: wut?"); devAddr = _devAddr; } function setDevPercent(uint256 _newDevPercent) public onlyOwner { require( 0 <= _newDevPercent && _newDevPercent <= 980, "setDevPercent: invalid percent value" ); devPercent = _newDevPercent; } function setTvlApr(uint256[] memory _tvlArray) external onlyOwner { TvlAPR = _tvlArray; } function setTvlThresholds(uint256[] memory _tvlThresholdArray) external onlyOwner { TvlThresholds = _tvlThresholdArray; } function getjoePerSec() public view returns(uint256 amount ) { uint256 joeUsdValue = ((_uniswapRouter.getAmountsOut(1e18, pathForTVL))[2]).mul(1e12); uint256 lpInJoe = (((joeERC20.balanceOf(address(poolInfo[0].lpToken))).mul(2)).mul((poolInfo[0].lpToken.balanceOf(address(this))))).div(poolInfo[0].lpToken.totalSupply()); uint256 tvl = (joeUsdValue.mul(lpInJoe.add(stakedJoe))).div(1e18); for (uint256 i; i<TvlThresholds.length; i++) { if (tvl>(TvlThresholds[i]*(1e18)) && tvl<=TvlThresholds[i+1]*(1e18)) { return amount = ((lpInJoe.add(stakedJoe)).mul(TvlAPR[i])).div(3153600000); } } } function mintReserves(uint256 _amount) external onlyOwner { require(_amount <= availableReserves, "amount too high"); availableReserves = availableReserves - _amount; joe.mint(msg.sender, _amount); } }
62,653
265
// must try check pointing epoch first
_checkpointEpoch();
_checkpointEpoch();
41,717
9
// Allows the upgradeability owner to upgrade the current implementation of the proxyand delegatecall the new implementation for initialization. implementation_ representing the address of the new implementation to be set. data represents the msg.data to bet sent in the low level call. This parameter may include the functionsignature of the implementation to be called with the needed payload /
function upgradeToAndCall(address implementation_, bytes memory data) payable public onlyProxyOwner { upgradeTo(implementation_); (bool success,) = address(this).delegatecall(data); require(success, "Call failed after proxy upgrade"); }
function upgradeToAndCall(address implementation_, bytes memory data) payable public onlyProxyOwner { upgradeTo(implementation_); (bool success,) = address(this).delegatecall(data); require(success, "Call failed after proxy upgrade"); }
13,859
420
// Ensure the Safe has Fei currently boosting the Vault.
require(totalFeiBoostedForVault != 0, "NO_FEI_BOOSTED");
require(totalFeiBoostedForVault != 0, "NO_FEI_BOOSTED");
61,662
16
// Permissions on the pool.
Rights memory rights; rights.canPauseSwapping = true; rights.canChangeSwapFee = false; rights.canChangeWeights = true; rights.canAddRemoveTokens = false; rights.canWhitelistLPs = true; rights.canChangeCap = false;
Rights memory rights; rights.canPauseSwapping = true; rights.canChangeSwapFee = false; rights.canChangeWeights = true; rights.canAddRemoveTokens = false; rights.canWhitelistLPs = true; rights.canChangeCap = false;
40,156
1
// function getNTokenFromToken(address token) view external returns (address); function setNTokenToToken(address token, address ntoken) external;
function addNest(address miner, uint256 amount) external; function addNToken(address contributor, address ntoken, uint256 amount) external; function depositEth(address miner) external payable; function freezeEth(address miner, uint256 ethAmount) external; function unfreezeEth(address miner, uint256 ethAmount) external; function freezeNest(address miner, uint256 nestAmount) external;
function addNest(address miner, uint256 amount) external; function addNToken(address contributor, address ntoken, uint256 amount) external; function depositEth(address miner) external payable; function freezeEth(address miner, uint256 ethAmount) external; function unfreezeEth(address miner, uint256 ethAmount) external; function freezeNest(address miner, uint256 nestAmount) external;
17,390
1
// A plugin's metadata. name The unique name of the plugin.metadataURIThe URI where the metadata for the plugin lives.implementation The implementation smart contract address of the plugin. /
struct PluginMetadata { string name; string metadataURI; address implementation; }
struct PluginMetadata { string name; string metadataURI; address implementation; }
26,948
50
// return the name of the token. /
function name() public view returns(string) { return _name; }
function name() public view returns(string) { return _name; }
39,783
57
// Converts a signed int256 into an unsigned uint256. Requirements: - input must be greater than or equal to 0. /
function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); }
function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); }
25,834
5
// If opened for more than 45 days, restartthe poll again
if ((now - lastVotedAt) > 35 days) { lastVotedAt = now - 5 days; }
if ((now - lastVotedAt) > 35 days) { lastVotedAt = now - 5 days; }
48,416
68
// Submit a batch of commits in a single transaction. Using `encryptedVote` is optional. If included then commitment is emitted in an event.Look at `project-root/common/Constants.js` for the tested maximum number ofcommitments that can fit in one transaction. commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. /
function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } }
function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } }
18,906
31
// Call the arbitrageur's execute arbitrage method.
return IArbitrage(msg.sender).executeArbitrage(token, amount, dest, data);
return IArbitrage(msg.sender).executeArbitrage(token, amount, dest, data);
68,322
77
// check neighbors on bottom of area
_tokenId = soldUnits[i][upY]; if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); }
_tokenId = soldUnits[i][upY]; if (_tokenId != 0) { if (!neighbours[tokenId][_tokenId]) { neighbours[tokenId][_tokenId] = true; neighboursArea[tokenId].push(_tokenId); }
70,020
121
// Map root token to child token _rootToken Token address on the root chain _childToken Token address on the child chain _isERC721 Is the token being mapped ERC721 /
function mapToken( address _rootToken, address _childToken, bool _isERC721
function mapToken( address _rootToken, address _childToken, bool _isERC721
22,727
331
// Internal function to mint a new tokenReverts if the given token ID already exists to The address that will own the minted token tokenId uint256 ID of the token to be minted /
function _mint(address to, uint256 tokenId) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); }
function _mint(address to, uint256 tokenId) internal { require(to != address(0)); require(!_exists(tokenId)); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); }
63,171
14
// ============ External Functions ============ //Starts the RNG Request, ends the current auction, and stores the reward fraction to be allocated to the recipient. Will revert if the current auction has already been completed or expired. If the RNG service expects the fee to already be in possession, the caller should not call this function directly and should instead call a helper function that transfers the funds to the RNG service before calling this function. If there is a pending RNG service (see _nextRng), it will be swapped in before the auction is completed. _rewardRecipient Address that will receive the auction
function startRngRequest(address _rewardRecipient) external { if (_rewardRecipient == address(0)) revert RewardRecipientIsZero(); if (!_canStartNextSequence()) revert CannotStartNextSequence(); RNGInterface rng = _nextRng; uint64 _auctionElapsedTimeSeconds = _auctionElapsedTime(); if (_auctionElapsedTimeSeconds > auctionDuration) revert AuctionExpired(); (address _feeToken, uint256 _requestFee) = rng.getRequestFee(); if ( _feeToken != address(0) && _requestFee > 0 && IERC20(_feeToken).allowance(address(this), address(rng)) < _requestFee ) { /** * Set approval for the RNG service to take the request fee to support RNG services * that pull funds from the caller. * NOTE: Not compatible with safeApprove or safeIncreaseAllowance. */ IERC20(_feeToken).approve(address(rng), _requestFee); } (uint32 rngRequestId,) = rng.requestRandomNumber(); uint32 sequenceId = _openSequenceId(); UD2x18 rewardFraction = _currentFractionalReward(); _lastAuction = RngAuctionResult({ recipient: _rewardRecipient, rewardFraction: rewardFraction, sequenceId: sequenceId, rng: rng, rngRequestId: rngRequestId }); emit RngAuctionCompleted( msg.sender, _rewardRecipient, sequenceId, rng, rngRequestId, _auctionElapsedTimeSeconds, rewardFraction ); }
function startRngRequest(address _rewardRecipient) external { if (_rewardRecipient == address(0)) revert RewardRecipientIsZero(); if (!_canStartNextSequence()) revert CannotStartNextSequence(); RNGInterface rng = _nextRng; uint64 _auctionElapsedTimeSeconds = _auctionElapsedTime(); if (_auctionElapsedTimeSeconds > auctionDuration) revert AuctionExpired(); (address _feeToken, uint256 _requestFee) = rng.getRequestFee(); if ( _feeToken != address(0) && _requestFee > 0 && IERC20(_feeToken).allowance(address(this), address(rng)) < _requestFee ) { /** * Set approval for the RNG service to take the request fee to support RNG services * that pull funds from the caller. * NOTE: Not compatible with safeApprove or safeIncreaseAllowance. */ IERC20(_feeToken).approve(address(rng), _requestFee); } (uint32 rngRequestId,) = rng.requestRandomNumber(); uint32 sequenceId = _openSequenceId(); UD2x18 rewardFraction = _currentFractionalReward(); _lastAuction = RngAuctionResult({ recipient: _rewardRecipient, rewardFraction: rewardFraction, sequenceId: sequenceId, rng: rng, rngRequestId: rngRequestId }); emit RngAuctionCompleted( msg.sender, _rewardRecipient, sequenceId, rng, rngRequestId, _auctionElapsedTimeSeconds, rewardFraction ); }
9,501
2
// Returns the number of decimals used to get its user representation./ For example, if `decimals` equals `2`, a balance of `505` tokens should/ be displayed to a user as `5,05` (`505 / 102`).// Tokens usually opt for a value of 18, imitating the relationship between
/// Ether and Wei. This is the value {ERC20} uses, unless this function is /// overridden; /// /// NOTE: This information is only used for _display_ purposes: it in /// no way affects any of the arithmetic of the contract, including /// {IERC20-balanceOf} and {IERC20-transfer}. function decimals() public view override returns (uint8) { return _dec; }
/// Ether and Wei. This is the value {ERC20} uses, unless this function is /// overridden; /// /// NOTE: This information is only used for _display_ purposes: it in /// no way affects any of the arithmetic of the contract, including /// {IERC20-balanceOf} and {IERC20-transfer}. function decimals() public view override returns (uint8) { return _dec; }
48,205
42
// Returns the subtraction of two signed integers, reverting onoverflow. Counterpart to Solidity's `-` operator. Requirements: - Subtraction cannot overflow. /
function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; }
function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; }
1,030
11
// Writes to state
function setLB(uint8 length, uint8 breath) public { l = length; b = breath; }
function setLB(uint8 length, uint8 breath) public { l = length; b = breath; }
7,355
1
// Token Details
uint8 constant private decimal = 18; uint256 constant private maxSupply = 1_000_000_000 * (10 ** decimal);
uint8 constant private decimal = 18; uint256 constant private maxSupply = 1_000_000_000 * (10 ** decimal);
27,801
61
// mint timelocked tokens /
function mintTimelocked(address _to, uint256 _amount, uint256 _releaseTime)
function mintTimelocked(address _to, uint256 _amount, uint256 _releaseTime)
46,600
95
// solhint-disable-next-line not-rely-on-time
return block.timestamp;
return block.timestamp;
3,237
1
// Adds the provided identifier as a supported identifier. Price requests using this identifier will succeed after this call. identifier bytes32 encoding of the string identifier. Eg: BTC/USD. /
function addSupportedIdentifier(bytes32 identifier) external;
function addSupportedIdentifier(bytes32 identifier) external;
29,960
23
// remove last element
delete protocols[protocols.length - 1]; protocols.pop();
delete protocols[protocols.length - 1]; protocols.pop();
21,196
11
// Adds a new module. The `init` method of the module/will be called with `address(this)` as the parameter./This method must throw if the module has already been added./_module The module's address.
function addModule(address _module) external;
function addModule(address _module) external;
25,543
28
// If compoundRate is greater than aaveRate, and the current location of user funds is not in compound, then we transfer funds.
_withdrawFromAave(); balance = dai.balanceOf(address(this)); _depositToCompound(balance);
_withdrawFromAave(); balance = dai.balanceOf(address(this)); _depositToCompound(balance);
18,736
21
// call vault to calculate and pay fees vault Vault address profit Profit /
function _payFeesAndTransfer( IVault vault, uint256 profit
function _payFeesAndTransfer( IVault vault, uint256 profit
72,066
102
// make sure name fees paid
require (msg.value >= registrationFee_, "You have to pay the name fee.(10 finney)");
require (msg.value >= registrationFee_, "You have to pay the name fee.(10 finney)");
1,999
21
// 发行锚定币
uint256 issued = amount.div(token.denominator).mul(token.numerator); token.output.mint(msg.sender, issued);
uint256 issued = amount.div(token.denominator).mul(token.numerator); token.output.mint(msg.sender, issued);
14,845
3
// Events // Functions /
) VRFConsumerBaseV2(vrfCoordinatorV2) { i_vrfCoordinator = VRFCoordinatorV2Interface(vrfCoordinatorV2); i_gasLane = gasLane; i_interval = interval; i_subscriptionId = subscriptionId; i_entranceFee = entranceFee; s_raffleState = RaffleState.OPEN; s_lastTimeStamp = block.timestamp; i_callbackGasLimit = callbackGasLimit; }
) VRFConsumerBaseV2(vrfCoordinatorV2) { i_vrfCoordinator = VRFCoordinatorV2Interface(vrfCoordinatorV2); i_gasLane = gasLane; i_interval = interval; i_subscriptionId = subscriptionId; i_entranceFee = entranceFee; s_raffleState = RaffleState.OPEN; s_lastTimeStamp = block.timestamp; i_callbackGasLimit = callbackGasLimit; }
27,740
305
// if already joined, move along
results[i] = uint(Error.NO_ERROR); continue;
results[i] = uint(Error.NO_ERROR); continue;
10,794
53
// Mark the token as redeemed.
redeemed[_tokenId] = true;
redeemed[_tokenId] = true;
23,784
227
// Splitter contract address
address payable splitter;
address payable splitter;
16,994
64
// ex oracle's callback function,process lottery
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { address userAddress = requestIdAndAddress[requestId]; require(userAddress != address(0), "the target order doesn't exist"); BlindOrder storage order = consumerOrders[requestId]; order.randomness = randomness; uint[] memory tokenIDsRecord = new uint[](order.amount); uint tokenSize = blindBoxSales[order.saleID].base.tokenIds.length; for (uint i = 0; i < order.amount; i++) { uint index = randomness % tokenSize; uint256 tokenId = blindBoxSales[order.saleID].base.tokenIds[index]; // call other contract use tokenId and sender address IERC721(blindBoxSales[order.saleID].base.contractAddress).safeTransferFrom( blindBoxSales[order.saleID].base.seller, requestIdAndAddress[requestId], tokenId); //for event tokenIDsRecord[i] = tokenId; //array tail -> array[index] blindBoxSales[order.saleID].base.tokenIds[index] = blindBoxSales[order.saleID].base.tokenIds[tokenSize-1]; tokenSize--; //array tail pop blindBoxSales[order.saleID].base.tokenIds.pop(); } // remove consumerOrders and requestIdAndAddress delete requestIdAndAddress[requestId]; delete consumerOrders[requestId]; uint remainNftTotal = blindBoxSales[order.saleID].base.remainNftTotal; address payTokenAddress = blindBoxSales[order.saleID].base.payTokenAddress; uint totalPayment = blindBoxSales[order.saleID].base.price.mul(order.amount); emit PurchaseSuccess(order.saleID,userAddress,remainNftTotal,payTokenAddress,totalPayment,requestId, randomness,tokenIDsRecord); }
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { address userAddress = requestIdAndAddress[requestId]; require(userAddress != address(0), "the target order doesn't exist"); BlindOrder storage order = consumerOrders[requestId]; order.randomness = randomness; uint[] memory tokenIDsRecord = new uint[](order.amount); uint tokenSize = blindBoxSales[order.saleID].base.tokenIds.length; for (uint i = 0; i < order.amount; i++) { uint index = randomness % tokenSize; uint256 tokenId = blindBoxSales[order.saleID].base.tokenIds[index]; // call other contract use tokenId and sender address IERC721(blindBoxSales[order.saleID].base.contractAddress).safeTransferFrom( blindBoxSales[order.saleID].base.seller, requestIdAndAddress[requestId], tokenId); //for event tokenIDsRecord[i] = tokenId; //array tail -> array[index] blindBoxSales[order.saleID].base.tokenIds[index] = blindBoxSales[order.saleID].base.tokenIds[tokenSize-1]; tokenSize--; //array tail pop blindBoxSales[order.saleID].base.tokenIds.pop(); } // remove consumerOrders and requestIdAndAddress delete requestIdAndAddress[requestId]; delete consumerOrders[requestId]; uint remainNftTotal = blindBoxSales[order.saleID].base.remainNftTotal; address payTokenAddress = blindBoxSales[order.saleID].base.payTokenAddress; uint totalPayment = blindBoxSales[order.saleID].base.price.mul(order.amount); emit PurchaseSuccess(order.saleID,userAddress,remainNftTotal,payTokenAddress,totalPayment,requestId, randomness,tokenIDsRecord); }
2,109
134
// Move the pointer 1 byte leftwards to point to an empty character slot.
ptr := sub(ptr, 1)
ptr := sub(ptr, 1)
5,276
0
// The Scam Seal Token is intended to mark an address as SCAM.this token is used by the contract ScamSeal defined bellowa false ERC20 token, where transfers can be done only by the creator of the token.
string public constant name = "SCAM Seal Token"; string public constant symbol = "SCAMSEAL"; uint8 public constant decimals = 0; uint256 public totalSupply;
string public constant name = "SCAM Seal Token"; string public constant symbol = "SCAMSEAL"; uint8 public constant decimals = 0; uint256 public totalSupply;
31,824
14
// Gets function signature from _data _data Passed data /
function getSig(bytes memory _data) internal pure returns(bytes4 sig) { uint len = _data.length < 4 ? _data.length : 4; for (uint256 i = 0; i < len; i++) { sig |= bytes4(_data[i] & 0xFF) >> (i * 8); } return sig; }
function getSig(bytes memory _data) internal pure returns(bytes4 sig) { uint len = _data.length < 4 ? _data.length : 4; for (uint256 i = 0; i < len; i++) { sig |= bytes4(_data[i] & 0xFF) >> (i * 8); } return sig; }
34,843
89
// epoch id starting from 1
return startTime.add((t.sub(1)).mul(epochDuration));
return startTime.add((t.sub(1)).mul(epochDuration));
8,199
127
// Deposit staked tokens and collect reward tokens (if any) _amount: amount to withdraw (in rewardToken) /
function deposit(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; _updatePool(); if (user.amount > 0) { uint256 pending = _getUserPendingReward(user.amount, user.rewardDebt); if (pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); } } if (_amount > 0) { stakedTokenPop.safeTransferFrom(address(msg.sender), address(this), _amount); uint256 stakedAmount = _burnAndReturnStakedAmount(_amount); user.amount = user.amount.add(stakedAmount); emit Deposit(msg.sender, stakedAmount); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR_DIV); }
function deposit(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; _updatePool(); if (user.amount > 0) { uint256 pending = _getUserPendingReward(user.amount, user.rewardDebt); if (pending > 0) { rewardToken.safeTransfer(address(msg.sender), pending); } } if (_amount > 0) { stakedTokenPop.safeTransferFrom(address(msg.sender), address(this), _amount); uint256 stakedAmount = _burnAndReturnStakedAmount(_amount); user.amount = user.amount.add(stakedAmount); emit Deposit(msg.sender, stakedAmount); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR_DIV); }
77,845
51
// Increase the time until expiration. Only the owner can perform this._newExpiration New date time in seconds when timelock expires./
function increaseTime(uint _newExpiration) public onlyOwner() { require(_newExpiration > expiration, 'can only increase expiration'); expiration = _newExpiration; emit IncreaseTime(_newExpiration); }
function increaseTime(uint _newExpiration) public onlyOwner() { require(_newExpiration > expiration, 'can only increase expiration'); expiration = _newExpiration; emit IncreaseTime(_newExpiration); }
73,496
688
// Calculate denominator for row 2080: x - g^2080z.
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xec0))) mstore(add(productsPtr, 0xb00), partialProduct) mstore(add(valuesPtr, 0xb00), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xec0))) mstore(add(productsPtr, 0xb00), partialProduct) mstore(add(valuesPtr, 0xb00), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
77,836