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
70
// Read and consume the next 16 bytes from the buffer as an `uint128`./buffer An instance of `Buffer`./ return value The `uint128` value of the next 16 bytes in the buffer counting from the cursor position.
function readUint128(Buffer memory buffer) internal pure withinRange(buffer.cursor + 16, buffer.data.length) returns (uint128 value)
function readUint128(Buffer memory buffer) internal pure withinRange(buffer.cursor + 16, buffer.data.length) returns (uint128 value)
18,890
25
// ============ Internal Functions ============ // Gets the PrizeDistributionBuffer for a drawId _buffer DrawRingBufferLib.Buffer _drawId drawId /
function _getPrizeDistribution(DrawRingBufferLib.Buffer memory _buffer, uint32 _drawId) internal view returns (IPrizeDistributionBuffer.PrizeDistribution memory)
function _getPrizeDistribution(DrawRingBufferLib.Buffer memory _buffer, uint32 _drawId) internal view returns (IPrizeDistributionBuffer.PrizeDistribution memory)
24,598
5
// Count of all guards /
uint256 internal guardCount;
uint256 internal guardCount;
5,721
182
// Last block number that NTSs distribution occurs.
uint256 public lastRewardBlock;
uint256 public lastRewardBlock;
616
2
// Batch version of mint function /
function mintBatch( address to, uint256[] calldata tokenIds,
function mintBatch( address to, uint256[] calldata tokenIds,
9,673
147
// increment token balance!
IERC20(TRUSTED_DEPOSIT_TOKEN_ADDRESS).safeTransferFrom(msg.sender, address(this), amount); totalTokensDepositedByUser[msg.sender] = totalTokensDepositedByUser[msg.sender].add(amount); IERC20(TRUSTED_DEPOSIT_TOKEN_ADDRESS).safeApprove(TRUSTED_CTOKEN_ADDRESS, 0); IERC20(TRUSTED_DEPOSIT_TOKEN_ADDRESS).safeApprove(TRUSTED_CTOKEN_ADDRESS, amount); uint oldCTokenBalance = IERC20(TRUSTED_CTOKEN_ADDRESS).balanceOf(address(this)); require(CErc20(TRUSTED_CTOKEN_ADDRESS).mint(amount) == 0, "mint failed!");
IERC20(TRUSTED_DEPOSIT_TOKEN_ADDRESS).safeTransferFrom(msg.sender, address(this), amount); totalTokensDepositedByUser[msg.sender] = totalTokensDepositedByUser[msg.sender].add(amount); IERC20(TRUSTED_DEPOSIT_TOKEN_ADDRESS).safeApprove(TRUSTED_CTOKEN_ADDRESS, 0); IERC20(TRUSTED_DEPOSIT_TOKEN_ADDRESS).safeApprove(TRUSTED_CTOKEN_ADDRESS, amount); uint oldCTokenBalance = IERC20(TRUSTED_CTOKEN_ADDRESS).balanceOf(address(this)); require(CErc20(TRUSTED_CTOKEN_ADDRESS).mint(amount) == 0, "mint failed!");
28,292
19
// Estimate Royalty & Split in half
uint256 royalty = getPercentOf(getCommonRate(), price, 6) / 2;
uint256 royalty = getPercentOf(getCommonRate(), price, 6) / 2;
23,164
5
// Get the URI of the NFT's metadata/This function is part of the IERC721 standard/_tokenId The ID of the NFT to get the URI for/ return The URI of the NFT's metadata
function tokenURI(uint256 _tokenId) external view virtual override returns (string memory) { return string.concat(uri, uint256(_tokenId).toString(), ".json"); }
function tokenURI(uint256 _tokenId) external view virtual override returns (string memory) { return string.concat(uri, uint256(_tokenId).toString(), ".json"); }
19,022
31
// Returns the scaled balance of the user. The scaled balance is the sum of all theupdated stored balance divided by the reserve's liquidity index at the moment of the update user The user whose balance is calculatedreturn The scaled balance of the user /
{ return super.balanceOf(user); }
{ return super.balanceOf(user); }
8,284
143
// ========== VIEW FUNCTIONS ========== // There is a motion in progress on the specifiedaccount, and votes are being accepted in that motion. /
function motionVoting(uint motionID) public view returns (bool)
function motionVoting(uint motionID) public view returns (bool)
73,628
0
// Check for data 0-->new user 1->user already exists 2->for logging out the user
mapping(string=>string) private user_data; mapping(string=>string) private logindata; mapping(string=>uint) private data_checker; mapping (string=>uint) private activeUsers;
mapping(string=>string) private user_data; mapping(string=>string) private logindata; mapping(string=>uint) private data_checker; mapping (string=>uint) private activeUsers;
32,043
3
// Redeem any invested tokens from the pool
function redeem(uint256 _shares) external;
function redeem(uint256 _shares) external;
5,618
12
// require(balances[_from] >= _value && allowed[_from][msg.sender] >=_value && balances[_to] + _value > balances[_to]);
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value;//接收账户增加token数量_value balances[_from] -= _value; //支出账户_from减去token数量_value allowed[_from][msg.sender] -= _value;//消息发送者可以从账户_from中转出的数量减少_value Transfer(_from, _to, _value);//触发转币交易事件 return true;
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value;//接收账户增加token数量_value balances[_from] -= _value; //支出账户_from减去token数量_value allowed[_from][msg.sender] -= _value;//消息发送者可以从账户_from中转出的数量减少_value Transfer(_from, _to, _value);//触发转币交易事件 return true;
53,658
128
// Only whitelisted can transfer tokens, and only to whitelisted addresses _to The address where tokens will be sent to _value The amount of tokens to be sent /
function transfer(address _to, uint256 _value) public onlyWhitelisted returns(bool) { //If the destination is not whitelisted, try to add it (only admins modifier) if(!isWhitelisted(_to) && !whitelistUnlocked) addToWhitelist(_to); return super.transfer(_to, _value); }
function transfer(address _to, uint256 _value) public onlyWhitelisted returns(bool) { //If the destination is not whitelisted, try to add it (only admins modifier) if(!isWhitelisted(_to) && !whitelistUnlocked) addToWhitelist(_to); return super.transfer(_to, _value); }
22,661
166
// Max supply and price of Baddies (0.049 ETH)
uint256 public constant MAX_BADDIES = 9999; uint256 public reserved = 1000; uint256 pricePerBaddie = 0.049 ether; uint256 constant CREATOR_SHARE = 90; address baddiesAddress = 0xb27A7637eCdf570b624B97758074220E7aC71eA4;
uint256 public constant MAX_BADDIES = 9999; uint256 public reserved = 1000; uint256 pricePerBaddie = 0.049 ether; uint256 constant CREATOR_SHARE = 90; address baddiesAddress = 0xb27A7637eCdf570b624B97758074220E7aC71eA4;
31,932
10
// Get the pool margin of the liquidity pool liquidityPool The address of the liquidity poolreturn isSynced True if the funding state is synced to real-time data. False if error happens (oracle error, zero price etc.). In this case, trading, withdraw (if position != 0), addLiquidity, removeLiquidity will failreturn poolMargin The pool margin of the liquidity pool /
function getPoolMargin(address liquidityPool) public returns ( bool isSynced, int256 poolMargin, bool isSafe )
function getPoolMargin(address liquidityPool) public returns ( bool isSynced, int256 poolMargin, bool isSafe )
49,219
52
// Gets the balance of the specified address.owner The address to query the the balance of. return An uint256 representing the amount owned by the passed address./
function balanceOf(address owner) external view returns (uint256)
function balanceOf(address owner) external view returns (uint256)
82,393
7
// Emitted on swapBorrowRateMode() reserve The address of the underlying asset of the reserve user The address of the user swapping his rate mode interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable /
event SwapBorrowRateMode(
event SwapBorrowRateMode(
39,111
5
// ================ TRANSACTION FUNCTIONS ================ /
) external override whenNotPaused { require(startBlock < endBlock, "Web3Gas: startBlock must over endBlock"); require(startBlock >= lastEndBlock[account], "Web3Gas: startBlock must over claimEndBlock"); address signer = ECDSAUpgradeable.recover( _hashTypedDataV4(keccak256(abi.encode(ClAIM_TYPEHASH, account, gasAmount, startBlock, endBlock))), v, r, s ); require(claimSigner == signer, "Web3Gas: not claimSigner"); uint256 tokenAmount = predictToken(gasAmount); _mint(account, tokenAmount); emit Mint(account, tokenAmount); lastEndBlock[_msgSender()] = endBlock; }
) external override whenNotPaused { require(startBlock < endBlock, "Web3Gas: startBlock must over endBlock"); require(startBlock >= lastEndBlock[account], "Web3Gas: startBlock must over claimEndBlock"); address signer = ECDSAUpgradeable.recover( _hashTypedDataV4(keccak256(abi.encode(ClAIM_TYPEHASH, account, gasAmount, startBlock, endBlock))), v, r, s ); require(claimSigner == signer, "Web3Gas: not claimSigner"); uint256 tokenAmount = predictToken(gasAmount); _mint(account, tokenAmount); emit Mint(account, tokenAmount); lastEndBlock[_msgSender()] = endBlock; }
14,118
85
// 3. Convert the position's LP tokens to the underlying assets.
uint256 userWETH = lpBalance.mul(totalWETH).div(lpSupply); uint256 userfToken = lpBalance.mul(totalfToken).div(lpSupply);
uint256 userWETH = lpBalance.mul(totalWETH).div(lpSupply); uint256 userfToken = lpBalance.mul(totalfToken).div(lpSupply);
18,654
172
// Verify the external contract is valid
require(address(transferRestrictions) != address(0), 'TransferRestrictions contract must be set');
require(address(transferRestrictions) != address(0), 'TransferRestrictions contract must be set');
37,977
19
// Sandwich protection mapping of last user deposits by block number
mapping(address => uint256) lastDeposit;
mapping(address => uint256) lastDeposit;
38,853
107
// Check personal cap
uint256 personalLendingAmount = _lendingAmounts[index][msg.sender].add(amount); require(personalLendingAmount <= round.personalCap, "ACEX DeFi: Exceeds personal cap.");
uint256 personalLendingAmount = _lendingAmounts[index][msg.sender].add(amount); require(personalLendingAmount <= round.personalCap, "ACEX DeFi: Exceeds personal cap.");
16,432
1
// Contract level metadata.
string private _contractURI; modifier onlyModuleAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "only module admin role"); _; }
string private _contractURI; modifier onlyModuleAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "only module admin role"); _; }
40,187
246
// update last token local index to point to proper place in the collection preserve global index and ownership info
tokens[sourceId] = tokens[sourceId]
tokens[sourceId] = tokens[sourceId]
24,846
8
// Calculate next supply rate for bBadger, given an `_amount` supplied_amount : new underlying amount supplied (eg badger token)return : yearly net rate /
function nextSupplyRate(uint256 _amount) public override view returns (uint256) { return 0; }
function nextSupplyRate(uint256 _amount) public override view returns (uint256) { return 0; }
7,352
7
// ISavingStrategy.redeemUnderlying implementation
function redeemUnderlying(uint256 redeemAmount) external onlyOwner returns (uint256) { uint256 aTotalBefore = aToken.totalSupply(); // TODO should we handle redeem failure? aToken.redeem(redeemAmount); uint256 aTotalAfter = aToken.totalSupply(); uint256 aBurnedAmount; require(aTotalAfter <= aTotalBefore, "Compound redeemed negative amount!?"); aBurnedAmount = aTotalBefore - aTotalAfter; token.transfer(msg.sender, redeemAmount); return aBurnedAmount; }
function redeemUnderlying(uint256 redeemAmount) external onlyOwner returns (uint256) { uint256 aTotalBefore = aToken.totalSupply(); // TODO should we handle redeem failure? aToken.redeem(redeemAmount); uint256 aTotalAfter = aToken.totalSupply(); uint256 aBurnedAmount; require(aTotalAfter <= aTotalBefore, "Compound redeemed negative amount!?"); aBurnedAmount = aTotalBefore - aTotalAfter; token.transfer(msg.sender, redeemAmount); return aBurnedAmount; }
5,892
52
// Do not check if pair is not a contract to avoid warning in txn log
if (!isContract(pair)) return (address(0), address(0)); return (tokenLookup(pair, token0Selector), tokenLookup(pair, token1Selector));
if (!isContract(pair)) return (address(0), address(0)); return (tokenLookup(pair, token0Selector), tokenLookup(pair, token1Selector));
16,740
0
// ´:°•.°+.•´.:˚.°.˚•´.°:°•.°•.•´.:˚.°.˚•´.°:°•.°+.•´.://CUSTOM ERRORS //.•°:°.´+˚.°.˚:.´•.+°.•°:´.´•.•°.•°:°.´:•˚°.°.˚:.´+°.•//The `length` of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
error HexLengthInsufficient();
13,044
0
// Manual assertion
uint min = 0; uint max_smallerArray = smallerArray.length; uint max_biggerArray = biggerArray.length; for(uint i = min; i <= max_smallerArray-1; i++){ for(uint j = min; j <= max_biggerArray-1; j++){ require(smallerArray[i] < biggerArray[j], "Counterexample found!"); }
uint min = 0; uint max_smallerArray = smallerArray.length; uint max_biggerArray = biggerArray.length; for(uint i = min; i <= max_smallerArray-1; i++){ for(uint j = min; j <= max_biggerArray-1; j++){ require(smallerArray[i] < biggerArray[j], "Counterexample found!"); }
42,050
65
// 22 IN DATA / SET DATA / GET DATA / STRING / PUBLIC / ONLY OWNER / CONSTANT
string inPI_edit_22 = " une première phrase " ;
string inPI_edit_22 = " une première phrase " ;
69,738
12
// Token State This contract manages lockers to control token transferability.The SKALE Network has three types of locked tokens:- Tokens that are transferrable but are currently locked into delegation witha validator.- Tokens that are not transferable from one address to another, but may bedelegated to a validator `getAndUpdateLockedAmount`. This lock enforcesProof-of-Use requirements.- Tokens that are neither transferable nor delegatable`getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing. /
contract TokenState is Permissions, ILocker { string[] private _lockers; DelegationController private _delegationController; /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { if (address(_delegationController) == address(0)) { _delegationController = DelegationController(contractManager.getContract("DelegationController")); } uint locked = 0; if (_delegationController.getDelegationsByHolderLength(holder) > 0) { // the holder ever delegated for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } } return locked; } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a {LockerWasRemoved} event. */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } }
contract TokenState is Permissions, ILocker { string[] private _lockers; DelegationController private _delegationController; /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { if (address(_delegationController) == address(0)) { _delegationController = DelegationController(contractManager.getContract("DelegationController")); } uint locked = 0; if (_delegationController.getDelegationsByHolderLength(holder) > 0) { // the holder ever delegated for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } } return locked; } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a {LockerWasRemoved} event. */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } }
69,215
145
// Here we calc the pool share one can withdraw given the amount of IdleToken they want to burnThis method triggers a rebalance of the pools if neededNOTE: If the contract is paused or iToken price has decreased one can still redeem but no rebalance happens.NOTE 2: If iToken price has decresed one should not redeem (but can do it) otherwise he would capitalize the loss.Ideally one should wait until the black swan event is terminated_amount : amount of IdleTokens to be burnedreturn redeemedTokens : amount of underlying tokens redeemed /
function redeemIdleToken(uint256 _amount) external returns (uint256 redeemedTokens);
function redeemIdleToken(uint256 _amount) external returns (uint256 redeemedTokens);
35,160
28
// Returns true if `account` is a contract. [IMPORTANT]====It is unsafe to assume that an address for which this function returnsfalse is an externally-owned account (EOA) and not a contract. Among others, `isContract` will return false for the followingtypes of addresses:- an externally-owned account - a contract in construction - an address where a contract will be created - an address where a contract lived, but was destroyed==== /
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly {codehash := extcodehash(account)} return (codehash != accountHash && codehash != 0x0); }
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly {codehash := extcodehash(account)} return (codehash != accountHash && codehash != 0x0); }
25,482
3
// thirdweb.com /
library InitStorage { /// @dev The location of the storage of the entrypoint contract's data. bytes32 constant INIT_STORAGE_POSITION = keccak256("init.storage"); /// @dev Layout of the entrypoint contract's storage. struct Data { bool initialized; } /// @dev Returns the entrypoint contract's data at the relevant storage location. function initStorage() internal pure returns (Data storage initData) { bytes32 position = INIT_STORAGE_POSITION; assembly { initData.slot := position } } }
library InitStorage { /// @dev The location of the storage of the entrypoint contract's data. bytes32 constant INIT_STORAGE_POSITION = keccak256("init.storage"); /// @dev Layout of the entrypoint contract's storage. struct Data { bool initialized; } /// @dev Returns the entrypoint contract's data at the relevant storage location. function initStorage() internal pure returns (Data storage initData) { bytes32 position = INIT_STORAGE_POSITION; assembly { initData.slot := position } } }
16,212
12
// Triggers new promos as well as being able to end the current promo
function tooglePromo() public onlyOwner{ promo = !promo; emit AirDropPromo(msg.sender, promo); }
function tooglePromo() public onlyOwner{ promo = !promo; emit AirDropPromo(msg.sender, promo); }
47,449
224
// Add on to existing deposit, if it exists
Deposit storage curDeposit = deposits[msg.sender]; uint lockDepositUntil = block.timestamp + (nDays*86400); Deposit memory myDeposit = Deposit({ lockedUntil: curDeposit.lockedUntil > lockDepositUntil ? curDeposit.lockedUntil : lockDepositUntil, poolTokenAmount: newTokensToMint+curDeposit.poolTokenAmount });
Deposit storage curDeposit = deposits[msg.sender]; uint lockDepositUntil = block.timestamp + (nDays*86400); Deposit memory myDeposit = Deposit({ lockedUntil: curDeposit.lockedUntil > lockDepositUntil ? curDeposit.lockedUntil : lockDepositUntil, poolTokenAmount: newTokensToMint+curDeposit.poolTokenAmount });
58,923
9
// Add the `receive()` special function that receives eth and calls stake()
receive() external payable { stake(); }
receive() external payable { stake(); }
4,285
28
// returns the amount of currency currently in the reserve
function totalBalance() public view returns (uint) { return balance_; }
function totalBalance() public view returns (uint) { return balance_; }
10,283
245
// old holder is not a voter
else if (fromPrice == 0) { votingTokens += _amount; reserveTotal += _amount * toPrice; }
else if (fromPrice == 0) { votingTokens += _amount; reserveTotal += _amount * toPrice; }
65,518
5
// Store purchasers in memory rather than contract's storage
address[16] memory purchasers = purchases.getPurchasers(); Assert.equal(purchasers[expectedWallpaperId], expectedPurchaser, "Owner of the expected wallpaper should be this contract");
address[16] memory purchasers = purchases.getPurchasers(); Assert.equal(purchasers[expectedWallpaperId], expectedPurchaser, "Owner of the expected wallpaper should be this contract");
56,030
78
// Claim the given amount of the token to the given address. Reverts if the inputs are invalid.
function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external; function setRoot(bytes32 _merkleRoot) external;
function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external; function setRoot(bytes32 _merkleRoot) external;
12,704
248
// set contract owner
_ownershipOwner = msg.sender;
_ownershipOwner = msg.sender;
52,230
147
// _addLiquidity in any proportion of tokenA or tokenBThe inheritor contract should implement _getABPrice and _onAddLiquidity functionsamountOfA amount of TokenA to add amountOfB amount of TokenB to add owner address of the account that will have ownership of the liquidity /
function _addLiquidity( uint256 amountOfA, uint256 amountOfB, address owner
function _addLiquidity( uint256 amountOfA, uint256 amountOfB, address owner
18,754
3
// calculate value
return (IERC20(hedge).balanceOf(address(this)).mul(IOracle(theOracle).priceOf(hedge)).div(2) + IERC20(wbtc).balanceOf(address(this)).mul(1e10).mul(IOracle(theOracle).wbtcPriceOne())).div(variableReduction).div(IERC20(control).totalSupply());
return (IERC20(hedge).balanceOf(address(this)).mul(IOracle(theOracle).priceOf(hedge)).div(2) + IERC20(wbtc).balanceOf(address(this)).mul(1e10).mul(IOracle(theOracle).wbtcPriceOne())).div(variableReduction).div(IERC20(control).totalSupply());
10,474
64
// Initializes the contract setting the deployer as the initial registryRegistryAdmin. /
constructor () internal { address msgSender = _msgSender(); _registryAdmin = msgSender; emit RegistryManagementTransferred(address(0), msgSender); }
constructor () internal { address msgSender = _msgSender(); _registryAdmin = msgSender; emit RegistryManagementTransferred(address(0), msgSender); }
36,938
47
// Get the current position
MozartTypes.Position storage position = positions[positionId]; Decimal.D256 memory currentPrice = oracle.fetchCurrentPrice();
MozartTypes.Position storage position = positions[positionId]; Decimal.D256 memory currentPrice = oracle.fetchCurrentPrice();
49,875
5
// returns the unclaimed rewards of the user user the address of the user asset The asset to incentivizereturn the user index for the asset /
function getUserAssetData(address user, address asset) external view returns (uint256);
function getUserAssetData(address user, address asset) external view returns (uint256);
19,895
31
// --- Math --- Taken from official DSR contract: https:github.com/makerdao/dss/blob/master/src/pot.sol
uint constant RAY = 10 ** 27;
uint constant RAY = 10 ** 27;
4,751
32
// Add Operator commission log
OperatorCommision memory comp; comp.name = "PRE_WITHDRAWL_STAKE_COMMISION"; comp.amount = stake2Transfer; comp.timestamp = block.timestamp; OpCommisions.push(comp);
OperatorCommision memory comp; comp.name = "PRE_WITHDRAWL_STAKE_COMMISION"; comp.amount = stake2Transfer; comp.timestamp = block.timestamp; OpCommisions.push(comp);
3,341
49
// @inheritdocVRFConsumerBase
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomNumbers[requestId] = randomness; filled[requestId] = true; }
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomNumbers[requestId] = randomness; filled[requestId] = true; }
63,032
14
// Return price for `currency => Token _id` trades with an exact token amount. _idsArray of ID of tokens bought. _tokensBought Amount of Tokens bought.return Amount of currency needed to buy Tokens in _ids for amounts in _tokensBought /
function getPrice_currencyToToken(uint256[] calldata _ids, uint256[] calldata _tokensBought) external view returns (uint256[] memory);
function getPrice_currencyToToken(uint256[] calldata _ids, uint256[] calldata _tokensBought) external view returns (uint256[] memory);
39,793
75
// simulate LP state update
usdcReserves = add(usdcReserves, usdcAmount); maiReserves = sub(maiReserves, maiAmount);
usdcReserves = add(usdcReserves, usdcAmount); maiReserves = sub(maiReserves, maiAmount);
31,184
7
// Sum the total amount of NFTs being gifted
for(uint i = 0; i < quantity.length; ++i){ totalQuantity += quantity[i]; }
for(uint i = 0; i < quantity.length; ++i){ totalQuantity += quantity[i]; }
30,425
13
// Override this hook called by the base class `onSwap`, to check whether we are doing a regular swap,or a swap involving BPT, which is equivalent to a single token join or exit. Since one of the Pool'stokens is the preminted BPT, we need to handle swaps where BPT is involved separately. At this point, the balances are unscaled. The indices are coming from the Vault, so they are indices intothe array of registered tokens (including BPT). If this is a swap involving BPT, call `_swapWithBpt`, which computes the amountOut using the swapFeePercentageand charges protocol fees, in the same manner as
function _swapGivenIn( SwapRequest memory swapRequest, uint256[] memory registeredBalances, uint256 registeredIndexIn, uint256 registeredIndexOut, uint256[] memory scalingFactors
function _swapGivenIn( SwapRequest memory swapRequest, uint256[] memory registeredBalances, uint256 registeredIndexIn, uint256 registeredIndexOut, uint256[] memory scalingFactors
9,984
38
// List of enabled Resources; Resources provide data, functionality, or permissions that can be drawn upon from Module, SetTokens or factories
address[] public resources;
address[] public resources;
34,321
3
// This maps from a hash to the data for this topic. Note: the hash is a hash of the "subject" or "topic" of the message.
mapping(bytes32 => TopicData) topics;
mapping(bytes32 => TopicData) topics;
41,134
283
// Grab a reference to the egg in storage.
Alpaca storage egg = alpacas[_id];
Alpaca storage egg = alpacas[_id];
52,505
5
// Emits a {Transfer} event./
function transfer(address recipient, uint256 amount) external returns(bool);
function transfer(address recipient, uint256 amount) external returns(bool);
2,347
27
// --- PRIVATE FUNCTIONS --- / Creates a new VNF id for keeping track of VNF instantiations
function createDeploymentId() private returns (uint) { return nextDeploymentId++; }
function createDeploymentId() private returns (uint) { return nextDeploymentId++; }
5,962
58
// Transfer coin for a specified addressesfrom The address to transfer from.to The address to transfer to.value The amount to be transferred./
function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); require(value > 0); require(!mastercardUsers[from]); if(publicLock && !walletLock){ require( SGCUsers[from] && SGCUsers[to] ); } if(isMinter(from)){ _addSGCUsers(to); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } else{ require(!walletLock); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } }
function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); require(value > 0); require(!mastercardUsers[from]); if(publicLock && !walletLock){ require( SGCUsers[from] && SGCUsers[to] ); } if(isMinter(from)){ _addSGCUsers(to); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } else{ require(!walletLock); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } }
51,212
769
// Draws down the funds (and locks the pool) to the borrower address. Can only be called by the borrower amount The amount to drawdown from the creditline (must be < limit) /
function drawdown(uint256 amount) external override onlyLocker whenNotPaused { require(!drawdownsPaused, "Drawdowns are paused"); if (!locked()) { // Assumes the senior pool has invested already (saves the borrower a separate transaction to lock the pool) _lockPool(); } // Drawdown only draws down from the current slice for simplicity. It's harder to account for how much // money is available from previous slices since depositors can redeem after unlock. PoolSlice storage currentSlice = poolSlices[poolSlices.length.sub(1)]; uint256 amountAvailable = sharePriceToUsdc( currentSlice.juniorTranche.principalSharePrice, currentSlice.juniorTranche.principalDeposited ); amountAvailable = amountAvailable.add( sharePriceToUsdc(currentSlice.seniorTranche.principalSharePrice, currentSlice.seniorTranche.principalDeposited) ); require(amount <= amountAvailable, "Insufficient funds in slice"); creditLine.drawdown(amount); // Update the share price to reflect the amount remaining in the pool uint256 amountRemaining = amountAvailable.sub(amount); uint256 oldJuniorPrincipalSharePrice = currentSlice.juniorTranche.principalSharePrice; uint256 oldSeniorPrincipalSharePrice = currentSlice.seniorTranche.principalSharePrice; currentSlice.juniorTranche.principalSharePrice = currentSlice.juniorTranche.calculateExpectedSharePrice( amountRemaining, currentSlice ); currentSlice.seniorTranche.principalSharePrice = currentSlice.seniorTranche.calculateExpectedSharePrice( amountRemaining, currentSlice ); currentSlice.principalDeployed = currentSlice.principalDeployed.add(amount); totalDeployed = totalDeployed.add(amount); address borrower = creditLine.borrower(); safeERC20TransferFrom(config.getUSDC(), address(this), borrower, amount); emit DrawdownMade(borrower, amount); emit SharePriceUpdated( address(this), currentSlice.juniorTranche.id, currentSlice.juniorTranche.principalSharePrice, int256(oldJuniorPrincipalSharePrice.sub(currentSlice.juniorTranche.principalSharePrice)) * -1, currentSlice.juniorTranche.interestSharePrice, 0 ); emit SharePriceUpdated( address(this), currentSlice.seniorTranche.id, currentSlice.seniorTranche.principalSharePrice, int256(oldSeniorPrincipalSharePrice.sub(currentSlice.seniorTranche.principalSharePrice)) * -1, currentSlice.seniorTranche.interestSharePrice, 0 ); }
function drawdown(uint256 amount) external override onlyLocker whenNotPaused { require(!drawdownsPaused, "Drawdowns are paused"); if (!locked()) { // Assumes the senior pool has invested already (saves the borrower a separate transaction to lock the pool) _lockPool(); } // Drawdown only draws down from the current slice for simplicity. It's harder to account for how much // money is available from previous slices since depositors can redeem after unlock. PoolSlice storage currentSlice = poolSlices[poolSlices.length.sub(1)]; uint256 amountAvailable = sharePriceToUsdc( currentSlice.juniorTranche.principalSharePrice, currentSlice.juniorTranche.principalDeposited ); amountAvailable = amountAvailable.add( sharePriceToUsdc(currentSlice.seniorTranche.principalSharePrice, currentSlice.seniorTranche.principalDeposited) ); require(amount <= amountAvailable, "Insufficient funds in slice"); creditLine.drawdown(amount); // Update the share price to reflect the amount remaining in the pool uint256 amountRemaining = amountAvailable.sub(amount); uint256 oldJuniorPrincipalSharePrice = currentSlice.juniorTranche.principalSharePrice; uint256 oldSeniorPrincipalSharePrice = currentSlice.seniorTranche.principalSharePrice; currentSlice.juniorTranche.principalSharePrice = currentSlice.juniorTranche.calculateExpectedSharePrice( amountRemaining, currentSlice ); currentSlice.seniorTranche.principalSharePrice = currentSlice.seniorTranche.calculateExpectedSharePrice( amountRemaining, currentSlice ); currentSlice.principalDeployed = currentSlice.principalDeployed.add(amount); totalDeployed = totalDeployed.add(amount); address borrower = creditLine.borrower(); safeERC20TransferFrom(config.getUSDC(), address(this), borrower, amount); emit DrawdownMade(borrower, amount); emit SharePriceUpdated( address(this), currentSlice.juniorTranche.id, currentSlice.juniorTranche.principalSharePrice, int256(oldJuniorPrincipalSharePrice.sub(currentSlice.juniorTranche.principalSharePrice)) * -1, currentSlice.juniorTranche.interestSharePrice, 0 ); emit SharePriceUpdated( address(this), currentSlice.seniorTranche.id, currentSlice.seniorTranche.principalSharePrice, int256(oldSeniorPrincipalSharePrice.sub(currentSlice.seniorTranche.principalSharePrice)) * -1, currentSlice.seniorTranche.interestSharePrice, 0 ); }
72,904
109
// Checks if rounding error >= 0.1% when rounding down./numerator Numerator./denominator Denominator./target Value to multiply with numerator/denominator./ return Rounding error is present.
function isRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { require(
function isRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { require(
24,073
66
// Emit events before deleting listing to check whether is whitelisted
if (listing.whitelisted) { emit _ListingRemoved(_listingHash); } else {
if (listing.whitelisted) { emit _ListingRemoved(_listingHash); } else {
53,898
3
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory);}
interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory);}
16,510
77
// Helps contracts guard against reentrancy attacks. Remco Bloemen <[email protected]π.com>, Eenae <[email protected]> If you mark a function `nonReentrant`, you should alsomark it `external`. /
contract ReentrancyGuard { /// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs. /// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056 uint256 internal constant REENTRANCY_GUARD_FREE = 1; /// @dev Constant for locked guard state uint256 internal constant REENTRANCY_GUARD_LOCKED = 2; /** * @dev We use a single lock for the whole contract. */ uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant"); reentrancyLock = REENTRANCY_GUARD_LOCKED; _; reentrancyLock = REENTRANCY_GUARD_FREE; } }
contract ReentrancyGuard { /// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs. /// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056 uint256 internal constant REENTRANCY_GUARD_FREE = 1; /// @dev Constant for locked guard state uint256 internal constant REENTRANCY_GUARD_LOCKED = 2; /** * @dev We use a single lock for the whole contract. */ uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant"); reentrancyLock = REENTRANCY_GUARD_LOCKED; _; reentrancyLock = REENTRANCY_GUARD_FREE; } }
24,611
224
// Unsubscribes an owner from their inventory and updates the vacant inventories list. /
function _unsubscribeInventory(address owner) private { uint256 id = _getInventoryId(owner); delete _ownerToInventory[owner]; delete _inventoryToOwner[id]; _vacantInventories.push(uint16(id)); }
function _unsubscribeInventory(address owner) private { uint256 id = _getInventoryId(owner); delete _ownerToInventory[owner]; delete _inventoryToOwner[id]; _vacantInventories.push(uint16(id)); }
42,685
8
// Multiply x by 86400 and then divide it by 1e18.
r := div(mul(x, 86400), 1000000000000000000)
r := div(mul(x, 86400), 1000000000000000000)
1,835
158
// Claim each token
for (uint256 i = 0; i < tokens.length; i++) { uint256 claimable = cumulativeAmounts[i].sub(claimed[msg.sender][tokens[i]]); require(claimable > 0, "Excessive claim"); claimed[msg.sender][tokens[i]] = claimed[msg.sender][tokens[i]].add(claimable); require(claimed[msg.sender][tokens[i]] == cumulativeAmounts[i], "Claimed amount mismatch"); require(IERC20Upgradeable(tokens[i]).transfer(msg.sender, claimable), "Transfer failed");
for (uint256 i = 0; i < tokens.length; i++) { uint256 claimable = cumulativeAmounts[i].sub(claimed[msg.sender][tokens[i]]); require(claimable > 0, "Excessive claim"); claimed[msg.sender][tokens[i]] = claimed[msg.sender][tokens[i]].add(claimable); require(claimed[msg.sender][tokens[i]] == cumulativeAmounts[i], "Claimed amount mismatch"); require(IERC20Upgradeable(tokens[i]).transfer(msg.sender, claimable), "Transfer failed");
45,032
79
// Deallocates "amount" of available ICE to "usageAddress" contract args specific to usage contract must be passed into "usageData" /
function _deallocate(address userAddress, address usageAddress, uint256 amount) internal { require(amount > 0, "deallocate: amount cannot be null"); // check if there is enough allocated ICE to this usage to deallocate uint256 allocatedAmount = usageAllocations[userAddress][usageAddress]; require(allocatedAmount >= amount, "deallocate: non authorized amount"); // remove deallocated amount from usage's allocation usageAllocations[userAddress][usageAddress] = allocatedAmount.sub(amount); uint256 deallocationFeeAmount = amount.mul(usagesDeallocationFee[usageAddress]).div(10000); // adjust user's ICE balances IceBalance storage balance = iceBalances[userAddress]; balance.allocatedAmount = balance.allocatedAmount.sub(amount); _transfer(address(this), userAddress, amount.sub(deallocationFeeAmount)); // burn corresponding SLUSH and ICE slushToken.burn(deallocationFeeAmount); _burn(address(this), deallocationFeeAmount); emit Deallocate(userAddress, usageAddress, amount, deallocationFeeAmount); }
function _deallocate(address userAddress, address usageAddress, uint256 amount) internal { require(amount > 0, "deallocate: amount cannot be null"); // check if there is enough allocated ICE to this usage to deallocate uint256 allocatedAmount = usageAllocations[userAddress][usageAddress]; require(allocatedAmount >= amount, "deallocate: non authorized amount"); // remove deallocated amount from usage's allocation usageAllocations[userAddress][usageAddress] = allocatedAmount.sub(amount); uint256 deallocationFeeAmount = amount.mul(usagesDeallocationFee[usageAddress]).div(10000); // adjust user's ICE balances IceBalance storage balance = iceBalances[userAddress]; balance.allocatedAmount = balance.allocatedAmount.sub(amount); _transfer(address(this), userAddress, amount.sub(deallocationFeeAmount)); // burn corresponding SLUSH and ICE slushToken.burn(deallocationFeeAmount); _burn(address(this), deallocationFeeAmount); emit Deallocate(userAddress, usageAddress, amount, deallocationFeeAmount); }
33,618
68
// Send _value amount of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
23,678
100
// paid dividends cannot be greater then 150% from investor investment
if (investor.dividends.value >= investor.dividends.limit) { return 0; }
if (investor.dividends.value >= investor.dividends.limit) { return 0; }
13,295
415
// Users receive penalties if their collateralisation ratio drifts out of our desired brackets We precompute the brackets and penalties to save gas.
uint constant TWENTY_PERCENT = (20 * SafeDecimalMath.unit()) / 100; uint constant TWENTY_FIVE_PERCENT = (25 * SafeDecimalMath.unit()) / 100; uint constant THIRTY_PERCENT = (30 * SafeDecimalMath.unit()) / 100; uint constant FOURTY_PERCENT = (40 * SafeDecimalMath.unit()) / 100; uint constant FIFTY_PERCENT = (50 * SafeDecimalMath.unit()) / 100; uint constant SEVENTY_FIVE_PERCENT = (75 * SafeDecimalMath.unit()) / 100; constructor(address _proxy, address _owner, Synthetix _synthetix, address _feeAuthority, uint _transferFeeRate, uint _exchangeFeeRate) SelfDestructible(_owner) Proxyable(_proxy, _owner)
uint constant TWENTY_PERCENT = (20 * SafeDecimalMath.unit()) / 100; uint constant TWENTY_FIVE_PERCENT = (25 * SafeDecimalMath.unit()) / 100; uint constant THIRTY_PERCENT = (30 * SafeDecimalMath.unit()) / 100; uint constant FOURTY_PERCENT = (40 * SafeDecimalMath.unit()) / 100; uint constant FIFTY_PERCENT = (50 * SafeDecimalMath.unit()) / 100; uint constant SEVENTY_FIVE_PERCENT = (75 * SafeDecimalMath.unit()) / 100; constructor(address _proxy, address _owner, Synthetix _synthetix, address _feeAuthority, uint _transferFeeRate, uint _exchangeFeeRate) SelfDestructible(_owner) Proxyable(_proxy, _owner)
6,254
35
// This function calculates the tokens owed given an amount ofcontribution, accounting for oversubscription.This is in contrast to the _ethInCommodityOut() function,which simply calculates the amount of commodity thatan amount of eth would buy given an eth price.If a tier is not oversubscribed, he will simply get the _commodityOut amountthat _ethInCommodityOut outputs.If a tier is oversubscribed, then everyone gets _pro_rata_amount(), which splitsthe amountOnSale of a tier pro-rata in terms of eth contribution /
function _amountToGet( address guy, Tier tier
function _amountToGet( address guy, Tier tier
9,857
52
// Override _isApprovedOrOwner to whitelistcontracts to enable gas-less listings. /
function _isApprovedOrOwner(address spender, uint256 tokenId) override internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); if (isApprovedForAll(owner, spender)) return true; return super._isApprovedOrOwner(spender, tokenId); }
function _isApprovedOrOwner(address spender, uint256 tokenId) override internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); if (isApprovedForAll(owner, spender)) return true; return super._isApprovedOrOwner(spender, tokenId); }
28,639
1
// A dummy constructor /
constructor (uint256 totalSupply) public { require(msg.sender != address(0));
constructor (uint256 totalSupply) public { require(msg.sender != address(0));
1,274
0
// each atomic option is worth 109 = 1000000000 wei in case of win
uint256 constant private ATOMIC_OPTION_PAYOUT_WEI_EXP = 9; int256 constant private ATOMIC_OPTION_PAYOUT_WEI = int256(uint256(10)**ATOMIC_OPTION_PAYOUT_WEI_EXP); uint8 constant private RANGESTATE_NOT_USED = 0; uint8 constant private RANGESTATE_TRADED = 1; uint8 constant private RANGESTATE_PAYED_OUT = 2; int256 constant private INT256_MAX = int256(~(uint256(1) << 255));
uint256 constant private ATOMIC_OPTION_PAYOUT_WEI_EXP = 9; int256 constant private ATOMIC_OPTION_PAYOUT_WEI = int256(uint256(10)**ATOMIC_OPTION_PAYOUT_WEI_EXP); uint8 constant private RANGESTATE_NOT_USED = 0; uint8 constant private RANGESTATE_TRADED = 1; uint8 constant private RANGESTATE_PAYED_OUT = 2; int256 constant private INT256_MAX = int256(~(uint256(1) << 255));
48,355
6
// BlacklistAddRemove allow owner to Blacklist artist.contract owner can call .Requirement: _artist- artist address
* Emits a {Blacklisted} event. * Emits a {BlacklistedRemoved} event. */ function blacklistAddRemove(address _artist) public onlyOwner { if (isBlacklisted[_artist] == false) { isBlacklisted[_artist] = true; emit Blacklisted(msg.sender, _artist); } else { isBlacklisted[_artist] = false; emit BlacklistedRemoved(msg.sender, _artist); } }
* Emits a {Blacklisted} event. * Emits a {BlacklistedRemoved} event. */ function blacklistAddRemove(address _artist) public onlyOwner { if (isBlacklisted[_artist] == false) { isBlacklisted[_artist] = true; emit Blacklisted(msg.sender, _artist); } else { isBlacklisted[_artist] = false; emit BlacklistedRemoved(msg.sender, _artist); } }
20,319
36
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
assembly { word:= mload(mload(add(self, 32))) }
5,443
98
// RequestBankrollPayment(target, profit, tier);
}
}
58,145
155
// all the 1s at or to the right of the current bitPos
uint256 mask = (1 << bitPos) - 1 + (1 << bitPos); uint256 masked = self[wordPos] & mask;
uint256 mask = (1 << bitPos) - 1 + (1 << bitPos); uint256 masked = self[wordPos] & mask;
46,887
46
// check that the reserve has enough available liquiditywe avoid using the getAvailableLiquidity() function in LendingPoolCore to save gas
uint256 availableLiquidityBefore = _reserve == EthAddressLib.ethAddress() ? address(core).balance : IERC20(_reserve).balanceOf(address(core)); require( availableLiquidityBefore >= _amount, "There is not enough liquidity available to borrow" ); (uint256 totalFeeBips, uint256 protocolFeeBips) = parametersProvider
uint256 availableLiquidityBefore = _reserve == EthAddressLib.ethAddress() ? address(core).balance : IERC20(_reserve).balanceOf(address(core)); require( availableLiquidityBefore >= _amount, "There is not enough liquidity available to borrow" ); (uint256 totalFeeBips, uint256 protocolFeeBips) = parametersProvider
2,466
28
// External function to set the token price. This function can be called only by owner. _price New token price /
function setPrice(uint256 _price) external onlyOwner { price = _price; emit PriceSet(price); }
function setPrice(uint256 _price) external onlyOwner { price = _price; emit PriceSet(price); }
74,124
3
//
function initialize(address _authority, address _treasury, address _mainToken, address _staking) initializer public { __AccessControl_init(IAuthority(address(_authority))); treasury = ITreasury(_treasury); mainToken = IERC20Upgradeable(_mainToken); staking = _staking; }
function initialize(address _authority, address _treasury, address _mainToken, address _staking) initializer public { __AccessControl_init(IAuthority(address(_authority))); treasury = ITreasury(_treasury); mainToken = IERC20Upgradeable(_mainToken); staking = _staking; }
29,977
81
// Rewards Send
sendToken( userAddress, stakingDetails[userAddress].tokenAddress[stakeId], rewardToken, rewardsEarned );
sendToken( userAddress, stakingDetails[userAddress].tokenAddress[stakeId], rewardToken, rewardsEarned );
73,305
61
// team tokens are locked for 90 days
TokenTimelock teamTokensLock = new TokenTimelock(this, mobilinkTeamAddress, uint64(block.timestamp) + 60 * 60 * 24 * 90); teamTokensLockAddress = address(teamTokensLock); totalSupply = totalSupply.add(teamTokens); balances[teamTokensLockAddress] = teamTokens;
TokenTimelock teamTokensLock = new TokenTimelock(this, mobilinkTeamAddress, uint64(block.timestamp) + 60 * 60 * 24 * 90); teamTokensLockAddress = address(teamTokensLock); totalSupply = totalSupply.add(teamTokens); balances[teamTokensLockAddress] = teamTokens;
20,405
1
// next 32 bytes
s := mload(add(sig, 0x40))
s := mload(add(sig, 0x40))
40,636
48
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime); _;
require(block.timestamp >= openingTime && block.timestamp <= closingTime); _;
14,814
94
// Truncate bytes array if its size is more than 20 bytes.NOTE: This function does not perform any checks on the received parameter.Make sure that the _bytes argument has a correct length, not less than 20 bytes.A case when _bytes has length less than 20 will lead to the undefined behaviour,since assembly will read data from memory that is not related to the _bytes argument. _bytes to be converted to address typereturn addr address included in the firsts 20 bytes of the bytes array in parameter. /
function bytesToAddress(bytes memory _bytes) internal pure returns (address addr) { assembly { addr := mload(add(_bytes, 20)) } }
function bytesToAddress(bytes memory _bytes) internal pure returns (address addr) { assembly { addr := mload(add(_bytes, 20)) } }
24,047
742
// Burn several invalid tokens. Callable by anyone. Used to burn unecessary tokens for clarityand to free up storage. Throws if the position is not yet closed. positionIdsUnique IDs of the positions /
function burnClosedTokenMultiple( bytes32[] positionIds ) external nonReentrant
function burnClosedTokenMultiple( bytes32[] positionIds ) external nonReentrant
46,890
61
// One way breaker for closing payments from this contract
bool public breaker;
bool public breaker;
13,413
57
// Makes a checkpoint to start counting a new period/Should be used only by Profiterole contract
function addDistributionPeriod() public onlyProfiterole returns (uint) { uint _periodsCount = periodsCount; uint _nextPeriod = _periodsCount.add(1); periodDate2periodIdx[now] = _periodsCount; Period storage _previousPeriod = periods[_periodsCount]; uint _totalBmcDeposit = _getTotalBmcDaysAmount(now, _periodsCount); periods[_nextPeriod].startDate = now; periods[_nextPeriod].bmcDaysPerDay = _previousPeriod.bmcDaysPerDay; periods[_nextPeriod].totalBmcDays = _totalBmcDeposit; periodsCount = _nextPeriod; return OK; }
function addDistributionPeriod() public onlyProfiterole returns (uint) { uint _periodsCount = periodsCount; uint _nextPeriod = _periodsCount.add(1); periodDate2periodIdx[now] = _periodsCount; Period storage _previousPeriod = periods[_periodsCount]; uint _totalBmcDeposit = _getTotalBmcDaysAmount(now, _periodsCount); periods[_nextPeriod].startDate = now; periods[_nextPeriod].bmcDaysPerDay = _previousPeriod.bmcDaysPerDay; periods[_nextPeriod].totalBmcDays = _totalBmcDeposit; periodsCount = _nextPeriod; return OK; }
14,879
64
// sets recipient of transfer fee only callable by owner _newBeneficiary new beneficiary /
function setBeneficiary(address _newBeneficiary) public onlyOwner { setExcludeFromFee(_newBeneficiary, true); emit BeneficiaryUpdated(beneficiary, _newBeneficiary); beneficiary = _newBeneficiary; }
function setBeneficiary(address _newBeneficiary) public onlyOwner { setExcludeFromFee(_newBeneficiary, true); emit BeneficiaryUpdated(beneficiary, _newBeneficiary); beneficiary = _newBeneficiary; }
3,968
172
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
21,131
8
// Claim RGT/set timestamp for initial transfer of RSPT to `recipient`
rariGovernanceTokenDistributor.distributeRgt(sender, IRariGovernanceTokenDistributor.RariPool.Stable); if (balanceOf(recipient) > 0) rariGovernanceTokenDistributor.distributeRgt(recipient, IRariGovernanceTokenDistributor.RariPool.Stable); else rariGovernanceTokenDistributor.beforeFirstPoolTokenTransferIn(recipient, IRariGovernanceTokenDistributor.RariPool.Stable);
rariGovernanceTokenDistributor.distributeRgt(sender, IRariGovernanceTokenDistributor.RariPool.Stable); if (balanceOf(recipient) > 0) rariGovernanceTokenDistributor.distributeRgt(recipient, IRariGovernanceTokenDistributor.RariPool.Stable); else rariGovernanceTokenDistributor.beforeFirstPoolTokenTransferIn(recipient, IRariGovernanceTokenDistributor.RariPool.Stable);
12,029
281
// Tell the information related to a signer_signer Address of signer return lastSettingIdSigned Identification number of the last agreement setting signed by the signer return mustSign Whether the requested signer needs to sign the current agreement setting before submitting an action/
function getSigner(address _signer) external view returns (uint256 lastSettingIdSigned, bool mustSign) { (lastSettingIdSigned, mustSign) = _getSigner(_signer); }
function getSigner(address _signer) external view returns (uint256 lastSettingIdSigned, bool mustSign) { (lastSettingIdSigned, mustSign) = _getSigner(_signer); }
38,823
489
// make sure msg.sender is the guardian or the governance
modifier onlyGovernanceOrGatekeeper(address _governance) { _onlyGovernanceOrGatekeeper(_governance); _; }
modifier onlyGovernanceOrGatekeeper(address _governance) { _onlyGovernanceOrGatekeeper(_governance); _; }
69,657
36
// The map that keeps track of all proposasls submitted to the DAO
mapping(bytes32 => Proposal) public proposals;
mapping(bytes32 => Proposal) public proposals;
63,414
12
// Role allowed to initiate new validators by sending funds from the allocatedETHForDeposits balance/ to the beacon chain deposit contract.
bytes32 public constant INITIATOR_SERVICE_ROLE = keccak256("INITIATOR_SERVICE_ROLE");
bytes32 public constant INITIATOR_SERVICE_ROLE = keccak256("INITIATOR_SERVICE_ROLE");
32,712
2
// Contract is a wrapper for Types libraryfor use with testing only/
contract MockTypes { function hashOrder(Types.Order memory _order, bytes32 _domainSeparator) public pure returns (bytes32) { return Types.hashOrder(_order, _domainSeparator); } function hashDomain( bytes memory _name, bytes memory _version, address _verifyingContract ) public pure returns (bytes32) { return Types.hashDomain(_name, _version, _verifyingContract); } }
contract MockTypes { function hashOrder(Types.Order memory _order, bytes32 _domainSeparator) public pure returns (bytes32) { return Types.hashOrder(_order, _domainSeparator); } function hashDomain( bytes memory _name, bytes memory _version, address _verifyingContract ) public pure returns (bytes32) { return Types.hashDomain(_name, _version, _verifyingContract); } }
50,235