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
23
// Creates `amount` tokens and assigns them to `account`, increasingthe total supply.
* Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), 'BEP20: mint to the zero address'); uint256 predictedTotal = _totalMinted.add(amount); if (predictedTotal >= _maxMintable) { amount = _maxMintable.sub(_totalMinted); } require(_totalMinted <= _maxMintable , 'BEP20: Max Amount minted reached'); require(_totalSupply.add(amount) <= _maxSupply, 'Amount Exceeds Max Supply'); _totalSupply = _totalSupply.add(amount); _totalMinted = _totalMinted.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
* Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), 'BEP20: mint to the zero address'); uint256 predictedTotal = _totalMinted.add(amount); if (predictedTotal >= _maxMintable) { amount = _maxMintable.sub(_totalMinted); } require(_totalMinted <= _maxMintable , 'BEP20: Max Amount minted reached'); require(_totalSupply.add(amount) <= _maxSupply, 'Amount Exceeds Max Supply'); _totalSupply = _totalSupply.add(amount); _totalMinted = _totalMinted.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
35,934
11
// Native DIGG has 100% emissions through Faucet, LP has 50% emissions
uint256 fragments = digg_emissions_faucet[i]; if (i != 0) { fragments = digg_emissions_faucet[i] / 2; }
uint256 fragments = digg_emissions_faucet[i]; if (i != 0) { fragments = digg_emissions_faucet[i] / 2; }
13,536
134
// See {IAdminControl-isAdmin}. /
function isAdmin(address admin) public override view returns (bool) { return (owner() == admin || _admins.contains(admin)); }
function isAdmin(address admin) public override view returns (bool) { return (owner() == admin || _admins.contains(admin)); }
37,019
34
// a facade for prices fetch from oracles
interface LnPrices { // get price for a currency function getPrice(bytes32 currencyName) external view returns (uint); // get price and updated time for a currency function getPriceAndUpdatedTime(bytes32 currencyName) external view returns (uint price, uint time); // is the price is stale function isStale(bytes32 currencyName) external view returns (bool); // the defined stale time function stalePeriod() external view returns (uint); // exchange amount of source currenty for some dest currency, also get source and dest curreny price function exchange( bytes32 sourceName, uint sourceAmount, bytes32 destName ) external view returns (uint); // exchange amount of source currenty for some dest currency function exchangeAndPrices( bytes32 sourceName, uint sourceAmount, bytes32 destName ) external view returns ( uint value, uint sourcePrice, uint destPrice ); // price names function LUSD() external view returns (bytes32); function LINA() external view returns (bytes32); }
interface LnPrices { // get price for a currency function getPrice(bytes32 currencyName) external view returns (uint); // get price and updated time for a currency function getPriceAndUpdatedTime(bytes32 currencyName) external view returns (uint price, uint time); // is the price is stale function isStale(bytes32 currencyName) external view returns (bool); // the defined stale time function stalePeriod() external view returns (uint); // exchange amount of source currenty for some dest currency, also get source and dest curreny price function exchange( bytes32 sourceName, uint sourceAmount, bytes32 destName ) external view returns (uint); // exchange amount of source currenty for some dest currency function exchangeAndPrices( bytes32 sourceName, uint sourceAmount, bytes32 destName ) external view returns ( uint value, uint sourcePrice, uint destPrice ); // price names function LUSD() external view returns (bytes32); function LINA() external view returns (bytes32); }
9,808
7
// Swap with attribute at the end of the array
requiredAttributes[index] = requiredAttributes[requiredAttributes.length - 1]; delete requiredAttributes[requiredAttributes.length - 1]; emit RemovedRequiredAttribute(_attributeName);
requiredAttributes[index] = requiredAttributes[requiredAttributes.length - 1]; delete requiredAttributes[requiredAttributes.length - 1]; emit RemovedRequiredAttribute(_attributeName);
7,477
17
//
function setFaucetTokenMap(uint256 _assetID, address _token) external { tokenMap[_assetID] = _token; assetIDs.push(_assetID); }
function setFaucetTokenMap(uint256 _assetID, address _token) external { tokenMap[_assetID] = _token; assetIDs.push(_assetID); }
6,824
6
// Public address returned by ecrecover function
address recAddress;
address recAddress;
10,481
26
// extend a lock with a new unlock date, _index and _lockID ensure the correct lock is changedthis prevents errors when a user performs multiple tx per block possibly with varying gas prices /
function relock (address _lpToken, uint256 _index, uint256 _lockID, uint256 _unlock_date) external nonReentrant { require(_unlock_date < 10000000000, 'TIMESTAMP INVALID'); // prevents errors when timestamp entered in milliseconds uint256 lockID = users[msg.sender].locksForToken[_lpToken][_index]; TokenLock storage userLock = tokenLocks[_lpToken][lockID]; require(lockID == _lockID && userLock.owner == msg.sender, 'LOCK MISMATCH'); // ensures correct lock is affected require(userLock.unlockDate < _unlock_date, 'UNLOCK BEFORE'); uint256 liquidityFee = userLock.amount.mul(gFees.liquidityFee).div(1000); uint256 amountLocked = userLock.amount.sub(liquidityFee); userLock.amount = amountLocked; userLock.unlockDate = _unlock_date; // send univ2 fee to dev address TransferHelper.safeTransfer(_lpToken, devaddr, liquidityFee); }
function relock (address _lpToken, uint256 _index, uint256 _lockID, uint256 _unlock_date) external nonReentrant { require(_unlock_date < 10000000000, 'TIMESTAMP INVALID'); // prevents errors when timestamp entered in milliseconds uint256 lockID = users[msg.sender].locksForToken[_lpToken][_index]; TokenLock storage userLock = tokenLocks[_lpToken][lockID]; require(lockID == _lockID && userLock.owner == msg.sender, 'LOCK MISMATCH'); // ensures correct lock is affected require(userLock.unlockDate < _unlock_date, 'UNLOCK BEFORE'); uint256 liquidityFee = userLock.amount.mul(gFees.liquidityFee).div(1000); uint256 amountLocked = userLock.amount.sub(liquidityFee); userLock.amount = amountLocked; userLock.unlockDate = _unlock_date; // send univ2 fee to dev address TransferHelper.safeTransfer(_lpToken, devaddr, liquidityFee); }
26,510
8
// org = address_med_map[org_address];
address_med_map[org_address] = org; exists_address_med_map[org_address] = true;
address_med_map[org_address] = org; exists_address_med_map[org_address] = true;
2,678
2
// Constant used by buyTokens as part of the cost <-> tokens conversion. 18 for ETH -> WEI, TOKEN_DECIMALS (18 for JSE Coin Token), 3 for the K in tokensPerKEther.
uint256 public constant PURCHASE_DIVIDER = 10**(uint256(18) - TOKEN_DECIMALS + 3);
uint256 public constant PURCHASE_DIVIDER = 10**(uint256(18) - TOKEN_DECIMALS + 3);
29,980
121
// read all of the details about an upkeep /
function getUpkeep( uint256 id ) external view returns ( address target, uint32 executeGas, bytes memory checkData,
function getUpkeep( uint256 id ) external view returns ( address target, uint32 executeGas, bytes memory checkData,
9,925
1
// Events
event Harvested(uint256 _profit, uint256 _loss, uint256 _debtPayment, uint256 _debtOutstanding); event StrategistUpdated(address _newStrategist); event KeeperUpdated(address _newKeeper); event MinReportDelayUpdated(uint256 _delay); event MaxReportDelayUpdated(uint256 _delay); event ProfitFactorUpdated(uint256 _profitFactor); event DebtThresholdUpdated(uint256 _debtThreshold); event EmergencyExitEnabled();
event Harvested(uint256 _profit, uint256 _loss, uint256 _debtPayment, uint256 _debtOutstanding); event StrategistUpdated(address _newStrategist); event KeeperUpdated(address _newKeeper); event MinReportDelayUpdated(uint256 _delay); event MaxReportDelayUpdated(uint256 _delay); event ProfitFactorUpdated(uint256 _profitFactor); event DebtThresholdUpdated(uint256 _debtThreshold); event EmergencyExitEnabled();
33,831
18
// not sure what was returned: dont mark as success
default { }
default { }
20,361
170
// Set Presale
function setPresale(bool _state) public onlyOwner { presale = _state; }
function setPresale(bool _state) public onlyOwner { presale = _state; }
18,383
4
// Starts at index 0.
mapping (uint256 => Candlestick) public prices;
mapping (uint256 => Candlestick) public prices;
25,759
34
// Stores assets within the contract.
function createOrAddBundle( Token[] calldata _contents, uint256[] calldata _numOfRewardUnits, uint256 packId, uint256 amountPerOpen, bool isUpdate
function createOrAddBundle( Token[] calldata _contents, uint256[] calldata _numOfRewardUnits, uint256 packId, uint256 amountPerOpen, bool isUpdate
34,792
22
// Add the address to the list if it's not in there yet
if (preMintAllowance[addr] == 0) { preMintAddresses.push(addr); }
if (preMintAllowance[addr] == 0) { preMintAddresses.push(addr); }
460
18
// GraphToken contract This is the implementation of the ERC20 Graph Token.The implementation exposes a Permit() function to allow for a spender to send a signed messageand approve funds to a spender following EIP2612 to make integration with other contracts easier. The token is initially owned by the deployer address that can mint tokens to create the initialdistribution. For convenience, an initial supply can be passed in the constructor that will beassigned to the deployer. The governor can add the RewardsManager contract to mint indexing rewards./
contract GraphToken is Governed, ERC20, ERC20Burnable { using SafeMath for uint256; // -- EIP712 -- // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#definition-of-domainseparator bytes32 private constant DOMAIN_TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" ); bytes32 private constant DOMAIN_NAME_HASH = keccak256("Graph Token"); bytes32 private constant DOMAIN_VERSION_HASH = keccak256("0"); bytes32 private constant DOMAIN_SALT = 0x51f3d585afe6dfeb2af01bba0889a36c1db03beec88c6a4d0c53817069026afa; // Randomly generated salt bytes32 private constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); // -- State -- bytes32 private DOMAIN_SEPARATOR; mapping(address => bool) private _minters; mapping(address => uint256) public nonces; // -- Events -- event MinterAdded(address indexed account); event MinterRemoved(address indexed account); modifier onlyMinter() { require(isMinter(msg.sender), "Only minter can call"); _; } /** * @dev Graph Token Contract Constructor. * @param _initialSupply Initial supply of GRT */ constructor(uint256 _initialSupply) ERC20("Graph Token", "GRT") { Governed._initialize(msg.sender); // The Governor has the initial supply of tokens _mint(msg.sender, _initialSupply); // The Governor is the default minter _addMinter(msg.sender); // EIP-712 domain separator DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPE_HASH, DOMAIN_NAME_HASH, DOMAIN_VERSION_HASH, _getChainID(), address(this), DOMAIN_SALT ) ); } /** * @dev Approve token allowance by validating a message signed by the holder. * @param _owner Address of the token holder * @param _spender Address of the approved spender * @param _value Amount of tokens to approve the spender * @param _deadline Expiration time of the signed permit * @param _v Signature version * @param _r Signature r value * @param _s Signature s value */ function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, _owner, _spender, _value, nonces[_owner], _deadline ) ) ) ); nonces[_owner] = nonces[_owner].add(1); address recoveredAddress = ECDSA.recover(digest, abi.encodePacked(_r, _s, _v)); require(_owner == recoveredAddress, "GRT: invalid permit"); require(_deadline == 0 || block.timestamp <= _deadline, "GRT: expired permit"); _approve(_owner, _spender, _value); } /** * @dev Add a new minter. * @param _account Address of the minter */ function addMinter(address _account) external onlyGovernor { _addMinter(_account); } /** * @dev Remove a minter. * @param _account Address of the minter */ function removeMinter(address _account) external onlyGovernor { _removeMinter(_account); } /** * @dev Renounce to be a minter. */ function renounceMinter() external { _removeMinter(msg.sender); } /** * @dev Mint new tokens. * @param _to Address to send the newly minted tokens * @param _amount Amount of tokens to mint */ function mint(address _to, uint256 _amount) external onlyMinter { _mint(_to, _amount); } /** * @dev Return if the `_account` is a minter or not. * @param _account Address to check * @return True if the `_account` is minter */ function isMinter(address _account) public view returns (bool) { return _minters[_account]; } /** * @dev Add a new minter. * @param _account Address of the minter */ function _addMinter(address _account) private { _minters[_account] = true; emit MinterAdded(_account); } /** * @dev Remove a minter. * @param _account Address of the minter */ function _removeMinter(address _account) private { _minters[_account] = false; emit MinterRemoved(_account); } /** * @dev Get the running network chain ID. * @return The chain ID */ function _getChainID() private pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } }
contract GraphToken is Governed, ERC20, ERC20Burnable { using SafeMath for uint256; // -- EIP712 -- // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#definition-of-domainseparator bytes32 private constant DOMAIN_TYPE_HASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" ); bytes32 private constant DOMAIN_NAME_HASH = keccak256("Graph Token"); bytes32 private constant DOMAIN_VERSION_HASH = keccak256("0"); bytes32 private constant DOMAIN_SALT = 0x51f3d585afe6dfeb2af01bba0889a36c1db03beec88c6a4d0c53817069026afa; // Randomly generated salt bytes32 private constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); // -- State -- bytes32 private DOMAIN_SEPARATOR; mapping(address => bool) private _minters; mapping(address => uint256) public nonces; // -- Events -- event MinterAdded(address indexed account); event MinterRemoved(address indexed account); modifier onlyMinter() { require(isMinter(msg.sender), "Only minter can call"); _; } /** * @dev Graph Token Contract Constructor. * @param _initialSupply Initial supply of GRT */ constructor(uint256 _initialSupply) ERC20("Graph Token", "GRT") { Governed._initialize(msg.sender); // The Governor has the initial supply of tokens _mint(msg.sender, _initialSupply); // The Governor is the default minter _addMinter(msg.sender); // EIP-712 domain separator DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPE_HASH, DOMAIN_NAME_HASH, DOMAIN_VERSION_HASH, _getChainID(), address(this), DOMAIN_SALT ) ); } /** * @dev Approve token allowance by validating a message signed by the holder. * @param _owner Address of the token holder * @param _spender Address of the approved spender * @param _value Amount of tokens to approve the spender * @param _deadline Expiration time of the signed permit * @param _v Signature version * @param _r Signature r value * @param _s Signature s value */ function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, _owner, _spender, _value, nonces[_owner], _deadline ) ) ) ); nonces[_owner] = nonces[_owner].add(1); address recoveredAddress = ECDSA.recover(digest, abi.encodePacked(_r, _s, _v)); require(_owner == recoveredAddress, "GRT: invalid permit"); require(_deadline == 0 || block.timestamp <= _deadline, "GRT: expired permit"); _approve(_owner, _spender, _value); } /** * @dev Add a new minter. * @param _account Address of the minter */ function addMinter(address _account) external onlyGovernor { _addMinter(_account); } /** * @dev Remove a minter. * @param _account Address of the minter */ function removeMinter(address _account) external onlyGovernor { _removeMinter(_account); } /** * @dev Renounce to be a minter. */ function renounceMinter() external { _removeMinter(msg.sender); } /** * @dev Mint new tokens. * @param _to Address to send the newly minted tokens * @param _amount Amount of tokens to mint */ function mint(address _to, uint256 _amount) external onlyMinter { _mint(_to, _amount); } /** * @dev Return if the `_account` is a minter or not. * @param _account Address to check * @return True if the `_account` is minter */ function isMinter(address _account) public view returns (bool) { return _minters[_account]; } /** * @dev Add a new minter. * @param _account Address of the minter */ function _addMinter(address _account) private { _minters[_account] = true; emit MinterAdded(_account); } /** * @dev Remove a minter. * @param _account Address of the minter */ function _removeMinter(address _account) private { _minters[_account] = false; emit MinterRemoved(_account); } /** * @dev Get the running network chain ID. * @return The chain ID */ function _getChainID() private pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } }
39,361
145
// Initializing Auction Setup Stage
stage = Stages.AuctionSetUp; emit Setup(_etherPrice,_hardCap,_ceiling,_floor,_bonusThreshold,_bonusPercent);
stage = Stages.AuctionSetUp; emit Setup(_etherPrice,_hardCap,_ceiling,_floor,_bonusThreshold,_bonusPercent);
37,224
306
// effect: increment the user's claimedAmount
redemptions[msg.sender][cToken] += cTokenAmount; uint256 baseTokenAmountReceived = previewRedeem(cToken, cTokenAmount);
redemptions[msg.sender][cToken] += cTokenAmount; uint256 baseTokenAmountReceived = previewRedeem(cToken, cTokenAmount);
4,246
1
// 18 Decimals
string private constant nftSymbol = "SNLOT"; string private constant nftName = "Snx Lottery Ticket"; uint16 private constant maxTicketsPerPurchase = 100;
string private constant nftSymbol = "SNLOT"; string private constant nftName = "Snx Lottery Ticket"; uint16 private constant maxTicketsPerPurchase = 100;
29,103
6
// queried by others ({ERC165Checker}). For an implementation, see {ERC165}. /Returns true if this contract implements the interface defined by `interfaceId`. See the corresponding to learn more about how these ids are created. This function call must use less than 30 000 gas./
function supportsInterface(bytes4 interfaceId) external view returns (bool);
function supportsInterface(bytes4 interfaceId) external view returns (bool);
85,832
0
// injecter l'address du token Dai Γ  utiliser
dai = IERC20(daiAddress);
dai = IERC20(daiAddress);
19,553
158
// function execute(bytes memory _code, bytes memory _data) public payable virtual returns (address, bytes32);
function execute(address _target, bytes memory _data) public payable virtual returns (bytes32); function setCache(address _cacheAddr) public payable virtual returns (bool); function owner() public view virtual returns (address);
function execute(address _target, bytes memory _data) public payable virtual returns (bytes32); function setCache(address _cacheAddr) public payable virtual returns (bool); function owner() public view virtual returns (address);
6,043
1
// Chainlink can return prices for stablecoins that differs from 1 USD by a larger percentage than stableSwapFeeBasisPoints we use strictStableTokens to cap the price to 1 USD this allows us to configure stablecoins like DAI as being a stableToken while not being a strictStableToken
mapping (address => bool) public strictStableTokens; mapping (address => uint256) public override adjustmentBasisPoints; mapping (address => bool) public override isAdjustmentAdditive; mapping (address => uint256) public lastAdjustmentTimings;
mapping (address => bool) public strictStableTokens; mapping (address => uint256) public override adjustmentBasisPoints; mapping (address => bool) public override isAdjustmentAdditive; mapping (address => uint256) public lastAdjustmentTimings;
3,413
18
// if _user has no _userWeekCursor with GrassHouse yet then we need to perform binary search
_userEpoch = _findTimestampUserEpoch(_user, _startWeekCursor, _maxUserEpoch);
_userEpoch = _findTimestampUserEpoch(_user, _startWeekCursor, _maxUserEpoch);
19,112
30
// Emit an Approval event
emit Approval(owner, spender, amount);
emit Approval(owner, spender, amount);
26,406
133
// Gets the current chain ID/ return chainId The current chain ID
function get() internal pure returns (uint256 chainId) { assembly { chainId := chainid() } }
function get() internal pure returns (uint256 chainId) { assembly { chainId := chainid() } }
18,704
26
// Validate token id (must be less than or equal to total tokens amount)/_tokenId Token id/ return bool flag that indicates if token id is less than or equal to total tokens amount
function isValidTokenId(uint16 _tokenId) external view returns (bool) { return _tokenId <= totalTokens; }
function isValidTokenId(uint16 _tokenId) external view returns (bool) { return _tokenId <= totalTokens; }
10,930
189
// SIP-120 Atomic exchanges max allowed volume per block for atomic exchanges
function atomicMaxVolumePerBlock() external view returns (uint) { return getAtomicMaxVolumePerBlock(); }
function atomicMaxVolumePerBlock() external view returns (uint) { return getAtomicMaxVolumePerBlock(); }
48,983
101
// We return that we released 'minOutputUnderlying' and the number of bonds that preserves the reserve ratio
amountsReleased[baseIndex] = minOutputUnderlying; amountsReleased[bondIndex] = minOutputUnderlying.divDown( underlyingPerBond );
amountsReleased[baseIndex] = minOutputUnderlying; amountsReleased[bondIndex] = minOutputUnderlying.divDown( underlyingPerBond );
77,464
2
// create a smart wallet
function createSmartWallet() view internal returns (address) { return payable(msg.sender); // return normal address }
function createSmartWallet() view internal returns (address) { return payable(msg.sender); // return normal address }
17,043
93
// Token that serves as a reserve for YAM
address public reserveToken; address public gov; address public pendingGov; address public rebaser; address public yamAddress;
address public reserveToken; address public gov; address public pendingGov; address public rebaser; address public yamAddress;
28,869
205
// FairLaunch is a smart contract for distributing SOMMAI by asking user to stake the ERC20-based token.
contract FairLaunch is IFairLaunch, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many Staking tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 bonusDebt; // Last block that user exec something to the pool. address fundedBy; // Funded by who? // // We do some fancy math here. Basically, any point in time, the amount of SOMMAI // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSommaiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws Staking tokens to a pool. Here's what happens: // 1. The pool's `accSommaiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { address stakeToken; // Address of Staking token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SOMMAI to distribute per block. uint256 lastRewardBlock; // Last block number that SOMMAI distribution occurs. uint256 accSommaiPerShare; // Accumulated SOMMAI per share, times 1e12. See below. uint256 accSommaiPerShareTilBonusEnd; // Accumated SOMMAI per share until Bonus End. } // The Sommai TOKEN! SommaiToken public sommai; // Dev address. address public devaddr; // SOMMAI tokens created per block. uint256 public sommaiPerBlock; // Bonus muliplier for early sommai makers. uint256 public bonusMultiplier; // Block number when bonus SOMMAI period ends. uint256 public bonusEndBlock; // Bonus lock-up in BPS uint256 public bonusLockUpBps; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes Staking tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; // The block number when SOMMAI mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( SommaiToken _sommai, address _devaddr, uint256 _sommaiPerBlock, uint256 _startBlock, uint256 _bonusLockupBps, uint256 _bonusEndBlock ) public { bonusMultiplier = 0; totalAllocPoint = 0; sommai = _sommai; devaddr = _devaddr; sommaiPerBlock = _sommaiPerBlock; bonusLockUpBps = _bonusLockupBps; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } /* β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ•—β€ƒβ€ƒβ–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ•‘β€ƒβ€ƒβ–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β•β•β•β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β–ˆβ–ˆβ–ˆβ–ˆβ•”β–ˆβ–ˆβ•‘β€ƒβ€ƒβ•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•”β•β•β•β•β–‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘β€ƒβ€ƒβ–‘β•šβ•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–ˆβ–ˆβ•”β•β•β•β–‘β–‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–‘β•šβ•β•β–‘β–ˆβ–ˆβ•‘β€ƒβ€ƒβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘ β•šβ•β•β–‘β–‘β–‘β–‘β–‘β•šβ•β•β–‘β–‘β•šβ•β•β•šβ•β•β–‘β–‘β•šβ•β•β•šβ•β•β–‘β–‘β•šβ•β•β•šβ•β•β–‘β–‘β–‘β–‘β–‘β•šβ•β•β€ƒβ€ƒβ•šβ•β•β•β•β•β•β–‘β•šβ•β•β•β•β•β•β•β–‘β–‘β–‘β•šβ•β•β–‘β–‘β–‘β–‘β–‘β–‘β•šβ•β•β–‘β–‘β–‘β•šβ•β•β•β•β•β•β•β•šβ•β•β–‘β–‘β•šβ•β• */ // Update dev address by the previous dev. function setDev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } function setSommaiPerBlock(uint256 _sommaiPerBlock) public onlyOwner { sommaiPerBlock = _sommaiPerBlock; } // Set Bonus params. bonus will start to accu on the next block that this function executed // See the calculation and counting in test file. function setBonus( uint256 _bonusMultiplier, uint256 _bonusEndBlock, uint256 _bonusLockUpBps ) public onlyOwner { require(_bonusEndBlock > block.number, "setBonus: bad bonusEndBlock"); require(_bonusMultiplier > 1, "setBonus: bad bonusMultiplier"); bonusMultiplier = _bonusMultiplier; bonusEndBlock = _bonusEndBlock; bonusLockUpBps = _bonusLockUpBps; } // Add a new lp to the pool. Can only be called by the owner. function addPool( uint256 _allocPoint, address _stakeToken, bool _withUpdate ) public override onlyOwner { if (_withUpdate) { massUpdatePools(); } require(_stakeToken != address(0), "add: not stakeToken addr"); require(!isDuplicatedPool(_stakeToken), "add: stakeToken dup"); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ stakeToken: _stakeToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSommaiPerShare: 0, accSommaiPerShareTilBonusEnd: 0 }) ); } // Update the given pool's SOMMAI allocation point. Can only be called by the owner. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public override onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } /* β–‘β–ˆβ–ˆβ•—β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ•—β–‘β–‘β–ˆβ–ˆβ•— β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•—β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β–‘β–ˆβ–ˆβ•”β• β–‘β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•β•β–‘ β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ•‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•—β–‘ β–‘β–‘β•šβ–ˆβ–ˆβ•”β•β–‘β•šβ–ˆβ–ˆβ•”β•β–‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–‘β•šβ–ˆβ–ˆβ•— β–‘β–‘β–‘β•šβ•β•β–‘β–‘β–‘β•šβ•β•β–‘β–‘β–‘β•šβ•β•β•β•β•β–‘β•šβ•β•β–‘β–‘β•šβ•β•β•šβ•β•β–‘β–‘β•šβ•β• */ function isDuplicatedPool(address _stakeToken) public view returns (bool) { uint256 length = poolInfo.length; for (uint256 _pid = 0; _pid < length; _pid++) { if(poolInfo[_pid].stakeToken == _stakeToken) return true; } return false; } function poolLength() external override view returns (uint256) { return poolInfo.length; } function manualMint(address _to, uint256 _amount) public onlyOwner { sommai.manualMint(_to, _amount); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _lastRewardBlock, uint256 _currentBlock) public view returns (uint256) { if (_currentBlock <= bonusEndBlock) { return _currentBlock.sub(_lastRewardBlock).mul(bonusMultiplier); } if (_lastRewardBlock >= bonusEndBlock) { return _currentBlock.sub(_lastRewardBlock); } // This is the case where bonusEndBlock is in the middle of _lastRewardBlock and _currentBlock block. return bonusEndBlock.sub(_lastRewardBlock).mul(bonusMultiplier).add(_currentBlock.sub(bonusEndBlock)); } // View function to see pending SOMMAI on frontend. function pendingSommai(uint256 _pid, address _user) external override view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSommaiPerShare = pool.accSommaiPerShare; uint256 lpSupply = IERC20(pool.stakeToken).balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sommaiReward = multiplier.mul(sommaiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSommaiPerShare = accSommaiPerShare.add(sommaiReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSommaiPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public override { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = IERC20(pool.stakeToken).balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sommaiReward = multiplier.mul(sommaiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sommai.mint(devaddr, sommaiReward.div(10)); sommai.mint(address(this), sommaiReward); pool.accSommaiPerShare = pool.accSommaiPerShare.add(sommaiReward.mul(1e12).div(lpSupply)); // update accSommaiPerShareTilBonusEnd if (block.number <= bonusEndBlock) { sommai.lock(devaddr, sommaiReward.div(10).mul(bonusLockUpBps).div(10000)); pool.accSommaiPerShareTilBonusEnd = pool.accSommaiPerShare; } if(block.number > bonusEndBlock && pool.lastRewardBlock < bonusEndBlock) { uint256 sommaiBonusPortion = bonusEndBlock.sub(pool.lastRewardBlock).mul(bonusMultiplier).mul(sommaiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sommai.lock(devaddr, sommaiBonusPortion.div(10).mul(bonusLockUpBps).div(10000)); pool.accSommaiPerShareTilBonusEnd = pool.accSommaiPerShareTilBonusEnd.add(sommaiBonusPortion.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit Staking tokens to FairLaunchToken for SOMMAI allocation. function deposit(address _for, uint256 _pid, uint256 _amount) public override { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_for]; if (user.fundedBy != address(0)) require(user.fundedBy == msg.sender, "bad sof"); require(pool.stakeToken != address(0), "deposit: not accept deposit"); updatePool(_pid); if (user.amount > 0) _harvest(_for, _pid); if (user.fundedBy == address(0)) user.fundedBy = msg.sender; IERC20(pool.stakeToken).safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSommaiPerShare).div(1e12); user.bonusDebt = user.amount.mul(pool.accSommaiPerShareTilBonusEnd).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw Staking tokens from FairLaunchToken. function withdraw(address _for, uint256 _pid, uint256 _amount) public override { _withdraw(_for, _pid, _amount); } function withdrawAll(address _for, uint256 _pid) public override { _withdraw(_for, _pid, userInfo[_pid][_for].amount); } function _withdraw(address _for, uint256 _pid, uint256 _amount) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_for]; require(user.fundedBy == msg.sender, "only funder"); require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); _harvest(_for, _pid); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSommaiPerShare).div(1e12); user.bonusDebt = user.amount.mul(pool.accSommaiPerShareTilBonusEnd).div(1e12); if (pool.stakeToken != address(0)) { IERC20(pool.stakeToken).safeTransfer(address(msg.sender), _amount); } emit Withdraw(msg.sender, _pid, user.amount); } // Harvest SOMMAI earn from the pool. function harvest(uint256 _pid) public override { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); _harvest(msg.sender, _pid); user.rewardDebt = user.amount.mul(pool.accSommaiPerShare).div(1e12); user.bonusDebt = user.amount.mul(pool.accSommaiPerShareTilBonusEnd).div(1e12); } function _harvest(address _to, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_to]; require(user.amount > 0, "nothing to harvest"); uint256 pending = user.amount.mul(pool.accSommaiPerShare).div(1e12).sub(user.rewardDebt); require(pending <= sommai.balanceOf(address(this)), "wtf not enough sommai"); uint256 bonus = user.amount.mul(pool.accSommaiPerShareTilBonusEnd).div(1e12).sub(user.bonusDebt); safeSommaiTransfer(_to, pending); sommai.lock(_to, bonus.mul(bonusLockUpBps).div(10000)); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; IERC20(pool.stakeToken).safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sommai transfer function, just in case if rounding error causes pool to not have enough SOMMAI. function safeSommaiTransfer(address _to, uint256 _amount) internal { uint256 sommaiBal = sommai.balanceOf(address(this)); if (_amount > sommaiBal) { sommai.transfer(_to, sommaiBal); } else { sommai.transfer(_to, _amount); } } }
contract FairLaunch is IFairLaunch, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many Staking tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 bonusDebt; // Last block that user exec something to the pool. address fundedBy; // Funded by who? // // We do some fancy math here. Basically, any point in time, the amount of SOMMAI // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSommaiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws Staking tokens to a pool. Here's what happens: // 1. The pool's `accSommaiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { address stakeToken; // Address of Staking token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SOMMAI to distribute per block. uint256 lastRewardBlock; // Last block number that SOMMAI distribution occurs. uint256 accSommaiPerShare; // Accumulated SOMMAI per share, times 1e12. See below. uint256 accSommaiPerShareTilBonusEnd; // Accumated SOMMAI per share until Bonus End. } // The Sommai TOKEN! SommaiToken public sommai; // Dev address. address public devaddr; // SOMMAI tokens created per block. uint256 public sommaiPerBlock; // Bonus muliplier for early sommai makers. uint256 public bonusMultiplier; // Block number when bonus SOMMAI period ends. uint256 public bonusEndBlock; // Bonus lock-up in BPS uint256 public bonusLockUpBps; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes Staking tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; // The block number when SOMMAI mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( SommaiToken _sommai, address _devaddr, uint256 _sommaiPerBlock, uint256 _startBlock, uint256 _bonusLockupBps, uint256 _bonusEndBlock ) public { bonusMultiplier = 0; totalAllocPoint = 0; sommai = _sommai; devaddr = _devaddr; sommaiPerBlock = _sommaiPerBlock; bonusLockUpBps = _bonusLockupBps; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } /* β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ•—β€ƒβ€ƒβ–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘ β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ•‘β€ƒβ€ƒβ–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β•β•β•β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β–ˆβ–ˆβ–ˆβ–ˆβ•”β–ˆβ–ˆβ•‘β€ƒβ€ƒβ•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•”β•β•β•β•β–‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘β€ƒβ€ƒβ–‘β•šβ•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–ˆβ–ˆβ•”β•β•β•β–‘β–‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–‘β•šβ•β•β–‘β–ˆβ–ˆβ•‘β€ƒβ€ƒβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘ β•šβ•β•β–‘β–‘β–‘β–‘β–‘β•šβ•β•β–‘β–‘β•šβ•β•β•šβ•β•β–‘β–‘β•šβ•β•β•šβ•β•β–‘β–‘β•šβ•β•β•šβ•β•β–‘β–‘β–‘β–‘β–‘β•šβ•β•β€ƒβ€ƒβ•šβ•β•β•β•β•β•β–‘β•šβ•β•β•β•β•β•β•β–‘β–‘β–‘β•šβ•β•β–‘β–‘β–‘β–‘β–‘β–‘β•šβ•β•β–‘β–‘β–‘β•šβ•β•β•β•β•β•β•β•šβ•β•β–‘β–‘β•šβ•β• */ // Update dev address by the previous dev. function setDev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } function setSommaiPerBlock(uint256 _sommaiPerBlock) public onlyOwner { sommaiPerBlock = _sommaiPerBlock; } // Set Bonus params. bonus will start to accu on the next block that this function executed // See the calculation and counting in test file. function setBonus( uint256 _bonusMultiplier, uint256 _bonusEndBlock, uint256 _bonusLockUpBps ) public onlyOwner { require(_bonusEndBlock > block.number, "setBonus: bad bonusEndBlock"); require(_bonusMultiplier > 1, "setBonus: bad bonusMultiplier"); bonusMultiplier = _bonusMultiplier; bonusEndBlock = _bonusEndBlock; bonusLockUpBps = _bonusLockUpBps; } // Add a new lp to the pool. Can only be called by the owner. function addPool( uint256 _allocPoint, address _stakeToken, bool _withUpdate ) public override onlyOwner { if (_withUpdate) { massUpdatePools(); } require(_stakeToken != address(0), "add: not stakeToken addr"); require(!isDuplicatedPool(_stakeToken), "add: stakeToken dup"); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ stakeToken: _stakeToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSommaiPerShare: 0, accSommaiPerShareTilBonusEnd: 0 }) ); } // Update the given pool's SOMMAI allocation point. Can only be called by the owner. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public override onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } /* β–‘β–ˆβ–ˆβ•—β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–‘β–ˆβ–ˆβ•—β–‘β–‘β–ˆβ–ˆβ•— β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•—β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘β–‘β–ˆβ–ˆβ•”β• β–‘β•šβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•β•β–‘ β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ•‘β–‘β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•—β–‘ β–‘β–‘β•šβ–ˆβ–ˆβ•”β•β–‘β•šβ–ˆβ–ˆβ•”β•β–‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘β–‘β–‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–‘β•šβ–ˆβ–ˆβ•— β–‘β–‘β–‘β•šβ•β•β–‘β–‘β–‘β•šβ•β•β–‘β–‘β–‘β•šβ•β•β•β•β•β–‘β•šβ•β•β–‘β–‘β•šβ•β•β•šβ•β•β–‘β–‘β•šβ•β• */ function isDuplicatedPool(address _stakeToken) public view returns (bool) { uint256 length = poolInfo.length; for (uint256 _pid = 0; _pid < length; _pid++) { if(poolInfo[_pid].stakeToken == _stakeToken) return true; } return false; } function poolLength() external override view returns (uint256) { return poolInfo.length; } function manualMint(address _to, uint256 _amount) public onlyOwner { sommai.manualMint(_to, _amount); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _lastRewardBlock, uint256 _currentBlock) public view returns (uint256) { if (_currentBlock <= bonusEndBlock) { return _currentBlock.sub(_lastRewardBlock).mul(bonusMultiplier); } if (_lastRewardBlock >= bonusEndBlock) { return _currentBlock.sub(_lastRewardBlock); } // This is the case where bonusEndBlock is in the middle of _lastRewardBlock and _currentBlock block. return bonusEndBlock.sub(_lastRewardBlock).mul(bonusMultiplier).add(_currentBlock.sub(bonusEndBlock)); } // View function to see pending SOMMAI on frontend. function pendingSommai(uint256 _pid, address _user) external override view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSommaiPerShare = pool.accSommaiPerShare; uint256 lpSupply = IERC20(pool.stakeToken).balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sommaiReward = multiplier.mul(sommaiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSommaiPerShare = accSommaiPerShare.add(sommaiReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSommaiPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public override { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = IERC20(pool.stakeToken).balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sommaiReward = multiplier.mul(sommaiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sommai.mint(devaddr, sommaiReward.div(10)); sommai.mint(address(this), sommaiReward); pool.accSommaiPerShare = pool.accSommaiPerShare.add(sommaiReward.mul(1e12).div(lpSupply)); // update accSommaiPerShareTilBonusEnd if (block.number <= bonusEndBlock) { sommai.lock(devaddr, sommaiReward.div(10).mul(bonusLockUpBps).div(10000)); pool.accSommaiPerShareTilBonusEnd = pool.accSommaiPerShare; } if(block.number > bonusEndBlock && pool.lastRewardBlock < bonusEndBlock) { uint256 sommaiBonusPortion = bonusEndBlock.sub(pool.lastRewardBlock).mul(bonusMultiplier).mul(sommaiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sommai.lock(devaddr, sommaiBonusPortion.div(10).mul(bonusLockUpBps).div(10000)); pool.accSommaiPerShareTilBonusEnd = pool.accSommaiPerShareTilBonusEnd.add(sommaiBonusPortion.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit Staking tokens to FairLaunchToken for SOMMAI allocation. function deposit(address _for, uint256 _pid, uint256 _amount) public override { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_for]; if (user.fundedBy != address(0)) require(user.fundedBy == msg.sender, "bad sof"); require(pool.stakeToken != address(0), "deposit: not accept deposit"); updatePool(_pid); if (user.amount > 0) _harvest(_for, _pid); if (user.fundedBy == address(0)) user.fundedBy = msg.sender; IERC20(pool.stakeToken).safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSommaiPerShare).div(1e12); user.bonusDebt = user.amount.mul(pool.accSommaiPerShareTilBonusEnd).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw Staking tokens from FairLaunchToken. function withdraw(address _for, uint256 _pid, uint256 _amount) public override { _withdraw(_for, _pid, _amount); } function withdrawAll(address _for, uint256 _pid) public override { _withdraw(_for, _pid, userInfo[_pid][_for].amount); } function _withdraw(address _for, uint256 _pid, uint256 _amount) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_for]; require(user.fundedBy == msg.sender, "only funder"); require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); _harvest(_for, _pid); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSommaiPerShare).div(1e12); user.bonusDebt = user.amount.mul(pool.accSommaiPerShareTilBonusEnd).div(1e12); if (pool.stakeToken != address(0)) { IERC20(pool.stakeToken).safeTransfer(address(msg.sender), _amount); } emit Withdraw(msg.sender, _pid, user.amount); } // Harvest SOMMAI earn from the pool. function harvest(uint256 _pid) public override { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); _harvest(msg.sender, _pid); user.rewardDebt = user.amount.mul(pool.accSommaiPerShare).div(1e12); user.bonusDebt = user.amount.mul(pool.accSommaiPerShareTilBonusEnd).div(1e12); } function _harvest(address _to, uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_to]; require(user.amount > 0, "nothing to harvest"); uint256 pending = user.amount.mul(pool.accSommaiPerShare).div(1e12).sub(user.rewardDebt); require(pending <= sommai.balanceOf(address(this)), "wtf not enough sommai"); uint256 bonus = user.amount.mul(pool.accSommaiPerShareTilBonusEnd).div(1e12).sub(user.bonusDebt); safeSommaiTransfer(_to, pending); sommai.lock(_to, bonus.mul(bonusLockUpBps).div(10000)); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; IERC20(pool.stakeToken).safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sommai transfer function, just in case if rounding error causes pool to not have enough SOMMAI. function safeSommaiTransfer(address _to, uint256 _amount) internal { uint256 sommaiBal = sommai.balanceOf(address(this)); if (_amount > sommaiBal) { sommai.transfer(_to, sommaiBal); } else { sommai.transfer(_to, _amount); } } }
23,361
42
// Our contracts
address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant NEW_IDAI_ADDRESS = 0x6c1E2B0f67e00c06c8e2BE7Dc681Ab785163fF4D;
address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant NEW_IDAI_ADDRESS = 0x6c1E2B0f67e00c06c8e2BE7Dc681Ab785163fF4D;
84,877
213
// Get the time at which a given schedule entry will vest. /
function getVestingTime(address account, uint index) public view returns (uint)
function getVestingTime(address account, uint index) public view returns (uint)
49,926
41
// ==================== MODIFIERS ===================== /
modifier buyAllowed() { if (!generalConfig.allowBuy) revert BuyDisabled(); _; }
modifier buyAllowed() { if (!generalConfig.allowBuy) revert BuyDisabled(); _; }
22,575
11
// why is there amount
function JudgeDecision(uint256 ContractID, bool decision) public { require(msg.sender == JudgeIDInfo[ContractID].judge, "Un-Authorized access"); require(block.timestamp > Contracts[ContractID].InitiateTime + Contracts[ContractID].ContractDeadline, "Conctract still open"); require(Contracts[ContractID].paymentStatus == false, "Contract already closed"); if(decision == true) { Contracts[ContractID].counterparty.transfer(Contracts[ContractID].amount-JudgeFee); Contracts[ContractID].paymentStatus=true; JudgeIDInfo[ContractID].FinalDecision= "In favor of the counterparty"; AddressInfo[Contracts[ContractID].counterparty].ContractsWonWithJudge +=1 ; } else { Contracts[ContractID].issuer.transfer(Contracts[ContractID].amount-JudgeFee); JudgeIDInfo[ContractID].FinalDecision= "In favor of the issuer"; AddressInfo[Contracts[ContractID].issuer].ContractsWonWithJudge +=1; } ContractIDsolved[JudgeIDInfo[ContractID].judge].push(ContractID); JudgeIDInfo[ContractID].judge.transfer(JudgeFee); AddressInfo[Contracts[ContractID].issuer].ContractsErroneouslyClosed +=1; AddressInfo[Contracts[ContractID].counterparty].ContractsErroneouslyClosed +=1; }
function JudgeDecision(uint256 ContractID, bool decision) public { require(msg.sender == JudgeIDInfo[ContractID].judge, "Un-Authorized access"); require(block.timestamp > Contracts[ContractID].InitiateTime + Contracts[ContractID].ContractDeadline, "Conctract still open"); require(Contracts[ContractID].paymentStatus == false, "Contract already closed"); if(decision == true) { Contracts[ContractID].counterparty.transfer(Contracts[ContractID].amount-JudgeFee); Contracts[ContractID].paymentStatus=true; JudgeIDInfo[ContractID].FinalDecision= "In favor of the counterparty"; AddressInfo[Contracts[ContractID].counterparty].ContractsWonWithJudge +=1 ; } else { Contracts[ContractID].issuer.transfer(Contracts[ContractID].amount-JudgeFee); JudgeIDInfo[ContractID].FinalDecision= "In favor of the issuer"; AddressInfo[Contracts[ContractID].issuer].ContractsWonWithJudge +=1; } ContractIDsolved[JudgeIDInfo[ContractID].judge].push(ContractID); JudgeIDInfo[ContractID].judge.transfer(JudgeFee); AddressInfo[Contracts[ContractID].issuer].ContractsErroneouslyClosed +=1; AddressInfo[Contracts[ContractID].counterparty].ContractsErroneouslyClosed +=1; }
40,031
76
// Only stopping for bonus distribution/
modifier onlyStopping() { require(isStopped == true); _; }
modifier onlyStopping() { require(isStopped == true); _; }
17,522
48
// must use requestPayFromPlayer modifier to approve on the initial function!
dckToken.transferFrom(playerAddress, address(this), convertedAmount);
dckToken.transferFrom(playerAddress, address(this), convertedAmount);
26,689
107
// this event is emitted when the Agent has been added on the allowedList of this Compliance.the event is emitted by the Compliance constructor and by the addTokenAgent function`_agentAddress` is the address of the Agent to add/
event TokenAgentAdded(address _agentAddress);
event TokenAgentAdded(address _agentAddress);
15,166
22
// Set create fee
function setCreateFee(uint256 _fee) public onlyOwner { fees.createFee = _fee; emit CreateFeeChanged(_fee); }
function setCreateFee(uint256 _fee) public onlyOwner { fees.createFee = _fee; emit CreateFeeChanged(_fee); }
13,980
302
// dao redeem its winnings
if (proposal.daoRedeemItsWinnings == false && _beneficiary == organizations[proposal.organizationId] && proposal.state != ProposalState.ExpiredInQueue && proposal.winningVote == NO) { rewards[0] = rewards[0] .add((proposal.daoBounty.mul(totalStakesLeftAfterCallBounty))/totalWinningStakes) .sub(proposal.daoBounty); proposal.daoRedeemItsWinnings = true; }
if (proposal.daoRedeemItsWinnings == false && _beneficiary == organizations[proposal.organizationId] && proposal.state != ProposalState.ExpiredInQueue && proposal.winningVote == NO) { rewards[0] = rewards[0] .add((proposal.daoBounty.mul(totalStakesLeftAfterCallBounty))/totalWinningStakes) .sub(proposal.daoBounty); proposal.daoRedeemItsWinnings = true; }
7,703
73
// Tokenbridge Arbitrary Message Bridge
interface IAMB { //only on mainnet AMB: function executeSignatures(bytes calldata _data, bytes calldata _signatures) external; function messageSender() external view returns (address); function maxGasPerTx() external view returns (uint256); function transactionHash() external view returns (bytes32); function messageId() external view returns (bytes32); function messageSourceChainId() external view returns (bytes32); function messageCallStatus(bytes32 _messageId) external view returns (bool); function requiredSignatures() external view returns (uint256); function numMessagesSigned(bytes32 _message) external view returns (uint256); function signature(bytes32 _hash, uint256 _index) external view returns (bytes memory); function message(bytes32 _hash) external view returns (bytes memory); function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32); function failedMessageReceiver(bytes32 _messageId) external view returns (address); function failedMessageSender(bytes32 _messageId) external view returns (address); function requireToPassMessage( address _contract, bytes calldata _data, uint256 _gas ) external returns (bytes32); }
interface IAMB { //only on mainnet AMB: function executeSignatures(bytes calldata _data, bytes calldata _signatures) external; function messageSender() external view returns (address); function maxGasPerTx() external view returns (uint256); function transactionHash() external view returns (bytes32); function messageId() external view returns (bytes32); function messageSourceChainId() external view returns (bytes32); function messageCallStatus(bytes32 _messageId) external view returns (bool); function requiredSignatures() external view returns (uint256); function numMessagesSigned(bytes32 _message) external view returns (uint256); function signature(bytes32 _hash, uint256 _index) external view returns (bytes memory); function message(bytes32 _hash) external view returns (bytes memory); function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32); function failedMessageReceiver(bytes32 _messageId) external view returns (address); function failedMessageSender(bytes32 _messageId) external view returns (address); function requireToPassMessage( address _contract, bytes calldata _data, uint256 _gas ) external returns (bytes32); }
68,214
46
// Move bet into 'processed' state already.
bet.Amount = 0;
bet.Amount = 0;
13,151
8
// Defines a different service fees percentage than the global one for some specific collections (e.g., Brands)
mapping(address => uint256) public specialProtocolFeesPercentage;
mapping(address => uint256) public specialProtocolFeesPercentage;
29,412
34
// the primary modifier value will hold our defence bonus
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum); primaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus);
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum); primaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus);
48,471
3
// The constructor for the Staking Token._owner The address to receive all tokens on construction._supply The amount of tokens to mint on construction./
constructor(address _owner, uint256 _supply) public { startBlock = block.number; _mint(_owner, _supply); }
constructor(address _owner, uint256 _supply) public { startBlock = block.number; _mint(_owner, _supply); }
27,315
3
// GNNM13
event Transfer(address indexed from, address indexed to, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
19,578
44
// is hxb minting ceased? transfer from contract balance if so
if(hxb.mintBlock()){ uint b = customerShare / hxbRatio; if(hxb.balanceOf(address(this)) >= b){
if(hxb.mintBlock()){ uint b = customerShare / hxbRatio; if(hxb.balanceOf(address(this)) >= b){
42,765
8
// Address
function getAddress(bytes32 _key) public view returns (address); function setAddress(bytes32 _key, address _value) public; function deleteAddress(bytes32 _key) public;
function getAddress(bytes32 _key) public view returns (address); function setAddress(bytes32 _key, address _value) public; function deleteAddress(bytes32 _key) public;
5,342
26
// ι‚€θ―·δ»²θ£ε‘˜ιœ€θ¦ηΌ΄ηΊ³δ»²θ£θ΄ΉοΌŒδ½†εͺιœ€θ¦ηΌ΄ηΊ³δΈ€ζ¬‘
if (bma[i][msg.sender] == 0){ uint256 mm = mul(user[i].mma,arat)/one; mar.transferFrom(msg.sender, address(this), mm); bma[i][msg.sender] = mm; }
if (bma[i][msg.sender] == 0){ uint256 mm = mul(user[i].mma,arat)/one; mar.transferFrom(msg.sender, address(this), mm); bma[i][msg.sender] = mm; }
42,726
71
// Internal call to close advisory board voting _proposalId of proposal in concern category of proposal in concern /
function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal { uint _majorityVote; IMemberRoles.Role _roleId = IMemberRoles.Role.AdvisoryBoard; (,, _majorityVote,,,,) = proposalCategory.category(category); if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } }
function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal { uint _majorityVote; IMemberRoles.Role _roleId = IMemberRoles.Role.AdvisoryBoard; (,, _majorityVote,,,,) = proposalCategory.category(category); if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } }
31,807
8
// ------------------------------------------------------------------------ Transfer `tokens` from the `from` account to the `to` accountThe calling account must already have sufficient tokens approve(...)-d for spending from the `from` account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ // unlock tokens update unlockTokens(); require(tokens <= allowed[from][msg.sender]); //check allowance require(balances[from] >= tokens); if(from == owner){ require(balances[msg.sender].sub(tokens) >= lockedTokens); } balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from,to,tokens); return true; }
function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ // unlock tokens update unlockTokens(); require(tokens <= allowed[from][msg.sender]); //check allowance require(balances[from] >= tokens); if(from == owner){ require(balances[msg.sender].sub(tokens) >= lockedTokens); } balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from,to,tokens); return true; }
16,049
482
// redeem original deposited vault token
vault.withdraw(_tokensToShares(_amount)); IWETH vaultToken = IWETH(vault.token());
vault.withdraw(_tokensToShares(_amount)); IWETH vaultToken = IWETH(vault.token());
34,488
251
// The referral program
IReferralProgram public referralProgram; address public treasury; function _configureVaultWithReferralProgram( address _referralProgram, address _treasury
IReferralProgram public referralProgram; address public treasury; function _configureVaultWithReferralProgram( address _referralProgram, address _treasury
80,742
50
// Invalid proof length
transition(disputeId, DisputeState.RESOLVED_FOR_COMPLAINANT); return;
transition(disputeId, DisputeState.RESOLVED_FOR_COMPLAINANT); return;
23,195
155
// Get the coordinates of this neighboring identifier.
uint256 neighborIdentifier = coordinateToIdentifier( nx, ny ); if (gameStates[gameIndex].identifierToOwner[neighborIdentifier] != address(0x0)) { _tiles[claimed] = neighborIdentifier; claimed++; }
uint256 neighborIdentifier = coordinateToIdentifier( nx, ny ); if (gameStates[gameIndex].identifierToOwner[neighborIdentifier] != address(0x0)) { _tiles[claimed] = neighborIdentifier; claimed++; }
17,694
40
// Do not allow transfer to 0x0 or the token contract itself
require((_to != address(0)) && (_to != address(this))); require(_amount <= balances[_from]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount);
require((_to != address(0)) && (_to != address(this))); require(_amount <= balances[_from]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount);
27,866
20
// transfer the shapeshifters to this contract
for (uint256 i = 0; i < shapeIds.length; i++) { Shapeshifter.transferFrom(_msgSender(), address(this), shapeIds[i]); }
for (uint256 i = 0; i < shapeIds.length; i++) { Shapeshifter.transferFrom(_msgSender(), address(this), shapeIds[i]); }
18,594
11
// reset rewards to zero
rewards[msg.sender] = 0;
rewards[msg.sender] = 0;
60,208
34
// We don't care about overflow of the addition, because it would require a list larger than any feasible computer's memory.
int256 pivot = list[(lo + hi) / 2]; lo -= 1; // this can underflow. that's intentional. hi += 1; while (true) { do { lo += 1; } while (list[lo] < pivot);
int256 pivot = list[(lo + hi) / 2]; lo -= 1; // this can underflow. that's intentional. hi += 1; while (true) { do { lo += 1; } while (list[lo] < pivot);
14,364
45
// Check balance
uint b = basedToken.balanceOf(address(this)); if (b < _output_amount) { uint _toWithdraw = _output_amount.sub(b); uint _withdrawFee = IController(controller).withdraw(_toWithdraw); uint _after = basedToken.balanceOf(address(this)); uint _diff = _after.sub(b); if (_diff < _toWithdraw) { _output_amount = b.add(_diff); }
uint b = basedToken.balanceOf(address(this)); if (b < _output_amount) { uint _toWithdraw = _output_amount.sub(b); uint _withdrawFee = IController(controller).withdraw(_toWithdraw); uint _after = basedToken.balanceOf(address(this)); uint _diff = _after.sub(b); if (_diff < _toWithdraw) { _output_amount = b.add(_diff); }
10,119
78
// Clear value
airdrops[msg.sender].value = 0;
airdrops[msg.sender].value = 0;
21,531
85
// get next lottery end time
uint nextEndAt = latestEndAt + defaultParams.gameDuration; while(now > nextEndAt) { nextEndAt += defaultParams.gameDuration; }
uint nextEndAt = latestEndAt + defaultParams.gameDuration; while(now > nextEndAt) { nextEndAt += defaultParams.gameDuration; }
86,649
17
// ========== Portfolio Calculation ========== /
{ PoolConstant.PoolTypes poolType = poolTypes[pool]; address stakingToken; if (poolType == PoolConstant.PoolTypes.RubiStake_deprecated) { stakingToken = RUBI; } else { stakingToken = IStrategy(pool).stakingToken(); } if (stakingToken == address(0)) return 0; (, tokenInUSD) = priceCalculator.valueOfAsset( stakingToken, IStrategy(pool).principalOf(account) ); }
{ PoolConstant.PoolTypes poolType = poolTypes[pool]; address stakingToken; if (poolType == PoolConstant.PoolTypes.RubiStake_deprecated) { stakingToken = RUBI; } else { stakingToken = IStrategy(pool).stakingToken(); } if (stakingToken == address(0)) return 0; (, tokenInUSD) = priceCalculator.valueOfAsset( stakingToken, IStrategy(pool).principalOf(account) ); }
14,835
0
// use safemath
using SafeMath for uint256; using SafeMath32 for uint32; using SafeMath16 for uint16;
using SafeMath for uint256; using SafeMath32 for uint32; using SafeMath16 for uint16;
33,318
26
// Get the exchange rate the contract will got for the purchase. Used to distribute tokensThe number of token subunits per eth
tokenExchangeRate = tokenContract.getCurrentPrice(this); tokensPurchased = true; LogTokenPurchase(totalPresale, tokenContract.tokenSaleBalanceOf(this));
tokenExchangeRate = tokenContract.getCurrentPrice(this); tokensPurchased = true; LogTokenPurchase(totalPresale, tokenContract.tokenSaleBalanceOf(this));
38,914
30
// Returns true if the slice is empty (has a length of 0). self The slice to operate on.return True if the slice is empty, False otherwise. /
function empty(slice memory self) internal pure returns (bool) { return self._len == 0; }
function empty(slice memory self) internal pure returns (bool) { return self._len == 0; }
32,270
17
// new bid event
event NewBid(uint256 indexed tokenId, address lastBidder, address lastReferer, uint256 lastRecord, address tokenAddress, uint256 bidStartAt);
event NewBid(uint256 indexed tokenId, address lastBidder, address lastReferer, uint256 lastRecord, address tokenAddress, uint256 bidStartAt);
1,739
7
// Gets the accumulated reward weight of a pool.//_ctx the pool context.// return the accumulated reward weight.
function getUpdatedAccumulatedRewardWeight(Data storage _data, Context storage _ctx) internal view returns (FixedPointMath.FixedDecimal memory)
function getUpdatedAccumulatedRewardWeight(Data storage _data, Context storage _ctx) internal view returns (FixedPointMath.FixedDecimal memory)
16,037
38
// Function 'updateTokenURI' updates the Token URI for a specific Token
function updateTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyContractOwner
function updateTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyContractOwner
44,109
18
// SPDX-License-Identifier: MIT// Publius Governance handles propsing, voting for and committing BIPs as well as pausing/unpausing./
contract GovernanceFacet is VotingBooth { using SafeMath for uint256; using SafeMath for uint32; using Decimal for Decimal.D256; event Proposal(address indexed account, uint32 indexed bip, uint256 indexed start, uint256 period); event Vote(address indexed account, uint32 indexed bip, uint256 roots); event VoteList(address indexed account, uint32[] indexed bips, bool[] votes, uint256 roots); event Unvote(address indexed account, uint32 indexed bip, uint256 roots); event Commit(address indexed account, uint32 indexed bip); event Incentivization(address indexed account, uint256 beans); event Pause(address account, uint256 timestamp); event Unpause(address account, uint256 timestamp, uint256 timePassed); /** * Proposition **/ function propose( IDiamondCut.FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata, uint8 _pauseOrUnpause ) external { require(canPropose(msg.sender), "Governance: Not enough Stalk."); require(notTooProposed(msg.sender), "Governance: Too many active BIPs."); require( _init != address(0) || _diamondCut.length > 0 || _pauseOrUnpause > 0, "Governance: Proposition is empty." ); uint32 bipId = createBip( _diamondCut, _init, _calldata, _pauseOrUnpause, C.getGovernancePeriod(), msg.sender ); s.a[msg.sender].proposedUntil = startFor(bipId) + periodFor(bipId); emit Proposal(msg.sender, bipId, season(), C.getGovernancePeriod()); vote(bipId); } /** * Voting **/ function vote(uint32 bip) public { require(isNominated(bip), "Governance: Not nominated."); require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk."); require(isActive(bip), "Governance: Ended."); require(!voted(msg.sender, bip), "Governance: Already voted."); recordVote(msg.sender, bip); placeVotedUntil(msg.sender, bip); emit Vote(msg.sender, bip, balanceOfRoots(msg.sender)); } /// @notice Takes in a list of multiple bips and performs a vote on all of them /// @param bip_list Contains the bip proposal ids to vote on function voteAll(uint32[] calldata bip_list) public { require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk."); bool[] memory vote_types = new bool[](bip_list.length); uint i = 0; uint32 lock = s.a[msg.sender].votedUntil; for (i = 0; i < bip_list.length; i++) { uint32 bip = bip_list[i]; require(isNominated(bip), "Governance: Not nominated."); require(isActive(bip), "Governance: Ended."); require(!voted(msg.sender, bip), "Governance: Already voted."); recordVote(msg.sender, bip); vote_types[i] = true; // Place timelocks uint32 newLock = startFor(bip) + periodFor(bip); if (newLock > lock) lock = newLock; } s.a[msg.sender].votedUntil = lock; emit VoteList(msg.sender, bip_list, vote_types, balanceOfRoots(msg.sender)); } function unvote(uint32 bip) external { require(isNominated(bip), "Governance: Not nominated."); require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk."); require(isActive(bip), "Governance: Ended."); require(voted(msg.sender, bip), "Governance: Not voted."); require(proposer(bip) != msg.sender, "Governance: Is proposer."); unrecordVote(msg.sender, bip); updateVotedUntil(msg.sender); emit Unvote(msg.sender, bip, balanceOfRoots(msg.sender)); } /// @notice Takes in a list of multiple bips and performs an unvote on all of them /// @param bip_list Contains the bip proposal ids to unvote on function unvoteAll(uint32[] calldata bip_list) external { require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk."); uint i = 0; bool[] memory vote_types = new bool[](bip_list.length); for (i = 0; i < bip_list.length; i++) { uint32 bip = bip_list[i]; require(isNominated(bip), "Governance: Not nominated."); require(isActive(bip), "Governance: Ended."); require(voted(msg.sender, bip), "Governance: Not voted."); require(proposer(bip) != msg.sender, "Governance: Is proposer."); unrecordVote(msg.sender, bip); vote_types[i] = false; } updateVotedUntil(msg.sender); emit VoteList(msg.sender, bip_list, vote_types, balanceOfRoots(msg.sender)); } /// @notice Takes in a list of multiple bips and performs a vote or unvote on all of them /// depending on their status: whether they are currently voted on or not voted on /// @param bip_list Contains the bip proposal ids function voteUnvoteAll(uint32[] calldata bip_list) external { require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk."); uint i = 0; bool[] memory vote_types = new bool[](bip_list.length); for (i = 0; i < bip_list.length; i++) { uint32 bip = bip_list[i]; require(isNominated(bip), "Governance: Not nominated."); require(isActive(bip), "Governance: Ended."); if (s.g.voted[bip][msg.sender]) { // Handle Unvote require(proposer(bip) != msg.sender, "Governance: Is proposer."); unrecordVote(msg.sender, bip); vote_types[i] = false; } else { // Handle Vote recordVote(msg.sender, bip); vote_types[i] = true; } } updateVotedUntil(msg.sender); emit VoteList(msg.sender, bip_list, vote_types, balanceOfRoots(msg.sender)); } /** * Execution **/ function commit(uint32 bip) external { require(isNominated(bip), "Governance: Not nominated."); require(!isActive(bip), "Governance: Not ended."); require(!isExpired(bip), "Governance: Expired."); require( endedBipVotePercent(bip).greaterThanOrEqualTo(C.getGovernancePassThreshold()), "Governance: Must have majority." ); s.g.bips[bip].executed = true; cutBip(bip); pauseOrUnpauseBip(bip); incentivize(msg.sender, true, bip, C.getCommitIncentive()); emit Commit(msg.sender, bip); } function emergencyCommit(uint32 bip) external { require(isNominated(bip), "Governance: Not nominated."); require( block.timestamp >= timestamp(bip).add(C.getGovernanceEmergencyPeriod()), "Governance: Too early."); require(isActive(bip), "Governance: Ended."); require( bipVotePercent(bip).greaterThanOrEqualTo(C.getGovernanceEmergencyThreshold()), "Governance: Must have super majority." ); endBip(bip); s.g.bips[bip].executed = true; cutBip(bip); pauseOrUnpauseBip(bip); incentivize(msg.sender, false, bip, C.getCommitIncentive()); emit Commit(msg.sender, bip); } function pauseOrUnpause(uint32 bip) external { require(isNominated(bip), "Governance: Not nominated."); require(diamondCutIsEmpty(bip),"Governance: Has diamond cut."); require(isActive(bip), "Governance: Ended."); require( bipVotePercent(bip).greaterThanOrEqualTo(C.getGovernanceEmergencyThreshold()), "Governance: Must have super majority." ); endBip(bip); s.g.bips[bip].executed = true; pauseOrUnpauseBip(bip); incentivize(msg.sender, false, bip, C.getCommitIncentive()); emit Commit(msg.sender, bip); } function incentivize(address account, bool compound, uint32 bipId, uint256 amount) private { if (compound) amount = LibIncentive.fracExp(amount, 100, incentiveTime(bipId), 2); IBean(s.c.bean).mint(account, amount); emit Incentivization(account, amount); } /** * Pause / Unpause **/ function ownerPause() external { LibDiamond.enforceIsContractOwner(); pause(); } function ownerUnpause() external { LibDiamond.enforceIsContractOwner(); unpause(); } function pause() private { if (s.paused) return; s.paused = true; s.o.initialized = false; s.pausedAt = uint128(block.timestamp); emit Pause(msg.sender, block.timestamp); } function unpause() private { if (!s.paused) return; s.paused = false; uint256 timePassed = block.timestamp.sub(uint(s.pausedAt)); timePassed = (timePassed.div(3600).add(1)).mul(3600); s.season.start = s.season.start.add(timePassed); emit Unpause(msg.sender, block.timestamp, timePassed); } function pauseOrUnpauseBip(uint32 bipId) private { if (s.g.bips[bipId].pauseOrUnpause == 1) pause(); else if (s.g.bips[bipId].pauseOrUnpause == 2) unpause(); } }
contract GovernanceFacet is VotingBooth { using SafeMath for uint256; using SafeMath for uint32; using Decimal for Decimal.D256; event Proposal(address indexed account, uint32 indexed bip, uint256 indexed start, uint256 period); event Vote(address indexed account, uint32 indexed bip, uint256 roots); event VoteList(address indexed account, uint32[] indexed bips, bool[] votes, uint256 roots); event Unvote(address indexed account, uint32 indexed bip, uint256 roots); event Commit(address indexed account, uint32 indexed bip); event Incentivization(address indexed account, uint256 beans); event Pause(address account, uint256 timestamp); event Unpause(address account, uint256 timestamp, uint256 timePassed); /** * Proposition **/ function propose( IDiamondCut.FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata, uint8 _pauseOrUnpause ) external { require(canPropose(msg.sender), "Governance: Not enough Stalk."); require(notTooProposed(msg.sender), "Governance: Too many active BIPs."); require( _init != address(0) || _diamondCut.length > 0 || _pauseOrUnpause > 0, "Governance: Proposition is empty." ); uint32 bipId = createBip( _diamondCut, _init, _calldata, _pauseOrUnpause, C.getGovernancePeriod(), msg.sender ); s.a[msg.sender].proposedUntil = startFor(bipId) + periodFor(bipId); emit Proposal(msg.sender, bipId, season(), C.getGovernancePeriod()); vote(bipId); } /** * Voting **/ function vote(uint32 bip) public { require(isNominated(bip), "Governance: Not nominated."); require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk."); require(isActive(bip), "Governance: Ended."); require(!voted(msg.sender, bip), "Governance: Already voted."); recordVote(msg.sender, bip); placeVotedUntil(msg.sender, bip); emit Vote(msg.sender, bip, balanceOfRoots(msg.sender)); } /// @notice Takes in a list of multiple bips and performs a vote on all of them /// @param bip_list Contains the bip proposal ids to vote on function voteAll(uint32[] calldata bip_list) public { require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk."); bool[] memory vote_types = new bool[](bip_list.length); uint i = 0; uint32 lock = s.a[msg.sender].votedUntil; for (i = 0; i < bip_list.length; i++) { uint32 bip = bip_list[i]; require(isNominated(bip), "Governance: Not nominated."); require(isActive(bip), "Governance: Ended."); require(!voted(msg.sender, bip), "Governance: Already voted."); recordVote(msg.sender, bip); vote_types[i] = true; // Place timelocks uint32 newLock = startFor(bip) + periodFor(bip); if (newLock > lock) lock = newLock; } s.a[msg.sender].votedUntil = lock; emit VoteList(msg.sender, bip_list, vote_types, balanceOfRoots(msg.sender)); } function unvote(uint32 bip) external { require(isNominated(bip), "Governance: Not nominated."); require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk."); require(isActive(bip), "Governance: Ended."); require(voted(msg.sender, bip), "Governance: Not voted."); require(proposer(bip) != msg.sender, "Governance: Is proposer."); unrecordVote(msg.sender, bip); updateVotedUntil(msg.sender); emit Unvote(msg.sender, bip, balanceOfRoots(msg.sender)); } /// @notice Takes in a list of multiple bips and performs an unvote on all of them /// @param bip_list Contains the bip proposal ids to unvote on function unvoteAll(uint32[] calldata bip_list) external { require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk."); uint i = 0; bool[] memory vote_types = new bool[](bip_list.length); for (i = 0; i < bip_list.length; i++) { uint32 bip = bip_list[i]; require(isNominated(bip), "Governance: Not nominated."); require(isActive(bip), "Governance: Ended."); require(voted(msg.sender, bip), "Governance: Not voted."); require(proposer(bip) != msg.sender, "Governance: Is proposer."); unrecordVote(msg.sender, bip); vote_types[i] = false; } updateVotedUntil(msg.sender); emit VoteList(msg.sender, bip_list, vote_types, balanceOfRoots(msg.sender)); } /// @notice Takes in a list of multiple bips and performs a vote or unvote on all of them /// depending on their status: whether they are currently voted on or not voted on /// @param bip_list Contains the bip proposal ids function voteUnvoteAll(uint32[] calldata bip_list) external { require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk."); uint i = 0; bool[] memory vote_types = new bool[](bip_list.length); for (i = 0; i < bip_list.length; i++) { uint32 bip = bip_list[i]; require(isNominated(bip), "Governance: Not nominated."); require(isActive(bip), "Governance: Ended."); if (s.g.voted[bip][msg.sender]) { // Handle Unvote require(proposer(bip) != msg.sender, "Governance: Is proposer."); unrecordVote(msg.sender, bip); vote_types[i] = false; } else { // Handle Vote recordVote(msg.sender, bip); vote_types[i] = true; } } updateVotedUntil(msg.sender); emit VoteList(msg.sender, bip_list, vote_types, balanceOfRoots(msg.sender)); } /** * Execution **/ function commit(uint32 bip) external { require(isNominated(bip), "Governance: Not nominated."); require(!isActive(bip), "Governance: Not ended."); require(!isExpired(bip), "Governance: Expired."); require( endedBipVotePercent(bip).greaterThanOrEqualTo(C.getGovernancePassThreshold()), "Governance: Must have majority." ); s.g.bips[bip].executed = true; cutBip(bip); pauseOrUnpauseBip(bip); incentivize(msg.sender, true, bip, C.getCommitIncentive()); emit Commit(msg.sender, bip); } function emergencyCommit(uint32 bip) external { require(isNominated(bip), "Governance: Not nominated."); require( block.timestamp >= timestamp(bip).add(C.getGovernanceEmergencyPeriod()), "Governance: Too early."); require(isActive(bip), "Governance: Ended."); require( bipVotePercent(bip).greaterThanOrEqualTo(C.getGovernanceEmergencyThreshold()), "Governance: Must have super majority." ); endBip(bip); s.g.bips[bip].executed = true; cutBip(bip); pauseOrUnpauseBip(bip); incentivize(msg.sender, false, bip, C.getCommitIncentive()); emit Commit(msg.sender, bip); } function pauseOrUnpause(uint32 bip) external { require(isNominated(bip), "Governance: Not nominated."); require(diamondCutIsEmpty(bip),"Governance: Has diamond cut."); require(isActive(bip), "Governance: Ended."); require( bipVotePercent(bip).greaterThanOrEqualTo(C.getGovernanceEmergencyThreshold()), "Governance: Must have super majority." ); endBip(bip); s.g.bips[bip].executed = true; pauseOrUnpauseBip(bip); incentivize(msg.sender, false, bip, C.getCommitIncentive()); emit Commit(msg.sender, bip); } function incentivize(address account, bool compound, uint32 bipId, uint256 amount) private { if (compound) amount = LibIncentive.fracExp(amount, 100, incentiveTime(bipId), 2); IBean(s.c.bean).mint(account, amount); emit Incentivization(account, amount); } /** * Pause / Unpause **/ function ownerPause() external { LibDiamond.enforceIsContractOwner(); pause(); } function ownerUnpause() external { LibDiamond.enforceIsContractOwner(); unpause(); } function pause() private { if (s.paused) return; s.paused = true; s.o.initialized = false; s.pausedAt = uint128(block.timestamp); emit Pause(msg.sender, block.timestamp); } function unpause() private { if (!s.paused) return; s.paused = false; uint256 timePassed = block.timestamp.sub(uint(s.pausedAt)); timePassed = (timePassed.div(3600).add(1)).mul(3600); s.season.start = s.season.start.add(timePassed); emit Unpause(msg.sender, block.timestamp, timePassed); } function pauseOrUnpauseBip(uint32 bipId) private { if (s.g.bips[bipId].pauseOrUnpause == 1) pause(); else if (s.g.bips[bipId].pauseOrUnpause == 2) unpause(); } }
8,413
18
// Return the owner of a subdomain (e.g. "radek.startonchain.eth"), _subdomain - sub domain name only e.g. "radek" _domain - parent domain name e.g. "startonchain" _topdomain - parent domain name e.g. "eth", "xyz" /
function subdomainOwner(string _subdomain, string _domain, string _topdomain) public view returns (address) { bytes32 topdomainNamehash = keccak256(abi.encodePacked(emptyNamehash, keccak256(abi.encodePacked(_topdomain)))); bytes32 domainNamehash = keccak256(abi.encodePacked(topdomainNamehash, keccak256(abi.encodePacked(_domain)))); bytes32 subdomainNamehash = keccak256(abi.encodePacked(domainNamehash, keccak256(abi.encodePacked(_subdomain)))); return registry.owner(subdomainNamehash); }
function subdomainOwner(string _subdomain, string _domain, string _topdomain) public view returns (address) { bytes32 topdomainNamehash = keccak256(abi.encodePacked(emptyNamehash, keccak256(abi.encodePacked(_topdomain)))); bytes32 domainNamehash = keccak256(abi.encodePacked(topdomainNamehash, keccak256(abi.encodePacked(_domain)))); bytes32 subdomainNamehash = keccak256(abi.encodePacked(domainNamehash, keccak256(abi.encodePacked(_subdomain)))); return registry.owner(subdomainNamehash); }
42,172
10
// Redeem RToken for basket collateral/amount {qRTok} The quantity {qRToken} of RToken to redeem/revertOnPartialRedemption If true, will revert on partial redemption/ @custom:interaction
function redeem(uint256 amount, bool revertOnPartialRedemption) external;
function redeem(uint256 amount, bool revertOnPartialRedemption) external;
20,801
92
// 3
uint256 totalLocked; for(uint idx = 0; idx < timelockList[holder].length ; idx++ ){ totalLocked = totalLocked.add(timelockList[holder][idx]._amount); }
uint256 totalLocked; for(uint idx = 0; idx < timelockList[holder].length ; idx++ ){ totalLocked = totalLocked.add(timelockList[holder][idx]._amount); }
28,356
1
// is everything okay?
require(campaign.deadline < block.timestamp, "The deadline should be a date in the future."); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image = _image; numberOfCampaigns++; return numberOfCampaigns -1;
require(campaign.deadline < block.timestamp, "The deadline should be a date in the future."); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image = _image; numberOfCampaigns++; return numberOfCampaigns -1;
13,959
72
// This will suffice for checking _exists(nextTokenId), as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership .startTimestamp; }
if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership .startTimestamp; }
3,959
15
// call _claim()
_claim(index);
_claim(index);
37,896
10
// Onboard a new jurisdicton/name Name of jurisdicton/taxRate Tax rate of jurisdictions/inventory Inventory address of jurisdicton/reserve Reserve address of jurisdicton
function add(string name, uint taxRate, address inventory, address reserve) public onlyOwner(){ bytes32 code = keccak256(abi.encodePacked(name)); require(!jurisidictionExists[code], "Jurisdiction already in use"); require(!isBitcarbon[inventory], "Inventory address already in use"); require(!isBitcarbon[reserve], "Reserve address already in use"); Jurisdiction memory newJurisdiction = Jurisdiction({ code : code, name : name, taxRate : taxRate, inventory : inventory, reserve : reserve }); jurisdictions[code] = newJurisdiction; codes.push(code); jurisidictionExists[code] = true; isBitcarbon[reserve] = true; isBitcarbon[inventory] = true; bitcarbonJurisdiction[reserve] = code; bitcarbonJurisdiction[inventory] = code; emit JurisdictionAdded(code, name, taxRate, inventory, reserve, now); }
function add(string name, uint taxRate, address inventory, address reserve) public onlyOwner(){ bytes32 code = keccak256(abi.encodePacked(name)); require(!jurisidictionExists[code], "Jurisdiction already in use"); require(!isBitcarbon[inventory], "Inventory address already in use"); require(!isBitcarbon[reserve], "Reserve address already in use"); Jurisdiction memory newJurisdiction = Jurisdiction({ code : code, name : name, taxRate : taxRate, inventory : inventory, reserve : reserve }); jurisdictions[code] = newJurisdiction; codes.push(code); jurisidictionExists[code] = true; isBitcarbon[reserve] = true; isBitcarbon[inventory] = true; bitcarbonJurisdiction[reserve] = code; bitcarbonJurisdiction[inventory] = code; emit JurisdictionAdded(code, name, taxRate, inventory, reserve, now); }
43,864
48
// Check if a token access is valid. _tokenId ID of the NFT to validate. _hash Hash of tokenId + newOwner address. _tokenType Type of token access (0=view, 1=transfer). /
function isTokenValid(uint256 _tokenId, bytes32 _hash, uint256 _tokenType, bytes memory _signature) public view returns (bool){ return ECDSA.recover(_hash, _signature) == tokenAccess[_tokenId][_tokenType]; }
function isTokenValid(uint256 _tokenId, bytes32 _hash, uint256 _tokenType, bytes memory _signature) public view returns (bool){ return ECDSA.recover(_hash, _signature) == tokenAccess[_tokenId][_tokenType]; }
43,483
32
// offhand
rarities[5] = [255]; aliases[5] = [0];
rarities[5] = [255]; aliases[5] = [0];
56,669
2
// Returns true if the contract is currently in the ended stage return True if ended /
function isEnded() public view returns (bool);
function isEnded() public view returns (bool);
42,095
14
// Allow the owner to update the mint authority.//_nextMintAuthority The new mint authority address.
function updateMintAuthority(address _nextMintAuthority) public onlyOwnerOrMintAuthority
function updateMintAuthority(address _nextMintAuthority) public onlyOwnerOrMintAuthority
37,616
34
// pragma solidity 0.6.12; /
/* import {Fileable, ChainlogLike} from "dss-exec-lib/DssExecLib.sol"; */ /* import "dss-exec-lib/DssExec.sol"; */ /* import "dss-exec-lib/DssAction.sol"; */ /* import "dss-interfaces/dss/ClipAbstract.sol"; */ /* import "dss-interfaces/dss/ClipperMomAbstract.sol"; */ /* import "dss-interfaces/dss/OsmAbstract.sol"; */ struct Collateral { bytes32 ilk; address vat; address vow; address spotter; address cat; address dog; address end; address esm; address flipperMom; address clipperMom; address ilkRegistry; address pip; address clipper; address flipper; address calc; uint256 hole; uint256 chop; uint256 buf; uint256 tail; uint256 cusp; uint256 chip; uint256 tip; uint256 cut; uint256 step; uint256 tolerance; bytes32 clipKey; bytes32 calcKey; bytes32 flipKey; }
/* import {Fileable, ChainlogLike} from "dss-exec-lib/DssExecLib.sol"; */ /* import "dss-exec-lib/DssExec.sol"; */ /* import "dss-exec-lib/DssAction.sol"; */ /* import "dss-interfaces/dss/ClipAbstract.sol"; */ /* import "dss-interfaces/dss/ClipperMomAbstract.sol"; */ /* import "dss-interfaces/dss/OsmAbstract.sol"; */ struct Collateral { bytes32 ilk; address vat; address vow; address spotter; address cat; address dog; address end; address esm; address flipperMom; address clipperMom; address ilkRegistry; address pip; address clipper; address flipper; address calc; uint256 hole; uint256 chop; uint256 buf; uint256 tail; uint256 cusp; uint256 chip; uint256 tip; uint256 cut; uint256 step; uint256 tolerance; bytes32 clipKey; bytes32 calcKey; bytes32 flipKey; }
46,896
438
// Extract the middle four digits
iroiroId = (iroiroRemixId / 10) % 10000;
iroiroId = (iroiroRemixId / 10) % 10000;
32,236
83
// User award balance
mapping(address => uint) public rewards; mapping(address => uint) public userRewardPerTokenPaid; uint private _start; uint private _end;
mapping(address => uint) public rewards; mapping(address => uint) public userRewardPerTokenPaid; uint private _start; uint private _end;
14,077
1
// Converts token0 dust (if any) to earned tokens
uint256 token0Amt = IERC20(token0Address).balanceOf(address(this)); if (token0Amt > 0 && token0Address != earnedAddress) {
uint256 token0Amt = IERC20(token0Address).balanceOf(address(this)); if (token0Amt > 0 && token0Address != earnedAddress) {
46,985
203
// Add tokenId to matrix
function incrementToken(uint256 _tokenId) internal { uint256 maxIndex = maxSupply() - tokenCount(); // If the last available tokenID is still unused... if (tokenMatrix[maxIndex - 1] == 0) { // ...store that ID in the current matrix position. tokenMatrix[_tokenId] = maxIndex - 1; } else { // ...otherwise copy over the stored number to the current matrix position. tokenMatrix[_tokenId] = tokenMatrix[maxIndex - 1]; } super.onlyIncrement(); }
function incrementToken(uint256 _tokenId) internal { uint256 maxIndex = maxSupply() - tokenCount(); // If the last available tokenID is still unused... if (tokenMatrix[maxIndex - 1] == 0) { // ...store that ID in the current matrix position. tokenMatrix[_tokenId] = maxIndex - 1; } else { // ...otherwise copy over the stored number to the current matrix position. tokenMatrix[_tokenId] = tokenMatrix[maxIndex - 1]; } super.onlyIncrement(); }
23,670
113
// Returns a human-readable message for a given restriction code/restrictionCode Identifier for looking up a message/ return Text showing the restriction's reasoning/Overwrite with your custom message and restrictionCode handling
function messageForTransferRestriction (uint8 restrictionCode) public view returns (string memory);
function messageForTransferRestriction (uint8 restrictionCode) public view returns (string memory);
9,090
17
// The block at which voting ends: votes must be cast prior to this block
uint endBlock;
uint endBlock;
39,245
122
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). To add or remove collateral, use _addCollateral() and _removeCollateral().
Unsigned rawCollateral;
Unsigned rawCollateral;
29,048
12
// Auth2 Manages USDP's system access copy of Auth from VaultParameters.sol but with immutable vaultParameters for saving gas /
contract Auth2 { // address of the the contract with vault parameters VaultParameters public immutable vaultParameters; constructor(address _parameters) { require(_parameters != address(0), "Unit Protocol: ZERO_ADDRESS"); vaultParameters = VaultParameters(_parameters); } // ensures tx's sender is a manager modifier onlyManager() { require(vaultParameters.isManager(msg.sender), "Unit Protocol: AUTH_FAILED"); _; } // ensures tx's sender is able to modify the Vault modifier hasVaultAccess() { require(vaultParameters.canModifyVault(msg.sender), "Unit Protocol: AUTH_FAILED"); _; } // ensures tx's sender is the Vault modifier onlyVault() { require(msg.sender == vaultParameters.vault(), "Unit Protocol: AUTH_FAILED"); _; } }
contract Auth2 { // address of the the contract with vault parameters VaultParameters public immutable vaultParameters; constructor(address _parameters) { require(_parameters != address(0), "Unit Protocol: ZERO_ADDRESS"); vaultParameters = VaultParameters(_parameters); } // ensures tx's sender is a manager modifier onlyManager() { require(vaultParameters.isManager(msg.sender), "Unit Protocol: AUTH_FAILED"); _; } // ensures tx's sender is able to modify the Vault modifier hasVaultAccess() { require(vaultParameters.canModifyVault(msg.sender), "Unit Protocol: AUTH_FAILED"); _; } // ensures tx's sender is the Vault modifier onlyVault() { require(msg.sender == vaultParameters.vault(), "Unit Protocol: AUTH_FAILED"); _; } }
6,749
259
// pragma solidity >=0.6.0 <0.8.0; // Standard math utilities missing in the Solidity language. /
library Math_4 { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } }
library Math_4 { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } }
16,996
255
// Returns the total supply of votes available at the end of a past block (`blockNumber`). NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.Votes that have not been delegated are still part of total supply, even though they would not participate in avote. /
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
51,449
329
// Can only force recover after either: 1) The loan was called and the call period has elapsed 2) The maxDuration of the position has elapsed
require( /* solium-disable-next-line */ ( position.callTimestamp > 0 && block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit) ) || ( block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration) ), "ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet" );
require( /* solium-disable-next-line */ ( position.callTimestamp > 0 && block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit) ) || ( block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration) ), "ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet" );
72,321
208
// keccak256(abi.encodePacked("approvedCreatorRegistry")) = 0x74cb6de1099c3d993f336da7af5394f68038a23980424e1ae5723d4110522be4 keccak256(abi.encodePacked("approvedCreatorRegistryReadOnly")) = 0x9732b26dfb8751e6f1f71e8f21b28a237cfe383953dce7db3dfa1777abdb2791
require( contractType == 0x74cb6de1099c3d993f336da7af5394f68038a23980424e1ae5723d4110522be4 || contractType == 0x9732b26dfb8751e6f1f71e8f21b28a237cfe383953dce7db3dfa1777abdb2791, "not crtrRegistry"); creatorRegistryStore = candidateCreatorRegistryStore;
require( contractType == 0x74cb6de1099c3d993f336da7af5394f68038a23980424e1ae5723d4110522be4 || contractType == 0x9732b26dfb8751e6f1f71e8f21b28a237cfe383953dce7db3dfa1777abdb2791, "not crtrRegistry"); creatorRegistryStore = candidateCreatorRegistryStore;
36,872
31
// fulfillRandomness handles the VRF response. Your contract must implement it.The VRFCoordinator expects a calling contract to have a method with this signature, and will call it once it has verified the proof associated with the randomness.requestId The Id initially returned by requestRandomness randomness the VRF output /
function fulfillRandomness(bytes32 requestId, uint256 randomness) external virtual;
function fulfillRandomness(bytes32 requestId, uint256 randomness) external virtual;
39,843
15
// dev claim managementFees from strategy.when tx completed managementFees = 0 /
function claimManagementFees() public returns (uint256) { uint256 feeTokenBalance = _config.tokens[feeTokenId].balanceOf(address(this)); uint256 transferBalance = managementFees > feeTokenBalance ? feeTokenBalance : managementFees; if (transferBalance > 0) { _config.tokens[feeTokenId].safeTransfer(feeDistributor, transferBalance); } managementFees = 0; return transferBalance; }
function claimManagementFees() public returns (uint256) { uint256 feeTokenBalance = _config.tokens[feeTokenId].balanceOf(address(this)); uint256 transferBalance = managementFees > feeTokenBalance ? feeTokenBalance : managementFees; if (transferBalance > 0) { _config.tokens[feeTokenId].safeTransfer(feeDistributor, transferBalance); } managementFees = 0; return transferBalance; }
31,055
5
// 4. nondet
function nondet() public pure returns(uint8)
function nondet() public pure returns(uint8)
17,964