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
7
// Set the airdrop contract address./
function setAirdropAddress(address _airdrop) public onlyOwner{ airdrop = _airdrop; }
function setAirdropAddress(address _airdrop) public onlyOwner{ airdrop = _airdrop; }
50,343
150
// ------------Total Balances------------ Total USD value
uint256 total_value_E18 = free_collateral_E18 + lp_total_val; return [ lp_free, // [0] Free LP lp_value_in_vault, // [1] Staked LP in the vault lp_total_val, // [2] Free + Staked LP free_collateral, // [3] Free Collateral free_collateral_E18, // [4] Free Collateral, in E18 total_value_E18 // [5] Total USD value ];
uint256 total_value_E18 = free_collateral_E18 + lp_total_val; return [ lp_free, // [0] Free LP lp_value_in_vault, // [1] Staked LP in the vault lp_total_val, // [2] Free + Staked LP free_collateral, // [3] Free Collateral free_collateral_E18, // [4] Free Collateral, in E18 total_value_E18 // [5] Total USD value ];
10,903
261
// copy all batches from the old contracts leave ids intact
function copyNextBatch() public { require(migrating, "must be migrating"); uint256 start = nextBatch; (uint48 userID, uint16 size) = old.batches(start); require(size > 0 && userID > 0, "incorrect batch or limit reached"); if (old.cardProtos(start) != 0) { address to = old.userIDToAddress(userID); uint48 uID = _getUserID(to); batches[start] = Batch({ userID: uID, size: size }); uint256 end = start.add(size); for (uint256 i = start; i < end; i++) { emit Transfer(address(0), to, i); } _balances[to] = _balances[to].add(size); tokenCount = tokenCount.add(size); } nextBatch = nextBatch.add(batchSize); }
function copyNextBatch() public { require(migrating, "must be migrating"); uint256 start = nextBatch; (uint48 userID, uint16 size) = old.batches(start); require(size > 0 && userID > 0, "incorrect batch or limit reached"); if (old.cardProtos(start) != 0) { address to = old.userIDToAddress(userID); uint48 uID = _getUserID(to); batches[start] = Batch({ userID: uID, size: size }); uint256 end = start.add(size); for (uint256 i = start; i < end; i++) { emit Transfer(address(0), to, i); } _balances[to] = _balances[to].add(size); tokenCount = tokenCount.add(size); } nextBatch = nextBatch.add(batchSize); }
10,089
80
// Rounds a division result.
function roundedDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, 'div by 0'); uint256 halfB = (b.mod(2) == 0) ? (b.div(2)) : (b.div(2).add(1)); return (a.mod(b) >= halfB) ? (a.div(b).add(1)) : (a.div(b)); }
function roundedDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, 'div by 0'); uint256 halfB = (b.mod(2) == 0) ? (b.div(2)) : (b.div(2).add(1)); return (a.mod(b) >= halfB) ? (a.div(b).add(1)) : (a.div(b)); }
2,707
22
// @notify View function that returns whether the delay between calls has been passed/
function passedDelay() public view returns (bool ok) { return currentTime() >= uint(addition(lastUpdateTime, uint64(updateDelay))); }
function passedDelay() public view returns (bool ok) { return currentTime() >= uint(addition(lastUpdateTime, uint64(updateDelay))); }
53,897
29
// 3. mint bridgeable nft of same type
bridgeableNfts[nftType-1].mint(msg.sender, tokenId); emit NftToBridgeableNft(nftType, tokenId);
bridgeableNfts[nftType-1].mint(msg.sender, tokenId); emit NftToBridgeableNft(nftType, tokenId);
52,880
97
// To be disbursed continuously over this duration
uint public constant disburseDuration = 60 minutes;
uint public constant disburseDuration = 60 minutes;
5,541
0
// Initialize Ownable contract
constructor() public { Ownable(msg.sender); }
constructor() public { Ownable(msg.sender); }
8,182
15
// Emitted when the platform is updated newPlatform New platform /
event PlatformUpdated(address newPlatform);
event PlatformUpdated(address newPlatform);
14,215
686
// set relevant constants
state = State.OPEN; heldToken = position.heldToken; uint256 tokenAmount = getTokenAmountOnAdd(position.principal); emit Initialized(POSITION_ID, tokenAmount); mint(INITIAL_TOKEN_HOLDER, tokenAmount); return address(this); // returning own address retains ownership of position
state = State.OPEN; heldToken = position.heldToken; uint256 tokenAmount = getTokenAmountOnAdd(position.principal); emit Initialized(POSITION_ID, tokenAmount); mint(INITIAL_TOKEN_HOLDER, tokenAmount); return address(this); // returning own address retains ownership of position
46,147
45
// emit event - could remove to save ~3k gas
emit FlashLiquidate( LiquidationFunction.V3_FLASHSWAP, data.vault, data.asset );
emit FlashLiquidate( LiquidationFunction.V3_FLASHSWAP, data.vault, data.asset );
7,901
14
// created 2.5% extra to the contract owner to approach 2% total marketcap
toSender = tokens;
toSender = tokens;
12,971
106
// call _mint from constructor ERC20 Not giving loser lottery tokens !! lotteryToken.mint(msg.sender, lotteryConfig.registrationAmount);
if (lotteryPlayers.length == lotteryConfig.playersLimit) { emit MaxParticipationCompleted(msg.sender); getRandomNumber(lotteryConfig.randomSeed); }
if (lotteryPlayers.length == lotteryConfig.playersLimit) { emit MaxParticipationCompleted(msg.sender); getRandomNumber(lotteryConfig.randomSeed); }
2,200
153
// generate the snowSwap pair path of token -> weth
address[] memory path = new address[](2); path[0] = address(this); path[1] = snowSwapRouter.WAVAX(); _approve(address(this), address(snowSwapRouter), tokenAmount);
address[] memory path = new address[](2); path[0] = address(this); path[1] = snowSwapRouter.WAVAX(); _approve(address(this), address(snowSwapRouter), tokenAmount);
3,114
9
// Moves `amount` tokens from `sender` to `recipient` using theallowance mechanism. `amount` is then deducted from the caller'sallowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. /
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
320
18
// the valuation cap that each address has submitted
mapping (address => uint256) personalCaps;
mapping (address => uint256) personalCaps;
65,218
50
// internal function check account already contribute token and eth to contract
* {param} * amountToken , amountEth */ function checkSendedAccount(uint256 amountToken,uint256 amountEth)internal { bool flag = false; for(uint256 i=0;i<counterDeposit;i++){ if(contributor[i].addr == msg.sender){ contributor[i].balanceOfEth += amountEth; contributor[i].balanceOfToken += amountToken; flag = true; break; } } if(!flag){ contributor[counterDeposit].addr = msg.sender; contributor[counterDeposit].balanceOfEth = msg.value; contributor[counterDeposit].balanceOfToken = amountToken; counterDeposit++; } }
* {param} * amountToken , amountEth */ function checkSendedAccount(uint256 amountToken,uint256 amountEth)internal { bool flag = false; for(uint256 i=0;i<counterDeposit;i++){ if(contributor[i].addr == msg.sender){ contributor[i].balanceOfEth += amountEth; contributor[i].balanceOfToken += amountToken; flag = true; break; } } if(!flag){ contributor[counterDeposit].addr = msg.sender; contributor[counterDeposit].balanceOfEth = msg.value; contributor[counterDeposit].balanceOfToken = amountToken; counterDeposit++; } }
13,080
50
// Join a strategy with an amount of tokens strategy Address of the strategy to join tokensIn List of token addresses to join with amountsIn List of token amounts to join with slippage Slippage that will be used to compute the join data Extra data that may enable or not different behaviors depending on the implementationreturn tokensOut List of token addresses received after the joinreturn amountsOut List of token amounts received after the join /
function join(
function join(
32,205
207
// stores the stored reserve balance for a given reserve id_reserveId reserve id _reserveBalancereserve balance /
function setReserveBalance(uint256 _reserveId, uint256 _reserveBalance) internal { require(_reserveBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW"); uint256 otherBalance = decodeReserveBalance(__reserveBalances, 3 - _reserveId); __reserveBalances = encodeReserveBalances(_reserveBalance, _reserveId, otherBalance, 3 - _reserveId); }
function setReserveBalance(uint256 _reserveId, uint256 _reserveBalance) internal { require(_reserveBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW"); uint256 otherBalance = decodeReserveBalance(__reserveBalances, 3 - _reserveId); __reserveBalances = encodeReserveBalances(_reserveBalance, _reserveId, otherBalance, 3 - _reserveId); }
26,908
16
// Monday 25th June, 2018
worldCupGameID["UR-RU"] = 33; // Uruguay vs Russia worldCupGameID["SA-EG"] = 34; // Saudi Arabia vs Egypt worldCupGameID["ES-MA"] = 35; // Spain vs Morocco worldCupGameID["IR-PT"] = 36; // Iran vs Portugal gameLocked[33] = 1529935200; gameLocked[34] = 1529935200; gameLocked[35] = 1529949600; gameLocked[36] = 1529949600;
worldCupGameID["UR-RU"] = 33; // Uruguay vs Russia worldCupGameID["SA-EG"] = 34; // Saudi Arabia vs Egypt worldCupGameID["ES-MA"] = 35; // Spain vs Morocco worldCupGameID["IR-PT"] = 36; // Iran vs Portugal gameLocked[33] = 1529935200; gameLocked[34] = 1529935200; gameLocked[35] = 1529949600; gameLocked[36] = 1529949600;
38,393
2
// what time this SpeedBump was created at
bytes constant private speedBumpTimeCreated1 = '1.speedBump.timeCreated';
bytes constant private speedBumpTimeCreated1 = '1.speedBump.timeCreated';
17,427
29
// deposit /
function deposit(uint256 _value) public override returns (bool) { return depositTo(msg.sender, _value); }
function deposit(uint256 _value) public override returns (bool) { return depositTo(msg.sender, _value); }
50,730
125
// BlockIdentity ERC721 TokenThis implementation includes all the required and some optional functionality of the ERC721 standardMoreover, it includes approve all functionality using operator terminology /
contract ERC721Last is ERC721, ERC721Enumerable, ERC721Metadata { address private _ownerContract; uint256 public _nonce; modifier onlyMinter() { require(_ownerContract == msg.sender,"Identity: the token can mint only owner"); _; } constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { _ownerContract = msg.sender; } /** * @dev Function to set TokenUri only owner contract. * @param to The address that will receive the minted tokens. * @return A TokenId that indicates if the operation was successful. */ function mintToken(address to) public onlyMinter returns (uint256) { uint256 tokenId; tokenId = ++_nonce; _mint(to, tokenId); return tokenId; } /** * @dev Function to mint tokens only owner contract. * @param tokenId The token id to mint. * @param tokenURI The token URI of the minted token. * @return A boolean that indicates if the operation was successful. */ function setTokenURI(uint256 tokenId, string memory tokenURI) public onlyMinter returns (bool) { require(_ownerContract == msg.sender,"Identity: the token can mint only owner"); _setTokenURI(tokenId, tokenURI); return true; } /** * @dev Test tokenId and TokenHash * @param tokenId The token id to mint. * @param tokenHash The token URI of the minted token. * @return A boolean that indicates if the operation was successful. */ function checkKey(uint256 tokenId, bytes4 tokenHash) external view returns (bool) { require(_exists(tokenId), "ERC721Last: URI query for nonexistent token"); string memory str_hash = this.tokenURI(tokenId); if(tokenHash==bytes4(keccak256(abi.encodePacked(str_hash)))) {return true;} else {return false;} } /** * @dev Return last id token * @return Last token id */ function LastTokenId() external view returns (uint256) { require(_ownerContract == msg.sender,"Identity: the token can mint only owner"); return _nonce; } /** * @dev Function to get a hash of tokenId * @param tokenId The token id to mint. * @return A boolean that indicates if the operation was successful. */ function getTokenKey(uint256 tokenId) external view returns (bytes4) { require(_ownerContract == msg.sender,"Identity: the token can mint only owner"); require(_exists(tokenId), "ERC721Last: URI query for nonexistent token"); string memory str_hash = this.tokenURI(tokenId); return bytes4(keccak256(abi.encodePacked(str_hash))); } /** * @dev Function to mint tokens. * @param to The address that will receive the minted tokens * @param tokenURI The token URI of the minted token. * @return A TokenId that indicates if the operation was successful. */ function mintWithTokenURI(address to, string memory tokenURI) public onlyMinter returns (uint256) { require(_ownerContract == msg.sender,"Identity: the token can mint only owner"); uint256 tokenId; tokenId = ++_nonce; _mint(to, tokenId); _setTokenURI(tokenId, tokenURI); return tokenId; } }
contract ERC721Last is ERC721, ERC721Enumerable, ERC721Metadata { address private _ownerContract; uint256 public _nonce; modifier onlyMinter() { require(_ownerContract == msg.sender,"Identity: the token can mint only owner"); _; } constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { _ownerContract = msg.sender; } /** * @dev Function to set TokenUri only owner contract. * @param to The address that will receive the minted tokens. * @return A TokenId that indicates if the operation was successful. */ function mintToken(address to) public onlyMinter returns (uint256) { uint256 tokenId; tokenId = ++_nonce; _mint(to, tokenId); return tokenId; } /** * @dev Function to mint tokens only owner contract. * @param tokenId The token id to mint. * @param tokenURI The token URI of the minted token. * @return A boolean that indicates if the operation was successful. */ function setTokenURI(uint256 tokenId, string memory tokenURI) public onlyMinter returns (bool) { require(_ownerContract == msg.sender,"Identity: the token can mint only owner"); _setTokenURI(tokenId, tokenURI); return true; } /** * @dev Test tokenId and TokenHash * @param tokenId The token id to mint. * @param tokenHash The token URI of the minted token. * @return A boolean that indicates if the operation was successful. */ function checkKey(uint256 tokenId, bytes4 tokenHash) external view returns (bool) { require(_exists(tokenId), "ERC721Last: URI query for nonexistent token"); string memory str_hash = this.tokenURI(tokenId); if(tokenHash==bytes4(keccak256(abi.encodePacked(str_hash)))) {return true;} else {return false;} } /** * @dev Return last id token * @return Last token id */ function LastTokenId() external view returns (uint256) { require(_ownerContract == msg.sender,"Identity: the token can mint only owner"); return _nonce; } /** * @dev Function to get a hash of tokenId * @param tokenId The token id to mint. * @return A boolean that indicates if the operation was successful. */ function getTokenKey(uint256 tokenId) external view returns (bytes4) { require(_ownerContract == msg.sender,"Identity: the token can mint only owner"); require(_exists(tokenId), "ERC721Last: URI query for nonexistent token"); string memory str_hash = this.tokenURI(tokenId); return bytes4(keccak256(abi.encodePacked(str_hash))); } /** * @dev Function to mint tokens. * @param to The address that will receive the minted tokens * @param tokenURI The token URI of the minted token. * @return A TokenId that indicates if the operation was successful. */ function mintWithTokenURI(address to, string memory tokenURI) public onlyMinter returns (uint256) { require(_ownerContract == msg.sender,"Identity: the token can mint only owner"); uint256 tokenId; tokenId = ++_nonce; _mint(to, tokenId); _setTokenURI(tokenId, tokenURI); return tokenId; } }
8,894
15
// Interface for trading discounts and rebates for specific accounts /
contract FeeModifiersInterface { function accountFeeModifiers(address _user) public view returns (uint256 feeDiscount, uint256 feeRebate); function tradingFeeModifiers(address _maker, address _taker) public view returns (uint256 feeMakeDiscount, uint256 feeTakeDiscount, uint256 feeRebate); }
contract FeeModifiersInterface { function accountFeeModifiers(address _user) public view returns (uint256 feeDiscount, uint256 feeRebate); function tradingFeeModifiers(address _maker, address _taker) public view returns (uint256 feeMakeDiscount, uint256 feeTakeDiscount, uint256 feeRebate); }
70,593
14
// ---------------------------------------------------------------------------- Owned contract ----------------------------------------------------------------------------
contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } }
contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } }
50,594
9
// Checks whether the current cache does not, throwing an error if it does. cache The current cache /
function requireNotExists(Cache storage cache) internal view { require(!exists(cache), "CACHE_ALREADY_EXISTS"); }
function requireNotExists(Cache storage cache) internal view { require(!exists(cache), "CACHE_ALREADY_EXISTS"); }
44,518
75
// Lets buy you some tokens.
function buyTokens(address _buyer) public payable { // Available only if presale or crowdsale is running. require((currentPhase == Phase.PresaleRunning) || (currentPhase == Phase.ICORunning)); require(_buyer != address(0)); require(msg.value > 0); require(validPurchase()); uint tokensWouldAddTo = 0; uint weiWouldAddTo = 0; uint256 weiAmount = msg.value; uint newTokens = msg.value.mul(RATE); weiWouldAddTo = weiRaised.add(weiAmount); require(weiWouldAddTo <= TOKEN_SALE_LIMIT); newTokens = addBonusTokens(token.totalSupply(), newTokens); tokensWouldAddTo = newTokens.add(token.totalSupply()); require(tokensWouldAddTo <= TOKENS_FOR_SALE); token.mint(_buyer, newTokens); TokenPurchase(msg.sender, _buyer, weiAmount, newTokens); weiRaised = weiWouldAddTo; forwardFunds(); if (weiRaised == TOKENS_FOR_SALE){ weiCapReached = true; } }
function buyTokens(address _buyer) public payable { // Available only if presale or crowdsale is running. require((currentPhase == Phase.PresaleRunning) || (currentPhase == Phase.ICORunning)); require(_buyer != address(0)); require(msg.value > 0); require(validPurchase()); uint tokensWouldAddTo = 0; uint weiWouldAddTo = 0; uint256 weiAmount = msg.value; uint newTokens = msg.value.mul(RATE); weiWouldAddTo = weiRaised.add(weiAmount); require(weiWouldAddTo <= TOKEN_SALE_LIMIT); newTokens = addBonusTokens(token.totalSupply(), newTokens); tokensWouldAddTo = newTokens.add(token.totalSupply()); require(tokensWouldAddTo <= TOKENS_FOR_SALE); token.mint(_buyer, newTokens); TokenPurchase(msg.sender, _buyer, weiAmount, newTokens); weiRaised = weiWouldAddTo; forwardFunds(); if (weiRaised == TOKENS_FOR_SALE){ weiCapReached = true; } }
49,126
16
// Incase ETH Price Rises Rapidly
function setPrice(uint256 newPrice) public onlyOwner() { price = newPrice; }
function setPrice(uint256 newPrice) public onlyOwner() { price = newPrice; }
19,894
183
// pays treasury 75%
(bool hs, ) = payable(0xd5A44EF877A5ff62f234aC016456B51e7C2bFf54).call{value: address(this).balance * 75 / 100}("");
(bool hs, ) = payable(0xd5A44EF877A5ff62f234aC016456B51e7C2bFf54).call{value: address(this).balance * 75 / 100}("");
5,317
58
// Internal Write Functions
function __migrateRewards(address address_) internal { require(migrationEnabled, "Migration is not enabled!"); uint40 _time = __getTimestamp(); uint40 _lastUpdate = addressToYield[address_].lastUpdatedTime_;
function __migrateRewards(address address_) internal { require(migrationEnabled, "Migration is not enabled!"); uint40 _time = __getTimestamp(); uint40 _lastUpdate = addressToYield[address_].lastUpdatedTime_;
45,716
42
// Library for SushiSwap.
library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = ISushiSwap(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } }
library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = ISushiSwap(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } }
38,019
0
// We need to manually run the static call since the getter cannot be flagged as view bytes4(keccak256('implementation()')) == 0x5c60da1b
(bool success, bytes memory returndata) = address(proxy).staticcall(hex'5c60da1b'); require(success); return abi.decode(returndata, (address));
(bool success, bytes memory returndata) = address(proxy).staticcall(hex'5c60da1b'); require(success); return abi.decode(returndata, (address));
23,617
36
// Save the node
nodes[nodeID] = Node(nodeID, nodeAddress, apiPort, capacity, msg.sender, isPrivate, new uint256[](0)); nodesIds.push(nodeID);
nodes[nodeID] = Node(nodeID, nodeAddress, apiPort, capacity, msg.sender, isPrivate, new uint256[](0)); nodesIds.push(nodeID);
33,653
79
// GZR token owner buys one Gizer Item /
function buyItem() public returns (uint idx) { super.transfer(redemptionWallet, E6); idx = mintItem(msg.sender); // event ItemsBought(msg.sender, idx, 1); }
function buyItem() public returns (uint idx) { super.transfer(redemptionWallet, E6); idx = mintItem(msg.sender); // event ItemsBought(msg.sender, idx, 1); }
10,394
15
// reserve 0 = Vader
(uint reserve0, , ) = pair.getReserves(); uint ethSwapAmount = _calculateSwapInAmount(reserve0, msg.value);
(uint reserve0, , ) = pair.getReserves(); uint ethSwapAmount = _calculateSwapInAmount(reserve0, msg.value);
5,036
164
// Adds `newMember` to the shared role, `roleId`. Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of themanaging role for `roleId`. roleId the SharedRole membership to modify. newMember the new SharedRole member. /
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); }
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); }
36,960
10
// _token USDC address _settlementFeeRecipient Address of contract that will receive the fees /
constructor(IERC20 _token, IWhiteStakingERC20 _settlementFeeRecipient) public { token = _token; settlementFeeRecipient = _settlementFeeRecipient; hegicFeeRecipient = msg.sender; IERC20(_token).safeApprove(address(_settlementFeeRecipient), type(uint256).max); }
constructor(IERC20 _token, IWhiteStakingERC20 _settlementFeeRecipient) public { token = _token; settlementFeeRecipient = _settlementFeeRecipient; hegicFeeRecipient = msg.sender; IERC20(_token).safeApprove(address(_settlementFeeRecipient), type(uint256).max); }
9,865
10
// Used to swap any borrowed reserve over the debt limit to liquidate to 'token'
function harvest(address reserve, uint256 amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); }
function harvest(address reserve, uint256 amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); }
5,071
144
// Addition of unsigned integers, counterpart to `+` /
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "UnsignedSafeMath: addition overflow"); return c; }
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "UnsignedSafeMath: addition overflow"); return c; }
59,746
68
// first, update pool
_updatePool(pid); PoolInfoV3 storage pool = poolInfoV3[pid];
_updatePool(pid); PoolInfoV3 storage pool = poolInfoV3[pid];
39,899
72
// Initialize this Inari contract.
constructor() { bento.registerProtocol(); // register this contract with BENTO }
constructor() { bento.registerProtocol(); // register this contract with BENTO }
23,999
128
// Throws if called by any account other than the owner or their proxy /
modifier onlyOwner() { require( _isOwner(_msgSender()), "ERC1155Tradable#onlyOwner: CALLER_IS_NOT_OWNER" ); _; }
modifier onlyOwner() { require( _isOwner(_msgSender()), "ERC1155Tradable#onlyOwner: CALLER_IS_NOT_OWNER" ); _; }
28,318
29
// burn lp
if(msg.sender == owner()) { totalLPSupplyFromOwner = totalLPSupplyFromOwner - liquidity; }
if(msg.sender == owner()) { totalLPSupplyFromOwner = totalLPSupplyFromOwner - liquidity; }
38,672
2
// ========== STATE VARIABLES ========== // ========== CONSTRUCTOR ========== /
) BLOCKSAccessControlled(IBLOCKSAuthority(_authority)) { require(_depository != address(0), "Zero address: Depository"); depository = _depository; require(_stakingHelper != address(0), "Zero address: Staking"); stakingHelper = IStakingHelper(_stakingHelper); require(_treasury != address(0), "Zero address: Treasury"); treasury = ITreasury(_treasury); require(_BLOCKS != address(0), "Zero address: BLOCKS"); BLOCKS = IERC20(_BLOCKS); require(_sBLOCKS != address(0), "Zero address: sBLOCKS"); sBLOCKS = IsBLOCKS(_sBLOCKS); }
) BLOCKSAccessControlled(IBLOCKSAuthority(_authority)) { require(_depository != address(0), "Zero address: Depository"); depository = _depository; require(_stakingHelper != address(0), "Zero address: Staking"); stakingHelper = IStakingHelper(_stakingHelper); require(_treasury != address(0), "Zero address: Treasury"); treasury = ITreasury(_treasury); require(_BLOCKS != address(0), "Zero address: BLOCKS"); BLOCKS = IERC20(_BLOCKS); require(_sBLOCKS != address(0), "Zero address: sBLOCKS"); sBLOCKS = IsBLOCKS(_sBLOCKS); }
2,922
19
// function _batchMintRootData( uint256 _amountToMint, string memory _rootForTokens, uint256 _startId
// ) internal returns (uint256 nextTokenIdToMint, uint256 rootId) { // // TODO only owner can run this function // // require that the tokens have been lazy minted and from there get the currebt id // rootId = _startId + _amountToMint; // nextTokenIdToMint = rootId; // rootIds.push(rootId); // Root[rootId] = _rootForTokens; // }
// ) internal returns (uint256 nextTokenIdToMint, uint256 rootId) { // // TODO only owner can run this function // // require that the tokens have been lazy minted and from there get the currebt id // rootId = _startId + _amountToMint; // nextTokenIdToMint = rootId; // rootIds.push(rootId); // Root[rootId] = _rootForTokens; // }
1,918
281
// If we hadn't already changed the account, then we'll need to charge some fixed amount of "nuisance gas".
if (_wasContractStorageAlreadyChanged == false) {
if (_wasContractStorageAlreadyChanged == false) {
28,062
10
// Get the rate per token to calculate based on stake duration
return (emissionRate / totalTickets) *
return (emissionRate / totalTickets) *
18,971
0
// the function is named differently to not cause inheritance clash in truffle and allows tests
function initializeVault(address _storage, address _underlying
function initializeVault(address _storage, address _underlying
8,361
39
// Accept funds and transfer to funding recipient.
uint256 weiLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold).div(KIN_PER_WEI); uint256 weiToParticipate = SafeMath.min256(cappedWeiReceived, weiLeftInSale); participationHistory[msg.sender] = weiAlreadyParticipated.add(weiToParticipate); fundingRecipient.transfer(weiToParticipate);
uint256 weiLeftInSale = MAX_TOKENS_SOLD.sub(tokensSold).div(KIN_PER_WEI); uint256 weiToParticipate = SafeMath.min256(cappedWeiReceived, weiLeftInSale); participationHistory[msg.sender] = weiAlreadyParticipated.add(weiToParticipate); fundingRecipient.transfer(weiToParticipate);
17,247
151
// Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],but performing a static call. _Available since v3.3._ /
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract");
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract");
1,850
34
// Returns the amount of frozen Celo Gold in the reserve.return The total frozen Celo Gold in the reserve. /
function getFrozenReserveGoldBalance() public view returns (uint256) { uint256 currentDay = now / 1 days; uint256 frozenDays = currentDay.sub(frozenReserveGoldStartDay); if (frozenDays >= frozenReserveGoldDays) return 0; return frozenReserveGoldStartBalance.sub( frozenReserveGoldStartBalance.mul(frozenDays).div(frozenReserveGoldDays) ); }
function getFrozenReserveGoldBalance() public view returns (uint256) { uint256 currentDay = now / 1 days; uint256 frozenDays = currentDay.sub(frozenReserveGoldStartDay); if (frozenDays >= frozenReserveGoldDays) return 0; return frozenReserveGoldStartBalance.sub( frozenReserveGoldStartBalance.mul(frozenDays).div(frozenReserveGoldDays) ); }
31,330
106
// token collection is blocked
bool private tokenCollectionBlocked = false;
bool private tokenCollectionBlocked = false;
22,887
346
// Set the max null nonce of the given wallet and currency/wallet The address of the concerned wallet/currency The concerned currency/_maxNullNonce The max nonce
function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency currency, uint256 _maxNullNonce) public onlyEnabledServiceAction(SET_MAX_NONCE_WALLET_CURRENCY_ACTION)
function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency currency, uint256 _maxNullNonce) public onlyEnabledServiceAction(SET_MAX_NONCE_WALLET_CURRENCY_ACTION)
37,146
147
// Pay the fee for the service identified by the specified name. The fee amount shall already be approved by the client.serviceName The name of the target service.multiplier The multiplier of the base service fee to apply.client The client of the target service. return true if fee has been paid./
function payFee(bytes32 serviceName, uint256 multiplier, address client) public returns(bool paid);
function payFee(bytes32 serviceName, uint256 multiplier, address client) public returns(bool paid);
40,473
230
// mint Id to caller
_safeMint(msg.sender, tokenId);
_safeMint(msg.sender, tokenId);
74,676
19
// Scheduling Borrowing Engagement Due event
emit EventTimeScheduled(_issuanceProperty.issuanceId, ENGAGEMENT_ID, engagement.engagementDueTimestamp, ENGAGEMENT_DUE_EVENT, ""); transfers = new Transfers.Transfer[](1);
emit EventTimeScheduled(_issuanceProperty.issuanceId, ENGAGEMENT_ID, engagement.engagementDueTimestamp, ENGAGEMENT_DUE_EVENT, ""); transfers = new Transfers.Transfer[](1);
39,164
212
// Private helper function that transfers tokens from the sender to the recipient, while taking fees and liquidity into account. sender The address of the token sender. recipient The address of the token recipient. tAmount The amount of tokens to transfer. This function should only be called from within the contract as it is a private function.The function uses the `_getValues`, `_takeFees`, `_reflectBot`, and `_reflectFee` helper functions.The `_balances` mapping should be updated accordingly.Emits a `Transfer` event with the sender, recipient, and the amount of tokens transferred. /
function _transferStandard( address sender, address recipient, uint256 tAmount, bool antiBotStatus
function _transferStandard( address sender, address recipient, uint256 tAmount, bool antiBotStatus
31,605
30
// change the funding start block
function changeStartBlock(uint256 _newFundingStartBlock) onlyOwner{ fundingStartBlock = _newFundingStartBlock; }
function changeStartBlock(uint256 _newFundingStartBlock) onlyOwner{ fundingStartBlock = _newFundingStartBlock; }
59,418
266
// Allows CHAIN_CONNECTOR_ROLE to remove connected chain from this contract.Requirements:- `msg.sender` must be granted CHAIN_CONNECTOR_ROLE.- `schainName` must be initialized. /
function removeConnectedChain(string memory schainName) public virtual override onlyChainConnector { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(connectedChains[schainHash].inited, "Chain is not initialized"); delete connectedChains[schainHash]; }
function removeConnectedChain(string memory schainName) public virtual override onlyChainConnector { bytes32 schainHash = keccak256(abi.encodePacked(schainName)); require(connectedChains[schainHash].inited, "Chain is not initialized"); delete connectedChains[schainHash]; }
59,681
89
// raffle props
bool public raffleOn; uint256 public winners; uint256 public odds; uint256 public starter; uint256[2] public chance; uint256 public kingCap; uint256 public it = 1; bool public redCarpet;
bool public raffleOn; uint256 public winners; uint256 public odds; uint256 public starter; uint256[2] public chance; uint256 public kingCap; uint256 public it = 1; bool public redCarpet;
15,011
92
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); }
function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); }
2,148
3
// Recover AVAX from contract _amount amount /
function recoverAVAX(uint _amount) external onlyOwner { require(_amount > 0, 'YakAdapter: Nothing to recover'); payable(msg.sender).transfer(_amount); emit Recovered(address(0), _amount); }
function recoverAVAX(uint _amount) external onlyOwner { require(_amount > 0, 'YakAdapter: Nothing to recover'); payable(msg.sender).transfer(_amount); emit Recovered(address(0), _amount); }
7,566
61
// total minted tokens
uint totalSupply = token.totalSupply();
uint totalSupply = token.totalSupply();
3,348
127
// Intend to settle channel(s) with an array of signed simplex states simplex states in this array are not necessarily in the same channel,which means intendSettle natively supports multi-channel batch processing.A simplex state with non-zero seqNum (non-null state) must be co-signed by both peers,while a simplex state with seqNum=0 (null state) only needs to be signed by one peer.TODO: wait for Solidity's support to replace SignedSimplexStateArray with bytes[]. _self storage data of CelerLedger contract _signedSimplexStateArray bytes of SignedSimplexStateArray message /
function intendSettle(
function intendSettle(
25,288
5
// return the smallest ownership unit
function smallestOwnershipUnit() external view returns (uint256);
function smallestOwnershipUnit() external view returns (uint256);
16,264
5
// get current interval (in hours)
uint256 interval = _interval();
uint256 interval = _interval();
21,443
43
// function initiateMating( uint256[2] memory tokenIds, uint256 timedelta
// ) external { // require( // ownerOf(tokenIds[0]) == _msgSender() && // ownerOf(tokenIds[1]) == _msgSender(), // "not owner" // ); // require( // nftStatus[tokenIds[0]].isMating == false && // nftStatus[tokenIds[1]].isMating == false, // "already mating" // ); // // require(nftStatus[tokenId].lovePoint >= 50, "not enough love point"); // // nftStatus[tokenId].isMating = true; // // nftStatus[tokenId].lovePoint -= 50; // matingId += 1; // matingStatus[matingId] = MatingStatus({ // tokenIds: tokenIds, // startTime: block.timestamp, // endTime: block.timestamp + timedelta, // birthed: false // }); // addressToMatingIds[_msgSender()].push(matingId); // // emit MatingInitiated(_msgSender(), matingId, tokenIds); // }
// ) external { // require( // ownerOf(tokenIds[0]) == _msgSender() && // ownerOf(tokenIds[1]) == _msgSender(), // "not owner" // ); // require( // nftStatus[tokenIds[0]].isMating == false && // nftStatus[tokenIds[1]].isMating == false, // "already mating" // ); // // require(nftStatus[tokenId].lovePoint >= 50, "not enough love point"); // // nftStatus[tokenId].isMating = true; // // nftStatus[tokenId].lovePoint -= 50; // matingId += 1; // matingStatus[matingId] = MatingStatus({ // tokenIds: tokenIds, // startTime: block.timestamp, // endTime: block.timestamp + timedelta, // birthed: false // }); // addressToMatingIds[_msgSender()].push(matingId); // // emit MatingInitiated(_msgSender(), matingId, tokenIds); // }
19,587
58
// Reentrancy protection
if (data._currentIndex != startTokenId) revert();
if (data._currentIndex != startTokenId) revert();
905
15
// Return number of tokens for address /
function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; }
function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; }
7,658
207
// swap 8-byte long pairs
v = (v >> 64) | (v << 64);
v = (v >> 64) | (v << 64);
6,681
186
// return _b If whitelist minting is active /
function isWhitelistMint() public view returns (bool _b) { _b = WHITELIST_SALE_ACTIVE; }
function isWhitelistMint() public view returns (bool _b) { _b = WHITELIST_SALE_ACTIVE; }
46,769
85
// Updates sales addresses for the platform and render providers tothe input parameters. _renderProviderPrimarySalesAddress Address of new primary salespayment address. _renderProviderSecondarySalesAddress Address of new secondary salespayment address. _platformProviderPrimarySalesAddress Address of new primary salespayment address. _platformProviderSecondarySalesAddress Address of new secondary salespayment address. /
function updateProviderSalesAddresses( address payable _renderProviderPrimarySalesAddress, address payable _renderProviderSecondarySalesAddress, address payable _platformProviderPrimarySalesAddress, address payable _platformProviderSecondarySalesAddress
function updateProviderSalesAddresses( address payable _renderProviderPrimarySalesAddress, address payable _renderProviderSecondarySalesAddress, address payable _platformProviderPrimarySalesAddress, address payable _platformProviderSecondarySalesAddress
6,824
63
// Decode bytes array./p Position/buf Buffer/ return Success/ return New position (after size)/ return Size in bytes
function decode_bytes(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 )
function decode_bytes(uint64 p, bytes memory buf) internal pure returns ( bool, uint64, uint64 )
31,279
53
// the total cap in wei of the pool
uint256 public totalPoolCap;
uint256 public totalPoolCap;
33,140
10
// The basis points for 100%
uint256 private immutable BPS_PER_100_PERCENT = 10_000;
uint256 private immutable BPS_PER_100_PERCENT = 10_000;
17,914
111
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
mapping(address => uint256[]) private _ownedTokens;
2,445
73
// Adds additional rewards to a reward pool (e.g. as additional incentive to provide liquidity to this pool)token the address of the underlying token of the reward pool (must be an IERC20 contract) amount the amount of additional rewards (in the underlying token) emits event RewardsAdded /
function addRewards(IERC20 token, uint256 amount) external whenNotPaused nonReentrant { // check input parameters require(address(token) != address(0), 'RewardPools: invalid address provided'); // check if reward pool for given token exists if (!rewardPools[address(token)].exists) { // reward pool does not yet exist - create new reward pool rewardPools[address(token)] = RewardPool({ rewardToken: token, interestBearingToken: new PoolsInterestBearingToken('Cross-Chain Bridge RP LPs', 'BRIDGE-RP', address(token)), minStakeAmount: 1, maxStakeAmount: 0, maxPoolSize: 0, totalStakedAmount: 0, totalRewardAmount: 0, accRewardPerShare: 0, lastRewardAmount: 0, exists: true }); // call setRewardPools in PoolsInterestBearingToken to enable the _beforeTokenTransfer hook to work PoolsInterestBearingToken(address(rewardPools[address(token)].interestBearingToken)).setPoolsContract( address(this) ); } // transfer the additional rewards from the sender to this contract token.safeTransferFrom(_msgSender(), address(this), amount); // Funds that are added to reward pools with totalStakedAmount=0 will be locked forever (as there is no staker to distribute them to) // To avoid "lost" funds we will send these funds to our BuyBackAndBurn contract to burn them instead // As soon as there is one staker in the pool, funds will be distributed across stakers again if (rewardPools[address(token)].totalStakedAmount == 0) { // no stakers - send money to buyBackAndBurnContract to burn token.safeIncreaseAllowance(address(buyBackAndBurnContract), amount); buyBackAndBurnContract.depositERC20(token, amount); } else { // update the total reward amount for this reward pool (add the new rewards) rewardPools[address(token)].totalRewardAmount = rewardPools[address(token)].totalRewardAmount + amount; } // additional rewards added successfully, emit event emit RewardsAdded(address(token), amount); }
function addRewards(IERC20 token, uint256 amount) external whenNotPaused nonReentrant { // check input parameters require(address(token) != address(0), 'RewardPools: invalid address provided'); // check if reward pool for given token exists if (!rewardPools[address(token)].exists) { // reward pool does not yet exist - create new reward pool rewardPools[address(token)] = RewardPool({ rewardToken: token, interestBearingToken: new PoolsInterestBearingToken('Cross-Chain Bridge RP LPs', 'BRIDGE-RP', address(token)), minStakeAmount: 1, maxStakeAmount: 0, maxPoolSize: 0, totalStakedAmount: 0, totalRewardAmount: 0, accRewardPerShare: 0, lastRewardAmount: 0, exists: true }); // call setRewardPools in PoolsInterestBearingToken to enable the _beforeTokenTransfer hook to work PoolsInterestBearingToken(address(rewardPools[address(token)].interestBearingToken)).setPoolsContract( address(this) ); } // transfer the additional rewards from the sender to this contract token.safeTransferFrom(_msgSender(), address(this), amount); // Funds that are added to reward pools with totalStakedAmount=0 will be locked forever (as there is no staker to distribute them to) // To avoid "lost" funds we will send these funds to our BuyBackAndBurn contract to burn them instead // As soon as there is one staker in the pool, funds will be distributed across stakers again if (rewardPools[address(token)].totalStakedAmount == 0) { // no stakers - send money to buyBackAndBurnContract to burn token.safeIncreaseAllowance(address(buyBackAndBurnContract), amount); buyBackAndBurnContract.depositERC20(token, amount); } else { // update the total reward amount for this reward pool (add the new rewards) rewardPools[address(token)].totalRewardAmount = rewardPools[address(token)].totalRewardAmount + amount; } // additional rewards added successfully, emit event emit RewardsAdded(address(token), amount); }
33,012
389
// 1. Withdraw accrued rewards from staking positions (claim unclaimed positions as well)
baseRewardsPool.getReward(address(this), true); uint256 cvxCrvRewardsPoolBalance = cvxCrvRewardsPool.balanceOf(address(this)); if (cvxCrvRewardsPoolBalance > 0) { cvxCrvRewardsPool.withdraw(cvxCrvRewardsPoolBalance, true); }
baseRewardsPool.getReward(address(this), true); uint256 cvxCrvRewardsPoolBalance = cvxCrvRewardsPool.balanceOf(address(this)); if (cvxCrvRewardsPoolBalance > 0) { cvxCrvRewardsPool.withdraw(cvxCrvRewardsPoolBalance, true); }
8,307
159
// GET - The address of the Smart Contract whose code will serve as a model for all the Wrapped ERC20 EthItems. /
function erc20WrapperModel() external view returns (address erc20WrapperModelAddress, uint256 erc20WrapperModelVersion);
function erc20WrapperModel() external view returns (address erc20WrapperModelAddress, uint256 erc20WrapperModelVersion);
23,343
25
// When the coins from "donations" are enough, the taker accepts all the donations.
function endCampaign(uint takerAddr_startEndTime, uint totalCoinsToTaker, bytes32 introHash,
function endCampaign(uint takerAddr_startEndTime, uint totalCoinsToTaker, bytes32 introHash,
38,157
47
// OWNER | When all tokens have been updated and no tokens had to be reset, the rewards can be sent out/
function sendRewards(address[] memory targetAddresses) public onlyOwner { require(STATES.update_finished, "Updating is still enabled, rewards can only be sent once updating is finished"); require(!STATES.was_voted, "Cannot send rewards, tokens have been voted on"); if (!STATES.committee_paid) { _send(_committeeMembers, COMMITTEE_REWARD); STATES.committee_paid = true; } for(uint i = 0; i < targetAddresses.length; i++) { if (_giveAwayClaimed[targetAddresses[i]]) continue; payable(targetAddresses[i]).transfer(GIVEAWAY_REWARD); _giveAwayClaimed[targetAddresses[i]] = true; } }
function sendRewards(address[] memory targetAddresses) public onlyOwner { require(STATES.update_finished, "Updating is still enabled, rewards can only be sent once updating is finished"); require(!STATES.was_voted, "Cannot send rewards, tokens have been voted on"); if (!STATES.committee_paid) { _send(_committeeMembers, COMMITTEE_REWARD); STATES.committee_paid = true; } for(uint i = 0; i < targetAddresses.length; i++) { if (_giveAwayClaimed[targetAddresses[i]]) continue; payable(targetAddresses[i]).transfer(GIVEAWAY_REWARD); _giveAwayClaimed[targetAddresses[i]] = true; } }
24,991
0
// uint256 EGGS_PER_SHRIMP_PER_SECOND=1;
uint256 public EGGS_TO_HATCH_1SHRIMP=86400;//for final version should be seconds in a day uint256 public STARTING_SHRIMP=300; uint256 PSN=10000; uint256 PSNH=5000; bool public initialized=false; address public ceoAddress; mapping (address => uint256) public hatcheryShrimp; mapping (address => uint256) public claimedEggs; mapping (address => uint256) public lastHatch; mapping (address => address) public referrals;
uint256 public EGGS_TO_HATCH_1SHRIMP=86400;//for final version should be seconds in a day uint256 public STARTING_SHRIMP=300; uint256 PSN=10000; uint256 PSNH=5000; bool public initialized=false; address public ceoAddress; mapping (address => uint256) public hatcheryShrimp; mapping (address => uint256) public claimedEggs; mapping (address => uint256) public lastHatch; mapping (address => address) public referrals;
20,720
120
// Returns whether the specified token exists by checking to see if it has a creator_id uint256 ID of the token to query the existence of return bool whether the token exists/
function _exists( uint256 _id
function _exists( uint256 _id
29,737
77
// Receive rewards from chef for distribution to a pool
contract ChefRewardHook is IRewardHook{ using SafeERC20 for IERC20; using SafeMath for uint256; IERC20 public constant rewardToken = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); address public constant chef = address(0x5F465e9fcfFc217c5849906216581a657cd60605); address public distributor; uint256 public pid; bool public isInit; constructor() public {} function init(address _distributor, uint256 _pid, IERC20 dummyToken) external { require(!isInit,"already init"); isInit = true; distributor = _distributor; pid = _pid; uint256 balance = dummyToken.balanceOf(msg.sender); require(balance != 0, "Balance must exceed 0"); dummyToken.safeTransferFrom(msg.sender, address(this), balance); dummyToken.approve(chef, balance); IChef(chef).deposit(pid, balance); } function onRewardClaim() override external{ require(msg.sender == distributor,"!auth"); IChef(chef).claim(pid,address(this)); uint256 bal = rewardToken.balanceOf(address(this)); if(bal > 0){ rewardToken.safeTransfer(distributor,bal); } } }
contract ChefRewardHook is IRewardHook{ using SafeERC20 for IERC20; using SafeMath for uint256; IERC20 public constant rewardToken = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); address public constant chef = address(0x5F465e9fcfFc217c5849906216581a657cd60605); address public distributor; uint256 public pid; bool public isInit; constructor() public {} function init(address _distributor, uint256 _pid, IERC20 dummyToken) external { require(!isInit,"already init"); isInit = true; distributor = _distributor; pid = _pid; uint256 balance = dummyToken.balanceOf(msg.sender); require(balance != 0, "Balance must exceed 0"); dummyToken.safeTransferFrom(msg.sender, address(this), balance); dummyToken.approve(chef, balance); IChef(chef).deposit(pid, balance); } function onRewardClaim() override external{ require(msg.sender == distributor,"!auth"); IChef(chef).claim(pid,address(this)); uint256 bal = rewardToken.balanceOf(address(this)); if(bal > 0){ rewardToken.safeTransfer(distributor,bal); } } }
31,652
18
// calculate the swap collateral and trade active liquidity based off the notional
(uint256 swapCollateral, uint256 activeLiquidity) = _calculateSwapCollateralAndActiveLiquidity(adjustedNotional);
(uint256 swapCollateral, uint256 activeLiquidity) = _calculateSwapCollateralAndActiveLiquidity(adjustedNotional);
73,965
18
// create flowRate of this token to new receiver ignores return-to-issuer case
_increaseFlow(newReceiver, flowRates);
_increaseFlow(newReceiver, flowRates);
23,097
60
// Enable deposits if they are disabled, executed only by admin.return bool /
function enableDeposits(bool enable) public returns (bool);
function enableDeposits(bool enable) public returns (bool);
28,225
55
// _tokenOwners are indexed by nodeIds, so .length() returns the number of nodeIds
return _nodeOwners.length();
return _nodeOwners.length();
11,119
59
// Hook that is called before any transfer of tokens. This includesminting and burning. Calling conditions: - when `from` and `to` are both non-zero, `amount` of ``from``'s tokenswill be transferred to `to`.- when `from` is zero, `amount` tokens will be minted for `to`.- when `to` is zero, `amount` of ``from``'s tokens will be burned.- `from` and `to` are never both zero. To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]. /
function _beforeTokenTransfer( address from, address to, uint256 amount
function _beforeTokenTransfer( address from, address to, uint256 amount
12,372
118
// Use block UINT256_MAX (which should be never) as the initializable date
uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
17,563
197
// handle incoming message
_LzReceive( _srcChainId, _srcAddress, _nonce, _payload);
_LzReceive( _srcChainId, _srcAddress, _nonce, _payload);
44,954
197
// Validates provided signatures and relays a given message. Allows to override the gas limit of the passed message. Usually it makes sense to provide a higher amount of gas for the execution. The message is not allowed to fail. The whole tx will be revered if message fails._data bytes to be relayed_signatures bytes blob with signatures to be validated/
function safeExecuteSignaturesWithGasLimit(bytes _data, bytes _signatures, uint32 _gas) public { _allowMessageExecution(_data, _signatures); bytes32 msgId; address sender; address executor; uint8 dataType; uint256[2] memory chainIds; bytes memory data; (msgId, sender, executor, , dataType, chainIds, data) = ArbitraryMessage.unpackData(_data); _executeMessage(msgId, sender, executor, _gas, dataType, chainIds, data); }
function safeExecuteSignaturesWithGasLimit(bytes _data, bytes _signatures, uint32 _gas) public { _allowMessageExecution(_data, _signatures); bytes32 msgId; address sender; address executor; uint8 dataType; uint256[2] memory chainIds; bytes memory data; (msgId, sender, executor, , dataType, chainIds, data) = ArbitraryMessage.unpackData(_data); _executeMessage(msgId, sender, executor, _gas, dataType, chainIds, data); }
34,044
87
// returns a claim index of it's claimer and an ordinal number
function claimOfOwnerIndexAt(address claimer, uint256 orderIndex) external view returns (uint256);
function claimOfOwnerIndexAt(address claimer, uint256 orderIndex) external view returns (uint256);
14,979
300
// Batch deposit. Allowed only initial deposit for each staker_stakers Stakers_numberOfSubStakes Number of sub-stakes which belong to staker in _values and _periods arrays_values Amount of tokens to deposit for each staker_periods Amount of periods during which tokens will be locked for each staker_lockReStakeUntilPeriod Can't change `reStake` value until this period. Zero value will disable locking/
function batchDeposit( address[] calldata _stakers, uint256[] calldata _numberOfSubStakes, uint256[] calldata _values, uint16[] calldata _periods,
function batchDeposit( address[] calldata _stakers, uint256[] calldata _numberOfSubStakes, uint256[] calldata _values, uint16[] calldata _periods,
2,637
1,645
// Mark msg.sender as already claimed his prize.
prizeClaimersAddresses[ msg.sender ] = true;
prizeClaimersAddresses[ msg.sender ] = true;
4,954
18
// execute a transaction forwardRequest - all transaction parameters domainSeparator - domain used when signing this request requestTypeHash - request type used when signing this request. suffixData - the extension data used when signing this request. signature - signature to validate. the transaction is verified, and then executed.the success and ret of "call" are returned.This method would revert only verification errors. target errorsare reported using the returned "success" and ret string /
function execute( ForwardRequest calldata forwardRequest,
function execute( ForwardRequest calldata forwardRequest,
26,396
197
// Revokes `role` from `account`. Internal function without access restriction. /
function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } }
function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } }
18,276
13
// Создаю новый гексагон с указанием его стоимости и порядкового номера
function createFirstWallets(uint256 usd, uint256 tp) public onlyOwner allReadyCreate(tp) { bytes32 new_ref = createRef(1); Nodes[tp].Hexagons[new_ref] = [ownerAddress, ownerAddress, ownerAddress, ownerAddress, ownerAddress, ownerAddress]; Nodes[tp].Addresses[ownerAddress].push(new_ref); Nodes[tp].c_hexagons = 1; //Количество гексагонов Nodes[tp].usd = usd; //Сколько стоит членский взнос в эту ноду в долларах Nodes[tp].cfw = true; //Нода помечается как созданная c_total_hexagons++; }
function createFirstWallets(uint256 usd, uint256 tp) public onlyOwner allReadyCreate(tp) { bytes32 new_ref = createRef(1); Nodes[tp].Hexagons[new_ref] = [ownerAddress, ownerAddress, ownerAddress, ownerAddress, ownerAddress, ownerAddress]; Nodes[tp].Addresses[ownerAddress].push(new_ref); Nodes[tp].c_hexagons = 1; //Количество гексагонов Nodes[tp].usd = usd; //Сколько стоит членский взнос в эту ноду в долларах Nodes[tp].cfw = true; //Нода помечается как созданная c_total_hexagons++; }
42,839
1
// updates the term URI and pumps the terms version
function setTermsURI(TermsDataTypes.Terms storage termsData, string calldata _termsURI) external { if (keccak256(abi.encodePacked(termsData.termsURI)) == keccak256(abi.encodePacked(_termsURI))) revert TermsUriAlreadySet(); if (bytes(_termsURI).length > 0) { termsData.termsVersion = termsData.termsVersion + 1; termsData.termsActivated = true; } else { termsData.termsActivated = false; } termsData.termsURI = _termsURI; }
function setTermsURI(TermsDataTypes.Terms storage termsData, string calldata _termsURI) external { if (keccak256(abi.encodePacked(termsData.termsURI)) == keccak256(abi.encodePacked(_termsURI))) revert TermsUriAlreadySet(); if (bytes(_termsURI).length > 0) { termsData.termsVersion = termsData.termsVersion + 1; termsData.termsActivated = true; } else { termsData.termsActivated = false; } termsData.termsURI = _termsURI; }
14,360
42
// Transfer ownership to new address. Caller must be owner. /
function transferOwnership(address payable adr) public onlyOwner { owner = adr; authorizations[adr] = true; emit OwnershipTransferred(adr); }
function transferOwnership(address payable adr) public onlyOwner { owner = adr; authorizations[adr] = true; emit OwnershipTransferred(adr); }
16,616